猫咪家
首页
分类
标签
归档
关于
管理员
2022-01-09
1814
SpringSecurity 自定义用户密码验证
```java 1.自定义AuthenticationProvider @Component public class MyAuthenticationProvider implements AuthenticationProvider { @Autowired private ZPasswordEncoder zPasswordEncoder; @Autowired private EnCode enCode; @Autowired private UserMapper userMapper; @SneakyThrows @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String presentedPassword = (String)authentication.getCredentials(); UserDetails userDeatils = null; // 根据用户名获取用户信息 User sysUser = userMapper.loadUserByUsername(username); if (sysUser==null) { throw new BadCredentialsException("用户名不存在"); } else { userDeatils = new User(username, sysUser.getPassword()); // 自定义的加密规则,用户名、输的密码和数据库保存的盐值进行加密 ResutlInfo encodedPassword = enCode.doEncode(username, presentedPassword);//自定义的加密方法加密 if (authentication.getCredentials() == null) { throw new BadCredentialsException("登录名或密码错误"); } else if (!this.zPasswordEncoder.matches(encodedPassword.getData(), userDeatils.getPassword())) { throw new BadCredentialsException("登录名或密码错误"); } else { UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(userDeatils, authentication.getCredentials(), userDeatils.getAuthorities()); result.setDetails(authentication.getDetails()); return result; } } } @Override public boolean supports(Class<?> authentication) { return true; } } 2.自定义PasswordEncoder @Component public class ZPasswordEncoder implements PasswordEncoder { @SneakyThrows @Override public String encode(CharSequence rawPassword) { return null; } @SneakyThrows @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { return (rawPassword.equals(encodedPassword)); } } 3.WebSecurity设置 @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserService userService; @Autowired private MyAuthenticationProvider myAuthenticationProvider; @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(myAuthenticationProvider); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/testxx","/index","/layui/**", "/layui/css/**", "/js/**", "/css/**", "** /images/**", "/fonts/**", "/doc/**", "/static/**").permitAll() .antMatchers("/login").permitAll().anyRequest().authenticated() .and().formLogin() .loginPage("/login").permitAll() .loginProcessingUrl("/login") // .successForwardUrl("/index") .defaultSuccessUrl("/", true) .failureUrl("/loginfail") .and().logout().logoutUrl("/logout").clearAuthentication(true).logoutSuccessUrl("/userlogin"); // http.cors(); // http.csrf().disable(); http.headers().frameOptions().disable(); // http.authorizeRequests().anyRequest().permitAll(); } } 2. ```
###Hello world!
Java
评论
发布
留言
评论