美文网首页
Spring Security开发基于表单的认证

Spring Security开发基于表单的认证

作者: Burning_6c93 | 来源:发表于2019-02-06 12:49 被阅读0次

SpringSecurity核心功能

  1. 认证(你是谁)
  2. 授权(你能干什么)
  3. 攻击防护(防止伪造身份)

SpringSecurity基本原理

image.png

自定义用户认证逻辑

  • 处理用户信息获取逻辑(实现UserDetailService接口)
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  private MyUserDetailService userDetailService;
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder());
//    springSecurity推荐使用BCrypt加密
      auth.userDetailsService(userDetailService).passwordEncoder(new BCryptPasswordEncoder());
  }
  @Override
  protected void configure(HttpSecurity http) throws Exception {
//        http.httpBasic()
      http.formLogin()
              .and()
              .authorizeRequests()
              .anyRequest()
              .authenticated();
      super.configure(http);
  }
}
@Component
@Slf4j
public class MyUserDetailService implements UserDetailsService {
  @Override
  public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
      log.info("登录用户名:{}", s);
//        根据用户名查找用户信息(根据各自实际需求来查找用户密码、权限等信息)
      return new User(s, new BCryptPasswordEncoder().encode("1234"), AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
  }
}
  • 处理用户校验逻辑(实现UserDetails接口,除了判断密码是否正确外,判断用户账号是否过期、冻结、删除等等)
@Component
@Slf4j
public class MyUserDetailService implements UserDetailsService {
  @Override
  public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
      log.info("登录用户名:{}", s);
//        根据用户名查找用户信息(根据各自实际需求来查找用户密码、权限等信息)
//        根据查找到的用户信息判断用户是否被冻结
      return new User(s, new BCryptPasswordEncoder().encode("1234"),true,true,true,false,AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
  }
}
  • 处理密码加密解密(实现PasswordEncoder接口,推荐BCrypt加密)
//配置类中注入加密类
@Bean
  public PasswordEncoder passwordEncoder(){
      return new BCryptPasswordEncoder();
  }
@Component
@Slf4j
public class MyUserDetailService implements UserDetailsService {
  @Autowired
  private PasswordEncoder passwordEncoder;
  @Override
  public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
      log.info("登录用户名:{}", s);
//        根据用户名查找用户信息(根据各自实际需求来查找用户密码、权限等信息)
//        根据查找到的用户信息判断用户是否被冻结
      String password = passwordEncoder.encode("1234");
      return new User(s, password, true, true, true, false, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
  }
}

相关文章

网友评论

      本文标题:Spring Security开发基于表单的认证

      本文链接:https://www.haomeiwen.com/subject/fjdvsqtx.html