若依免密登錄配置

一、在framework模塊下security包下新建config包,在包裏新建CustomLoginAuthenticationProvider.java類 繼承DaoAuthenticationProvider類重寫additionalAuthenticationChecks 方法

public class CustomLoginAuthenticationProvider extends DaoAuthenticationProvider {
    public CustomLoginAuthenticationProvider(UserDetailsService userDetailsService) {
        super();
        setUserDetailsService(userDetailsService);
    }
 
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if (authentication.getCredentials() == null) {
            this.logger.debug("Authentication failed: no credentials provided");
            throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        } else {
            String presentedPassword = authentication.getCredentials().toString();
            if(Constants.CUSTOM_LOGIN_SMS.equals(presentedPassword)){
                //免密登錄,不驗證密碼(還可以繼續擴展,只要傳進來的password標識即可)
            }else{
                BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
                if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
                    this.logger.debug("Authentication failed: password does not match stored value");
                    throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
                }
            }
        }
    }
}

二、在SecurityConfig.java包裏 修改身份認證方式

    /**
     * 身份認證接口
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(new CustomLoginAuthenticationProvider(userDetailsService));
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(bCryptPasswordEncoder());
    }

 

三、SysPasswordService.java類下的 matches 方法 新增跳過驗證方法 Constants.CUSTOM_LOGIN_SMS 同第二步一樣 隨意定義即可

public boolean matches(WebsiteUser user, String rawPassword)
    {
        if (rawPassword.equals(Constants.CUSTOM_LOGIN_SMS)){
            return true;
        }
        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
    }

 

然後使用原本的登錄 密碼用Constants.CUSTOM_LOGIN_SMS 即可登錄

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章