自定义AuthenticationProvider

/**
 * @author Lengjx
 * @version 1.O.0
 * @date 2023/3/14 10:43
 */
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {

    /**
     * 自定义MD5 加密
     */
    @Autowired
    private MD5PasswordEncoder myPasswordEncoder;

    @Autowired
    private UserDetailsService userService;

    /**
     * 自定义验证方式
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //获取用户输入的用户名和密码
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        //通过获取的用户名,得到userDetails对象
        UserDetails user = userService.loadUserByUsername(username);

        //加密过程在这里体现,明文,密文
        if (!myPasswordEncoder.matches(password, user.getPassword())) {
            throw new UserPasswordNotMatchException();
        }

        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        return new UsernamePasswordAuthenticationToken(user, password, authorities);
    }

    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }

}

自定义 PasswordEncoder

实现加密|解密处理

@Component
public class MD5PasswordEncoder implements PasswordEncoder {

    @Override
    public String encode(CharSequence rawPassword) {
        return SymmetricCryptoUtil.encryptFromString(rawPassword.toString());
    }


    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        String password = SymmetricCryptoUtil.decryptFromString(encodedPassword);
        return ObjectUtil.equals(rawPassword, password);
    }
}

SecurityConfig加载自定义配置

 /**
     * 身份认证接口
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.authenticationProvider(authenticationProvider); 
    }

Security多线程下配置存储strategy模式调整

 // 启动类增加参数,,Security 多线程获取用户信息为空,设置子线程可查询数据;
 System.setProperty("spring.security.strategy","MODE_INHERITABLETHREADLOCAL");```


# RuoYi SecurityUtils工具类修改加密|解密方法
![工具类调整](https://img-blog.csdnimg.cn/d579c71e9e184656a671a40709606c54.jpeg#pic_center)

Logo

快速构建 Web 应用程序

更多推荐