自定义SpringSecurity----AuthenticationProvider(抽象认证技术可以根据业务需要进行拓展)

package com.zcw.demospringsecurity.demo6;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

/**
 * @ClassName : MyAuthenticationProvider
 * @Description :
 * @Author : Zhaocunwei
 * @Date: 2020-04-10 23:12
 */
@Component
public class MyAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails,
                                                  UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken)
        throws AuthenticationException{
        //校验密码
        if(usernamePasswordAuthenticationToken.getCredentials() ==null){
            throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",
                    "密码不能为空"));
        }else{
            String presentedPassword = usernamePasswordAuthenticationToken.getCredentials().toString();
            if (!presentedPassword.equals(userDetails.getPassword())){
                throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",
                        "密码错误"));
            }
        }
    }
    @Override
    protected UserDetails retrieveUser(String s,UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken)
        throws AuthenticationException{
        return userDetailsService.loadUserByUsername(s);
    }
}

发布了458 篇原创文章 · 获赞 15 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_32370913/article/details/105552267