当前位置: 代码网 > it编程>编程语言>Java > SpringSecurity 自定义认证登录的项目实践

SpringSecurity 自定义认证登录的项目实践

2024年08月18日 Java 我要评论
前言现在登录方式越来越多,传统的账号密码登录已经不能满足我们的需求。可能我们还需要手机验证码登录,邮箱验证码登录,一键登录等。这时候就需要我们自定义我们系统的认证登录流程,下面,我就一步一步在spri

前言

现在登录方式越来越多,传统的账号密码登录已经不能满足我们的需求。可能我们还需要手机验证码登录,邮箱验证码登录,一键登录等。这时候就需要我们自定义我们系统的认证登录流程,下面,我就一步一步在springsecurity 自定义认证登录,以手机验证码登录为例

1-自定义用户对象

spring security 中定义了 userdetails 接口来规范开发者自定义的用户对象,我们自定义对象直接实现这个接口,然后定义自己的对象属性即可

/**
 * 自定义用户角色
 */
@data
public class phoneuserdetails implements userdetails {

    public static final string account_active_status = "active";

    public static final integer not_expired = 0;

    private string userid;
    private string username;
    private string phone;
    private string status;
    private integer isexpired;

    @override
    public collection<? extends grantedauthority> getauthorities() {
        collection<grantedauthority> collection = new hashset<>();
        return collection;
    }

    @override
    public string getpassword() {
        return null;
    }

    @override
    public string getusername() {
        return this.phone;
    }

    @override
    public boolean isaccountnonexpired() {
        return not_expired.equals(isexpired);
    }

    @override
    public boolean isaccountnonlocked() {
        return true;
    }

    @override
    public boolean iscredentialsnonexpired() {
        return true;
    }

    @override
    public boolean isenabled() {
        return account_active_status.equals(status);
    }
}

自定义角色实现userdetails接口方法时,根据自己的需要来实现

2-自定义userdetailsservice

userdetails是用来规范我们自定义用户对象,而负责提供用户数据源的接口是userdetailsservice,它提供了一个查询用户的方法,我们需要实现它来查询用户

@service
public class phoneuserdetailsservice implements userdetailsservice {

    public static final string user_info_suffix = "user:info:";

    @autowired
    private phoneusermapper phoneusermapper;

    @autowired
    private redistemplate<string,object> redistemplate;

    /**
     * 查找用户
     * @param username
     * @return
     * @throws usernamenotfoundexception
     */
    @override
    public userdetails loaduserbyusername(string username) throws usernamenotfoundexception {
        //先查询缓存
        string userkey = user_info_suffix + username;
        phoneuserdetails cacheuserinfo = (phoneuserdetails) redistemplate.opsforvalue().get(userkey);
        if (cacheuserinfo == null){
            //缓存不存在,从数据库查找用户信息
            phoneuserdetails phoneuserdetails = phoneusermapper.selectphoneuserbyphone(username);
            if (phoneuserdetails == null){
                throw new usernamenotfoundexception("用户不存在");
            }
            //加入缓存
            redistemplate.opsforvalue().set(userkey,phoneuserdetails);
            return phoneuserdetails;
        }
        return cacheuserinfo;
    }

}

3-自定义authentication

在springsecurity认证过程中,最核心的对象为authentication,这个对象用于在认证过程中存储主体的各种基本信息(例如:用户名,密码等等)和主体的权限信息(例如,接口权限)。

我们可以通过继承abstractauthenticationtoken来自定义的authentication对象,我们参考springsecurity自有的usernamepasswordauthenticationtoken来实现自己的abstractauthenticationtoken 实现类

@getter
@setter
public class phoneauthenticationtoken  extends abstractauthenticationtoken {

    private final object principal;

    private object credentials;

   /**
     * 可以自定义属性
     */
    private string phone;

    /**
     * 创建一个未认证的对象
     * @param principal
     * @param credentials
     */
    public phoneauthenticationtoken(object principal, object credentials) {
        super(null);
        this.principal = principal;
        this.credentials = credentials;
        setauthenticated(false);
    }

    public phoneauthenticationtoken(collection<? extends grantedauthority> authorities, object principal, object credentials) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        // 必须使用super,因为我们要重写
        super.setauthenticated(true);
    }

    /**
     * 不能暴露authenticated的设置方法,防止直接设置
     * @param isauthenticated
     * @throws illegalargumentexception
     */
    @override
    public void setauthenticated(boolean isauthenticated) throws illegalargumentexception {
        assert.istrue(!isauthenticated,
                "cannot set this token to trusted - use constructor which takes a grantedauthority list instead");
        super.setauthenticated(false);
    }

    /**
     * 用户凭证,如密码
     * @return
     */
    @override
    public object getcredentials() {
        return credentials;
    }

    /**
     * 被认证主体的身份,如果是用户名/密码登录,就是用户名
     * @return
     */
    @override
    public object getprincipal() {
        return principal;
    }
}

因为我们的验证码是有时效性的,所以erasecredentials 方法也没必要重写了,无需擦除。主要是设置authenticated属性,authenticated属性代表是否已认证

4-自定义authenticationprovider

authenticationprovider对于spring security来说相当于是身份验证的入口。通过向authenticationprovider提供认证请求,我们可以得到认证结果,进而提供其他权限控制服务。

在spring security中,authenticationprovider是一个接口,其实现类需要覆盖authenticate(authentication authentication)方法。当用户请求认证时,authentication provider就会尝试对用户提供的信息(authentication对象里的信息)进行认证评估,并返回authentication对象。通常一个provider对应一种认证方式,providermanager中可以包含多个authenticationprovider表示系统可以支持多种认证方式。

spring security定义了authenticationprovider 接口来规范我们的authenticationprovider 实现类,authenticationprovider 接口只有两个方法,源码如下

public interface authenticationprovider {
	
	//身份认证
	authentication authenticate(authentication authentication)
			throws authenticationexception;

	//是否支持传入authentication类型的认证
	boolean supports(class<?> authentication);
}

下面自定义我们的authenticationprovider,如果authenticationprovider认证成功,它会返回一个完全有效的authentication对象,其中authenticated属性为true,已授权的权限列表(grantedauthority列表),以及用户凭证。

/**
 * 手机验证码认证授权提供者
 */
@data
public class phoneauthenticationprovider  implements authenticationprovider {

    private redistemplate<string,object> redistemplate;

    private phoneuserdetailsservice phoneuserdetailsservice;

    public static final string phone_code_suffix = "phone:code:";

    @override
    public authentication authenticate(authentication authentication) throws authenticationexception {
        //先将authentication转为我们自定义的authentication对象
        phoneauthenticationtoken authenticationtoken = (phoneauthenticationtoken) authentication;
        //校验参数
        object principal = authentication.getprincipal();
        object credentials = authentication.getcredentials();
        if (principal == null || "".equals(principal.tostring()) || credentials == null || "".equals(credentials.tostring())){
            throw new internalauthenticationserviceexception("手机/手机验证码为空!");
        }
        //获取手机号和验证码
        string phone = (string) authenticationtoken.getprincipal();
        string code = (string) authenticationtoken.getcredentials();
        //查找手机用户信息,验证用户是否存在
        userdetails userdetails = phoneuserdetailsservice.loaduserbyusername(phone);
        if (userdetails == null){
            throw new internalauthenticationserviceexception("用户手机不存在!");
        }
        string codekey =  phone_code_suffix+phone;
        //手机用户存在,验证手机验证码是否正确
        if (!redistemplate.haskey(codekey)){
            throw new internalauthenticationserviceexception("验证码不存在或已失效!");
        }
        string realcode = (string) redistemplate.opsforvalue().get(codekey);
        if (stringutils.isblank(realcode) || !realcode.equals(code)){
            throw new internalauthenticationserviceexception("验证码错误!");
        }
        //返回认证成功的对象
        phoneauthenticationtoken phoneauthenticationtoken = new phoneauthenticationtoken(userdetails.getauthorities(),phone,code);
        phoneauthenticationtoken.setphone(phone);
        //details是一个泛型属性,用于存储关于认证令牌的额外信息。其类型是 object,所以你可以存储任何类型的数据。这个属性通常用于存储与认证相关的详细信息,比如用户的角色、ip地址、时间戳等。
        phoneauthenticationtoken.setdetails(userdetails);
        return phoneauthenticationtoken;
    }


    /**
     * providermanager 选择具体provider时根据此方法判断
     * 判断 authentication 是不是 smscodeauthenticationtoken 的子类或子接口
     */
    @override
    public boolean supports(class<?> authentication) {
        //isassignablefrom方法如果比较类和被比较类类型相同,或者是其子类、实现类,返回true
        return phoneauthenticationtoken.class.isassignablefrom(authentication);
    }

}

5-自定义abstractauthenticationprocessingfilter

abstractauthenticationprocessingfilter是spring security中的一个重要的过滤器,用于处理用户的身份验证。它是一个抽象类,提供了一些基本的身份验证功能,可以被子类继承和扩展。该过滤器的主要作用是从请求中获取用户的身份认证信息,并将其传递给authenticationmanager进行身份验证。如果身份验证成功,它将生成一个身份验证令牌,并将其传递给authenticationsuccesshandler进行处理。如果身份验证失败,它将生成一个身份验证异常,并将其传递给authenticationfailurehandler进行处理。abstractauthenticationprocessingfilter还提供了一些其他的方法,如setauthenticationmanager()、setauthenticationsuccesshandler()、setauthenticationfailurehandler()等,可以用于定制身份认证的处理方式。

我们需要自定义认证流程,那么就需要继承abstractauthenticationprocessingfilter这个抽象类

spring security 的usernamepasswordauthenticationfilter也是继承了abstractauthenticationprocessingfilter,我们可以参考实现自己的身份验证

public class phoneverificationcodeauthenticationfilter extends abstractauthenticationprocessingfilter {

    /**
     * 参数名称
     */
    public static final string user_phone = "phone";
    public static final string phone_code = "phonecode";

    private string userphoneparameter = user_phone;
    private string phonecodeparameter = phone_code;

    /**
     * 是否只支持post请求
     */
    private boolean postonly = true;

    /**
     * 通过构造函数,设置对哪些请求进行过滤,如下设置,则只有接口为 /phone_login,请求方式为 post的请求才会进入逻辑
     */
    public phoneverificationcodeauthenticationfilter(){
        super(new regexrequestmatcher("/phone_login","post"));
    }


    /**
     * 认证方法
     * @param request
     * @param response
     * @return
     * @throws authenticationexception
     * @throws ioexception
     * @throws servletexception
     */
    @override
    public authentication attemptauthentication(httpservletrequest request, httpservletresponse response) throws authenticationexception, ioexception, servletexception {
        phoneauthenticationtoken phoneauthenticationtoken;
        //请求方法类型校验
        if (this.postonly && !request.getmethod().equals("post")) {
            throw new authenticationserviceexception("authentication method not supported: " + request.getmethod());
        }
        //如果不是json参数,从request获取参数
        if (!request.getcontenttype().equals(mediatype.application_json_utf8_value) && !request.getcontenttype().equals(mediatype.application_json_value)) {
            string userphone = request.getparameter(userphoneparameter);
            string phonecode = request.getparameter(phonecodeparameter);
            phoneauthenticationtoken = new phoneauthenticationtoken(userphone,phonecode);
        }else {
            //如果是json请求使用取参数逻辑,直接用map接收,也可以创建一个实体类接收
            map<string, string> logindata = new hashmap<>(2);
            try {
                logindata = jsonobject.parseobject(request.getinputstream(), map.class);
            } catch (ioexception e) {
                throw new internalauthenticationserviceexception("请求参数异常");
            }
            // 获得请求参数
            string userphone = logindata.get(userphoneparameter);
            string phonecode = logindata.get(phonecodeparameter);
            phoneauthenticationtoken = new phoneauthenticationtoken(userphone,phonecode);
        }
        phoneauthenticationtoken.setdetails(authenticationdetailssource.builddetails(request));
        return this.getauthenticationmanager().authenticate(phoneauthenticationtoken);
    }


}

6-自定义认证成功和失败的处理类

pringsecurity处理成功和失败一般是进行页面跳转,但是在前后端分离的架构下,前后端的交互一般是通过json进行交互,不需要后端重定向或者跳转,只需要返回我们的登陆信息即可。

这就要实现我们的认证成功和失败处理类

认证成功接口:authenticationsuccesshandler,只有一个onauthenticationsuccess认证成功处理方法

认证失败接口:authenticationfailurehandler,只有一个onauthenticationfailure认证失败处理方法

我们实现相应接口,在方法中定义好我们的处理逻辑即可

@component
public class customauthenticationsuccesshandler implements authenticationsuccesshandler {

    /**
     * 登录成功处理
     * @param httpservletrequest
     * @param httpservletresponse
     * @param authentication
     * @throws ioexception
     * @throws servletexception
     */
    @override
    public void onauthenticationsuccess(httpservletrequest httpservletrequest, httpservletresponse httpservletresponse, authentication authentication) throws ioexception, servletexception {
        httpservletresponse.setcontenttype("application/json;charset=utf-8");
        map<string, object> resp = new hashmap<>();
        resp.put("status", 200);
        resp.put("msg", "登录成功!");
        resp.put("token", new uuidgenerator().next());
        string s = jsonobject.tojsonstring(resp);
        httpservletresponse.getwriter().write(s);
    }

}

@slf4j
@component
public class customauthenticationfailurehandler implements authenticationfailurehandler {

    /**
     * 登录失败处理
     * @param httpservletrequest
     * @param httpservletresponse
     * @param exception
     * @throws ioexception
     * @throws servletexception
     */
    @override
    public void onauthenticationfailure(httpservletrequest httpservletrequest, httpservletresponse httpservletresponse, authenticationexception exception) throws ioexception, servletexception {
        httpservletresponse.setcontenttype("application/json;charset=utf-8");
        map<string, object> resp = new hashmap<>();
        resp.put("status", 500);
        resp.put("msg", "登录失败!" );
        string s  = jsonobject.tojsonstring(resp);
        log.error("登录异常:",exception);
        httpservletresponse.getwriter().write(s);
    }


}

7-修改配置类

想要应用自定义的 authenticationprovider 和 abstractauthenticationprocessingfilter,还需在websecurityconfigureradapter 配置类进行配置。

@configuration
@enablewebsecurity
public class securityconfig extends websecurityconfigureradapter {

    @autowired
    private redistemplate<string, object> redistemplate;

    @autowired
    private phoneuserdetailsservice phoneuserdetailsservice;


    @override
    protected void configure(httpsecurity http) throws exception {
        http.authorizerequests().anyrequest().authenticated()
                .and()
                .formlogin().successhandler(new customauthenticationsuccesshandler()).permitall()
                .and()
                .csrf().disable();

        //添加自定义过滤器
        phoneverificationcodeauthenticationfilter phoneverificationcodeauthenticationfilter = new phoneverificationcodeauthenticationfilter();
        //设置过滤器认证成功和失败的处理类
        phoneverificationcodeauthenticationfilter.setauthenticationsuccesshandler(new customauthenticationsuccesshandler());
        phoneverificationcodeauthenticationfilter.setauthenticationfailurehandler(new customauthenticationfailurehandler());
        //设置认证管理器
        phoneverificationcodeauthenticationfilter.setauthenticationmanager(authenticationmanager());
        //addfilterbefore方法用于将自定义的过滤器添加到过滤器链中,并指定该过滤器在哪个已存在的过滤器之前执行
        http.addfilterbefore(phoneverificationcodeauthenticationfilter, usernamepasswordauthenticationfilter.class);
    }

    @bean
    @override
    public authenticationmanager authenticationmanagerbean() throws exception {
        // 采用密码授权模式需要显式配置authenticationmanager
        return super.authenticationmanagerbean();
    }

    /**
     *
     * @param auth 认证管理器
     * @throws exception
     */
    @override
    protected void configure(authenticationmanagerbuilder auth) throws exception {
        //添加自定义认证提供者
        auth.authenticationprovider(phoneauthenticationprovider());
    }

    /**
     * 手机验证码登录的认证提供者
     * @return
     */
    @bean
    public phoneauthenticationprovider phoneauthenticationprovider(){
        phoneauthenticationprovider phoneauthenticationprovider = new phoneauthenticationprovider();
        phoneauthenticationprovider.setredistemplate(redistemplate);
        phoneauthenticationprovider.setphoneuserdetailsservice(phoneuserdetailsservice);
        return phoneauthenticationprovider;
    }

}

在spring security框架中,addfilterbefore方法用于将自定义的过滤器添加到过滤器链中,并指定该过滤器在哪个已存在的过滤器之前执行。还有一个addfilterafter方法可以将自定义过滤器添加到指定过滤器之后执行。

8-测试

完成上面的操作之后,我们就可以测试下新的登录方式是否生效了。我这里直接使用postman进行登录请求

在这里插入图片描述

到此这篇关于springsecurity 自定义认证登录的项目实践的文章就介绍到这了,更多相关springsecurity 自定义认证登录内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网! 

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com