spring boot security学习
spring boot security(一)
配置认证和授权
通过继承WebSecurityConfigurerAdapter,可以重写其认证和授权的逻辑。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/*@Autowired
private DataSource dataSource;*/
//一个UserDetailService
@Autowired
private AppUserDetailService appUserDetailService;
//一个密码加密器
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//super.configure(http);
//配置不需要登陆验证
//http.authorizeRequests().anyRequest().permitAll().and().logout().permitAll();
//http.authorizeRequests().antMatchers("/").authenticated()‘
/*http.authorizeRequests()
.antMatchers("/Home").permitAll() //全部能访问
.antMatchers("/").hasRole("asdfa"); //必须有角色xxx
http.formLogin().loginPage("/tologin");
http.csrf().disable();
http.logout().logoutSuccessUrl("/");
//记住我
http.rememberMe();
*/
//home必须认证了才能通过
http.authorizeRequests().antMatchers("/home").authenticated();
//关闭csrf
http.csrf().disable();
//登录面跳转
http.formLogin().loginPage("/login")
.usernameParameter("username")
.passwordParameter("password")
.defaultSuccessUrl("/home") //登录成功跳转
.successForwardUrl("/home");
//登出跳转
http.logout().logoutSuccessUrl("/");
//rememberMe
http.rememberMe().rememberMeParameter("rememberme");
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
super.configure(auth);
//从数据库中读取
/*auth.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery("select * from admin where user = ?;")
.authoritiesByUsernameQuery("select * from admin where user = ?;")
.passwordEncoder(new BCryptPasswordEncoder());*/
//内存硬编码
/*auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("xxx").password("yyy").and()
.withUser("xxxf").password("yyd");*/
//自定义
auth.userDetailsService(appUserDetailService)
.passwordEncoder(bCryptPasswordEncoder);
}
}
实现UserDetailsService接口
@Service
public class AppUserDetailService implements UserDetailsService {
@Resource
private AdminMapping adminMapping;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("进入认证代码块");
Admin admin = adminMapping.selectByUsername(username);
System.out.println("匹配到的用户"+admin);
if (admin == null){
System.out.println("无用户");
return null;
}else {
//权限组
List<GrantedAuthority> list = AuthorityUtils.createAuthorityList("ADMIN");
User user = new User(admin.getUsername() ,admin.getPwd(),list);
System.out.println("查找到用户,传递给security进行认证");
return user;
}
}
}
注入bean
BCryptPasswordEncoder
@Configuration
public class Myconfig {
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
}
Encoded password does not look like BCrypt
数据库传递的密码没有经过BCrypt加密。
解决方法一:在注册的时候对密码进行BCrypt加密。
//自定义
auth.userDetailsService(appUserDetailService)
.passwordEncoder(bCryptPasswordEncoder);
//注册时密码用bCryptPasswordEncoder进行加密
AdminMapper.save(new Admin("tom",bCryptPasswordEncoder.encode("123456")));
//在userDetailsService返回封装后的UserDetails(User security内置的UserDetails接口实现类)
User user = new User(
admin.getUsername()
,admin.getPwd() //数据库中的经过加密的密码
,list);
//security框架会在后续的认证中利用bCryptPasswordEncoder的matches()方法进行对面
bCryptPasswordEncoder.matches(
"123456", //前端传递过来的密码
user.getPassword() //数据库里面经过加密的密码
)
There is no PasswordEncoder mapped for the id “null”
Spring security 5.0中新增了多种加密方式,在Spring security中为了确保密码的安全性,默认是需要对密码进行加密的。
官方文档中有描述加密方式是{id}encodedPassword,其中id是加密的方式
{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG
{noop}password
{pbkdf2}5d923b44a6d129f3ddf3e3c8d29412723dcbde72445e8ef6bf3b508fbf17fa4ed4d6b99ca763d8dc
{scrypt}$e0801$8bWJaSu2IKSn9Z9kM+TPXfOc/9bdYSrN1oD9qfVThWEwdRTnO7re7Ei+fUZRJ68k9lTyuTeUp4of4g24hHnazw==$OAOec05+bXxvuu/1qZ6NUR+xQYvYv7BeL1QxwRpY5Pc=
{sha256}97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)