当前位置: 代码网 > it编程>编程语言>Java > SpringBoot3.x接入Security6.x实现JWT认证的完整步骤

SpringBoot3.x接入Security6.x实现JWT认证的完整步骤

2025年02月16日 Java 我要评论
一、引言springboot3.x的安全默认依赖security6.x,security6.x于security5.7以前的配置有了很大区别。我们将深入探讨这两个版本之间的差异,以及它们如何影响现代w

一、引言

springboot3.x的安全默认依赖security6.x,security6.x于security5.7以前的配置有了很大区别。我们将深入探讨这两个版本之间的差异,以及它们如何影响现代web应用的安全架构。特别是,我们将重点分析jwt(json web tokens)过滤器的工作原理,以及它是如何与匿名访问相结合,为应用提供更加灵活的安全控制。

二、环境

  • jdk 17
  • springboot 3.2
  • security 6.3

三、maven依赖

<!-- security安全 -->
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-security</artifactid>
    <version>3.2.2</version>
</dependency>
<!-- jwt接口认证 -->
<dependency>
    <groupid>com.auth0</groupid>
    <artifactid>java-jwt</artifactid>
    <version>4.4.0</version>
</dependency>      

四、认识jwt

json web token (jwt)是一个开放标准(rfc 7519),它定义了一种紧凑的、自包含的方式,用于作为json对象在各方之间安全地传输信息。该信息可以被验证和信任,因为它是数字签名的。

1. jwt组成

json web token由三部分组成,它们之间用圆点(.)连接,一个典型的jwt看起来是这个样子的:

  • 第一部分:header典型的由两部分组成:token的类型(“jwt”)和算法名称(比如:hmac sha256或者rsa等等),然后,用base64对这个json编码就得到jwt的第一部分。
  • 第二部分:payload它包含声明(要求),声明是关于实体(通常是用户)和其他数据的声明。
  • 第三部分:签名是用于验证消息在传递过程中有没有被更改,并且对于使用私钥签名的token,它还可以验证jwt的发送方是否为它所称的发送方。

注意:不要在jwt的payload或header中放置敏感信息,除非它们是加密的。

{
 alg: "rs256"
}.
{
//存储自定义的用户信息,属性可以自定扩充
 login_name: "admin",
 user_id: "xxxxx",
 ...
}.
[signature]
  • 请求header应该是这样的:authorization: bearer

五、认识security6.x

1. 和旧版本的区别(security5.7以前的版本)

springboot3中默认security升级到了6.x写法上发生了很大的变化,最显著的变化之一就是对websecurityconfigureradapter类的使用方式的改变。这个类在 spring security 中被广泛用于自定义安全配置。以下是主要的差异和写法上的变化:

  • 废弃websecurityconfigureradapter:

在security5.x 版本中,websecurityconfigureradapter 是实现安全配置的常用方法。用户通过继承这个类,并覆盖其方法来自定义安全配置。到了 spring security 6.x,websecurityconfigureradapter 被标记为过时(deprecated),意味着它可能在未来的版本中被移除。这一变化是为了推动使用更现代的配置方法,即使用组件式配置。

  • 新版本建议使用组件式配置:

在 spring security 6.x 中,推荐使用组件式配置。这意味着你可以创建一个配置类,该类不再需要继承 websecurityconfigureradapter。
你可以直接定义一个或多个 securityfilterchain bean来配置安全规则。这种方式更加灵活,并且与 spring framework 的整体风格更加一致。

2. security6.x的默认筛选器

支持的所有筛选器在spring-security-config-6.2.1.jar包的org.springframework.security.config.annotation.web.builders.filterorderregistration类的构造函数中定义,并确定了执行顺序。

filterorderregistration() {
    step order = new step(initial_order, order_step);
    put(disableencodeurlfilter.class, order.next());
    put(forceeagersessioncreationfilter.class, order.next());
    put(channelprocessingfilter.class, order.next());
    order.next(); // gh-8105
    put(webasyncmanagerintegrationfilter.class, order.next());
    put(securitycontextholderfilter.class, order.next());
    put(securitycontextpersistencefilter.class, order.next());
    put(headerwriterfilter.class, order.next());
    put(corsfilter.class, order.next());
    put(csrffilter.class, order.next());
    put(logoutfilter.class, order.next());
    this.filtertoorder.put(
            "org.springframework.security.oauth2.client.web.oauth2authorizationrequestredirectfilter",
            order.next());
    this.filtertoorder.put(
            "org.springframework.security.saml2.provider.service.web.saml2webssoauthenticationrequestfilter",
            order.next());
    put(x509authenticationfilter.class, order.next());
    put(abstractpreauthenticatedprocessingfilter.class, order.next());
    this.filtertoorder.put("org.springframework.security.cas.web.casauthenticationfilter", order.next());
    this.filtertoorder.put("org.springframework.security.oauth2.client.web.oauth2loginauthenticationfilter",
            order.next());
    this.filtertoorder.put(
            "org.springframework.security.saml2.provider.service.web.authentication.saml2webssoauthenticationfilter",
            order.next());
    put(usernamepasswordauthenticationfilter.class, order.next());
    order.next(); // gh-8105
    put(defaultloginpagegeneratingfilter.class, order.next());
    put(defaultlogoutpagegeneratingfilter.class, order.next());
    put(concurrentsessionfilter.class, order.next());
    put(digestauthenticationfilter.class, order.next());
    this.filtertoorder.put(
            "org.springframework.security.oauth2.server.resource.web.authentication.bearertokenauthenticationfilter",
            order.next());
    put(basicauthenticationfilter.class, order.next());
    put(requestcacheawarefilter.class, order.next());
    put(securitycontextholderawarerequestfilter.class, order.next());
    put(jaasapiintegrationfilter.class, order.next());
    put(remembermeauthenticationfilter.class, order.next());
    put(anonymousauthenticationfilter.class, order.next());
    this.filtertoorder.put("org.springframework.security.oauth2.client.web.oauth2authorizationcodegrantfilter",
            order.next());
    put(sessionmanagementfilter.class, order.next());
    put(exceptiontranslationfilter.class, order.next());
    put(filtersecurityinterceptor.class, order.next());
    put(authorizationfilter.class, order.next());
    put(switchuserfilter.class, order.next());
}

3. 注册securityfilterchain

    private final string[] permiturlarr = new string[]{"xxx"};
    /**
     * 配置spring security安全链。
     */
    @bean
    public securityfilterchain filterchain(httpsecurity httpsecurity) throws exception {
        //初始化jwt过滤器,并设置jwt公钥
        var jwttokenfilter = new jwttokenfilter();
        //security6.x关闭默认登录页
        httpsecurity.removeconfigurers(defaultloginpageconfigurer.class);
        logger.info("注册jwt认证securityfilterchain");
        var chain = httpsecurity
                // 自定义权限拦截规则
                .authorizehttprequests((requests) -> {
                    //requests.anyrequest().permitall(); //放行所有请求!!!
                    //允许匿名访问
                    requests
                            //自定可匿名访问地址,放到permitallurl中即可
                            .requestmatchers(permiturlarr).permitall()
                            //除上面声明的可匿名访问地址,其它所有请求全部需要进行认证
                            .anyrequest()
                            .authenticated();
                })
                // 禁用http响应标头
                .headers(headerscustomizer -> {headerscustomizer
                            .cachecontrol(cache -> cache.disable())
                            .frameoptions(options -> options.sameorigin());})
                //会话设为无状态,基于token,所以不需要session
                .sessionmanagement(session -> session
                        .sessioncreationpolicy(sessioncreationpolicy.stateless))
                //添加自定义的jwt认证筛选器,验证header中jwt有效性,将插入到usernamepasswordauthenticationfilter之前 
                .addfilterbefore(jwttokenfilter, usernamepasswordauthenticationfilter.class)
                //禁用表单登录
                .formlogin(formlogin -> formlogin.disable())
                //禁用httpbasic登录
                .httpbasic(httpbasic -> httpbasic.disable())
                //禁用rememberme
                .rememberme(rememberme -> rememberme.disable())
                // 禁用csrf,因为不使用session
                .csrf(csrf -> csrf.disable())
                //允许跨域请求
                .cors(customizer.withdefaults())
                .build();
        return chain;
    }

六、基于onceperrequestfilter自定义jwt认证筛选器

使用onceperrequestfilter的优点是,能保证一个请求只过一次筛选器。可以在filter中实现对jwt的校验,验证成功后需要对security上下文进行标注。标记认证已经通过,这点非常重要。如果认证完了不标注,后边的过滤器还是认为未认证导致无权限失败。

1. 标记认证成功

//接入spring security6.x上下文,标记为已认证状态
jwtauthenticationtoken jwttoken = new jwtauthenticationtoken(null);
jwttoken.setauthenticated(true); //标记认证通过
securitycontextholder.getcontext().setauthentication(jwttoken);

七、遇到的问题

1. 加入security6后,一直出现登录页

关闭默认登录页有两个设置可以完成,可以删除defaultloginpageconfigurer类的加载,或者调用formlogin()函数,具体如下:

    @bean
    public securityfilterchain filterchain(httpsecurity httpsecurity) throws exception {
        //security6.x关闭默认登录页
        httpsecurity.removeconfigurers(defaultloginpageconfigurer.class);
        var chain = httpsecurity
                //禁用表单登录
                .formlogin(formlogin -> formlogin.disable())
                .build();
        return chain;
    }

2. 配置完匿名访问的url后,仍然执行自定的筛选器

如果出现配置完匿名访问的url后,仍然执行自定的筛选器,的问题。那原因就在于这个自定义筛选器上了,
只通过requests.requestmatchers(…).permitall(); 配置的匿名访问只能对默认筛选器起效,如果想
对自定义删除器起效,还需要构建websecuritycustomizer bean对象,基于匿名函数配置要匿名访问的地址。
一下是官网推荐的一个写法,这里建议把两个位置,配置的匿名访问地址,使用一个公共数组进行管理,这样
能保证两个位置配置的一致性。

    /** 其它不需要认证的地址 */
    private final string[] permiturlarr = new string[]{
            "/login"
            ,"/error"
            //静态资源
            ,"/static/**.ico"
            ,"/static/**.js"
            ,"/static/**.css"
            //匹配springdoc
            ,"/doc.html"
            ,"/webjars/**"
            //匹配swagger路径(默认)
            , "/swagger-ui.html"
            , "/swagger-ui/index.html"
            , "/v3/api-docs/**"
            , "/swagger-ui/**"
            //监控检测
            , "/actuator/**"
    };
    @bean
    public websecuritycustomizer ignoringcustomize(){
        return (web) -> web.ignoring()
                .requestmatchers(permiturlarr);
    }
    @bean
    public securityfilterchain filterchain(httpsecurity httpsecurity) throws exception {
        //初始化jwt过滤器,并设置jwt公钥
        var jwttokenfilter = new jwttokenfilter();
        //security6.x关闭默认登录页
        httpsecurity.removeconfigurers(defaultloginpageconfigurer.class);
        logger.info("注册jwt认证securityfilterchain");
        var chain = httpsecurity
                // 自定义权限拦截规则
                .authorizehttprequests((requests) -> {
                    //允许匿名访问
                    requests
                            //自定可匿名访问地址,放到permitallurl中即可
                            .requestmatchers(permiturlarr).permitall()
                            //除上面声明的可匿名访问地址,其它所有请求全部需要进行认证
                            .anyrequest()
                            .authenticated();
                }).build();
        return chain;
    }                    

八、完成jwt认证的主要代码

目前是对已有jwt的认证,下发的jwt是基于rsa加密的内容,需要使用公钥进行解密,公钥一般配置在yml文件里。关键逻辑设计3部分,securitconfig、jwttokenfilter、jwtutil。

1. jwtutil

公钥是统一认证中心下发的,目前写在yml中,格式如下:

jwt.keyvalue: |
          -----begin public key-----
          xxxxxxxx
          -----end public key-----

jwtutil类提供了验证方法,出于性能考虑使用了单例模式,验证器只需要实例化一次。

public class jwtutil {
    private static jwtutil instance = new jwtutil();
    private static jwtverifier jwtverifier;
    //配置文件中公钥的key值
    private static final string jwtpublickeyconfig="jwt.keyvalue";

    private jwtutil()  {}

    /**
     * 基于固定配置文件的公钥初始化jwt验证器
     * @return
     */
    public static jwtutil getinstance(){
        if (jwtverifier == null){
            string publickey = springutil.getconfig(jwtpublickeyconfig);
            return getinstance(publickey);
        }
        return instance;
    }
    /**
     * 基于自定义公钥初始化jwt验证器
     * @return
     */
    public static jwtutil getinstance(string publickey) {
        if (jwtverifier == null){
            initverifier(publickey);
        }
        return instance;
    }

    // 静态的初始化函数
    private static synchronized void initverifier(string publickey) {
        if (jwtverifier != null)
            return;

        //替换为实际的base64编码的rsa公钥字符串
        string publickeystr = publickey.replaceall("\\s", "") // 去除所有空白字符,包括换行符
                .replace("-----beginpublickey-----", "")
                .replace("-----endpublickey-----", "");
        // 将base64编码的公钥字符串转换为publickey对象
        byte[] encodedpublickey = base64.getdecoder().decode(publickeystr);
        x509encodedkeyspec keyspec = new x509encodedkeyspec(encodedpublickey);
        keyfactory keyfactory = null;
        try {
            keyfactory = keyfactory.getinstance("rsa");
            publickey pubkey = keyfactory.generatepublic(keyspec);
            // 使用公钥创建一个algorithm对象,用于验证token的签名
            algorithm algorithm = algorithm.rsa256((rsapublickey) pubkey, null);
            // 解析和验证token
            jwtverifier = jwt.require(algorithm).build();
        } catch (nosuchalgorithmexception e) {
            throw new runtimeexception(e);
        } catch (invalidkeyspecexception e) {
            throw new runtimeexception(e);
        }catch (exception e){
            throw new runtimeexception(e);
        }

    }

    /**
     * 解析和验证jwt token。
     *
     * @param token jwt token字符串
     * @return 解码后的jwt对象
     * @throws exception 如果解析或验证失败,抛出异常
     */
    public decodedjwt verifytoken(string token) {
        return jwtverifier.verify(token);
    }
}

2. jwttokenfilter

该类是校验的主要逻辑,完成了jwt校验、已认证的标注。

public class jwttokenfilter extends onceperrequestfilter {
    private static logger logger = loggerfactory.getlogger(jwttokenfilter.class);
    private jwtutil jwtutil;
    //获取yml中的配置
    public string getconfig(string configkey) {
        var bean = applicationcontext.getbean(environment.class);
        var val = bean.getproperty(configkey);
        return val;
    }
    public jwttokenfilter() throws servletexception {
        string jwtpublikey = getconfig("jwt.keyvalue");
        inittokenfilter(jwtpublikey);
    }

    public jwttokenfilter(string jwtpublikey) throws servletexception {
        inittokenfilter(jwtpublikey);
    }

    @override
    protected void initfilterbean() throws servletexception {
    }
    @override
    protected void dofilterinternal(httpservletrequest request, httpservletresponse response, filterchain filterchain) throws servletexception, ioexception {
        var pass = dotokenfilter(request,response,filterchain);
        if(!pass){
            return;
        }
        filterchain.dofilter(request,response);
    }

    /**
     * 初始化token过滤器。
     * @throws servletexception 如果在初始化过程中发生错误,则抛出servletexception异常
     */
    public void  inittokenfilter(string publickey) throws servletexception {
        logger.info("初始化tokenfilter");
        if(stringutils.isblank(publickey)){
            throw new servletexception("jwtpublickey is null");
        }
        logger.info("jwtpublickey:{}",publickey);
        jwtutil = jwtutil.getinstance(publickey);
        logger.info("初始化jwtutil完成");
    }

    protected boolean dotokenfilter(servletrequest servletrequest, servletresponse servletresponse, filterchain filterchain) throws servletexception, ioexception {
        httpservletrequest request = (httpservletrequest) servletrequest;
        httpservletresponse response = (httpservletresponse) servletresponse;
        // 从请求头中获取token
        string token = request.getheader("authorization");
        if(stringutils.isblank(token)){
            logger.info("jwt token为空,{} {}",request.getmethod(),request.getrequesturi());
            // 验证失败,返回401状态码
            response.senderror(httpservletresponse.sc_unauthorized, "invalid token");
            return false;
        }

        // 假设token是以"bearer "开头的,需要去掉这个前缀
        if (token.startswith("bearer")) {
            token = token.replaceall("bearer\s+","");
        }
        logger.debug(request.getrequesturi());
        try {
            // 调用jwtutils进行token验证
            decodedjwt jwtdecode = jwtutil.verifytoken(token);
            //接入spring security6.x上下文,标记为已认证状态
            jwtauthenticationtoken jwttoken = new jwtauthenticationtoken(null);
            jwttoken.setauthenticated(true);
            securitycontextholder.getcontext().setauthentication(jwttoken);
            //将登录信息写入spring security上下文
        } catch (jwtverificationexception ex) {
            logger.info("jwt token 非法");
            response.senderror(httpservletresponse.sc_unauthorized, "非法token:"+ex.getmessage());
            return false;
        } catch (exception ex) {
            throw ex;
        }
        logger.debug("token验证通过");
        return true;
    }

    public static class jwtauthenticationtoken extends abstractauthenticationtoken {
        private user userinfo;
        public jwtauthenticationtoken(user user) {
            super(null);
            this.userinfo =user;
        }
        @override
        public user getprincipal() {
            return userinfo;
        }
        @override
        public object getcredentials() {
            throw new unsupportedoperationexception();
        }

        @override
        public boolean implies(subject subject) {
            return super.implies(subject);
        }
    }

}

3. securitconfig

该类完成了对需要匿名访问的地址的配置,还有自定义filter的注入。

@configuration
public class securityconfig {
    private static final logger logger = loggerfactory.getlogger(securityconfig.class);
    /** 其它不需要认证的地址 */
    private final string[] permiturlarr = new string[]{
            "/login"
            ,"/error"
            //静态资源
            ,"/static/**.ico"
            ,"/static/**.js"
            ,"/static/**.css"
            //匹配springdoc
            ,"/doc.html"
            ,"/webjars/**"
            //匹配swagger路径(默认)
            , "/swagger-ui.html"
            , "/swagger-ui/index.html"
            , "/v3/api-docs/**"
            , "/swagger-ui/**"
            //监控检测
            , "/actuator/**"
    };
    @bean
    public websecuritycustomizer ignoringcustomize(){
        return (web) -> web.ignoring()
                .requestmatchers(permiturlarr);
    }
    @bean
    public securityfilterchain filterchain(httpsecurity httpsecurity) throws exception {
        //初始化jwt过滤器,并设置jwt公钥
        var jwttokenfilter = new jwttokenfilter();
        //security6.x关闭默认登录页
        httpsecurity.removeconfigurers(defaultloginpageconfigurer.class);
        logger.info("注册jwt认证securityfilterchain");
        var chain = httpsecurity
                // 自定义权限拦截规则
                .authorizehttprequests((requests) -> {
                    //requests.anyrequest().permitall(); //放行所有请求!!!
                    //允许匿名访问
                    requests
                            //自定可匿名访问地址,放到permitallurl中即可
                            .requestmatchers(permiturlarr).permitall()
                            //除上面声明的可匿名访问地址,其它所有请求全部需要进行认证
                            .anyrequest()
                            .authenticated();
                })
                // 禁用http响应标头
                .headers(headerscustomizer -> {headerscustomizer
                            .cachecontrol(cache -> cache.disable())
                            .frameoptions(options -> options.sameorigin());})
                //会话设为无状态,基于token,所以不需要session
                .sessionmanagement(session -> session
                        .sessioncreationpolicy(sessioncreationpolicy.stateless))
                //添加自定义的jwt认证筛选器,验证header中jwt有效性,将插入到usernamepasswordauthenticationfilter之前 
                .addfilterbefore(jwttokenfilter, usernamepasswordauthenticationfilter.class)
                //禁用表单登录
                .formlogin(formlogin -> formlogin.disable())
                //禁用httpbasic登录
                .httpbasic(httpbasic -> httpbasic.disable())
                //禁用rememberme
                .rememberme(rememberme -> rememberme.disable())
                // 禁用csrf,因为不使用session
                .csrf(csrf -> csrf.disable())
                //允许跨域请求
                .cors(customizer.withdefaults())
                .build();
        return chain;
    }
    @bean
    public filterregistrationbean disablespringbooterrorfilter(errorpagefilter filter){
        filterregistrationbean filterregistrationbean = new filterregistrationbean();
        filterregistrationbean.setfilter(filter);
        filterregistrationbean.setenabled(false);
        return filterregistrationbean;
    }
}

总结

以上支持介绍了对于已有jwt统一认证系统的接入(jwt解析和认证),不涉及jwt生成和管理相关内容。

目前的用户信息是基于jwt动态解析的,所以暂时没有基于abstractauthenticationtoken在security上下文中存放用户信息,jwtauthenticationtoken已经支持自定义用户信息的存储,只需要按需传入即可。基于security上下文获取用户信息使用securitycontextholder.getcontext().getauthentication().getprincipal();方法。

到此这篇关于springboot3.x接入security6.x实现jwt认证的文章就介绍到这了,更多相关springboot3接入security6.x实现jwt认证内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

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

发表评论

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