当前位置: 首页 > 知识库问答 >
问题:

java - 若依框架api走jwt验证的实现流程是什么样的?

公良飞尘
2024-08-30

我是个java新手,如果描述得不准确,还望海涵。
最近在使用若依框架前后端分离版开发项目的过程中,遇到了如下问题:

现在的后台接口是通过jwt进行验证的。而现在我在开发前端app接口,也需要用到jwt验证。而现在SecurityConfig的过滤链是这样的:
protected SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception
    {
        return httpSecurity
            // CSRF禁用,因为不使用session
            .csrf(csrf -> csrf.disable())
            // 禁用HTTP响应标头
            .headers((headersCustomizer) -> {
                headersCustomizer.cacheControl(cache -> cache.disable()).frameOptions(options -> options.sameOrigin());
            })
            // 认证失败处理类
            .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
            // 基于token,所以不需要session
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            // 注解标记允许匿名访问的url
            .authorizeHttpRequests((requests) -> {
                permitAllUrl.getUrls().forEach(url -> requests.antMatchers(url).permitAll());
                // 对于登录login 注册register 验证码captchaImage 允许匿名访问
                requests.antMatchers("/login", "/register", "/captchaImage").permitAll()
                    // 静态资源,可匿名访问
                    .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
                    .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()
                    // 除上面外的所有请求全部需要鉴权认证
                    .anyRequest().authenticated();
            })
            // 添加Logout filter
            .logout(logout -> logout.logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler))
            // 添加JWT filter
            .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
            // 添加CORS filter
            .addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class)
            .addFilterBefore(corsFilter, LogoutFilter.class)
            .build();
    }

对于短信发送,注册和登录接口,我只需要在方法前加个@Anonymous注解就可以匿名访问。而其它接口,我希望通过jwt验证后才能访问。
目前后台的jwt验证是在 JwtAuthenticationTokenFilter类中,类代码如下:

package com.ruoyi.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.model.ApiLoginUser;
import com.ruoyi.framework.web.service.ApiTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;

/**
 * token过滤器 验证token有效性
 * 
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
        {
            tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }

        chain.doFilter(request, response);
    }
}

我现在能想到的方案是,修改这个类,如果请求的路径是以/api打头,就走我自定义的 ApiTokenService,最终结果如下:

package com.ruoyi.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.model.ApiLoginUser;
import com.ruoyi.framework.web.service.ApiTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;

/**
 * token过滤器 验证token有效性
 * 
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private ApiTokenService apiTokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        if (request.getRequestURI().startsWith("/api")) {
            ApiLoginUser apiLoginUser = apiTokenService.getLoginUser(request);
            if (StringUtils.isNotNull(apiLoginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
            {
                apiTokenService.verifyToken(apiLoginUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(apiLoginUser, null, apiLoginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        } else {
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
            {
                tokenService.verifyToken(loginUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }

        chain.doFilter(request, response);
    }
}

这样是可以实现我的需求,但总感觉不太优雅。
请教各位大佬,是否有其它的方法,可以实现不同的路由走不同的过滤链。

共有2个答案

督宏旷
2024-08-30

我也是后台和app两套用户,最终是在LoginUser中添加了一个属性appUser表示app用户,然后在涉及从LoginUser获取信息的地方都有两套获取方法。

比如:

SecurityUtils.getUserId()
//这个本身是从LoginUser中获取userId,但是现在有两个分支:
LoginUser.userId
LoginUser.appUser.userId
尹雅健
2024-08-30

用策略模式这么写:
1、定义一个策略接口 AuthenticationStrategy,用于定义认证逻辑
2、创建具体策略实现 ApiAuthenticationStrategyDefaultAuthenticationStrategy,后续有需要继续创建新的策略
3、创建策略工厂 AuthenticationStrategyFactory,它会根据请求的路径返回对应的策略实例
4、修改 JwtAuthenticationTokenFilter 类来使用策略模式
5、后续多一个策略你就新写一个策略类,在工厂类里作怎么跳转的逻辑判断就可以了,不用去管 JwtAuthenticationTokenFilter类,符合开闭原则
这里为了方便看就都写在一个类里了,你可以把接口、策略实现类和工厂类单独提出来方便维护:

package com.ruoyi.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.model.ApiLoginUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * token过滤器 验证token有效性
 * 使用策略模式和策略工厂重构
 * 
 * @author Undest
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private final AuthenticationStrategyFactory factory;

    @Autowired
    public JwtAuthenticationTokenFilter(AuthenticationStrategyFactory factory) {
        this.factory = factory;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        AuthenticationStrategy strategy = factory.createStrategy(request);
        strategy.authenticate(request);

        chain.doFilter(request, response);
    }

    interface AuthenticationStrategy {
        void authenticate(HttpServletRequest request) throws ServletException, IOException;
    }

    static class ApiAuthenticationStrategy implements AuthenticationStrategy {
        private final ApiTokenService apiTokenService;

        ApiAuthenticationStrategy(ApiTokenService apiTokenService) {
            this.apiTokenService = apiTokenService;
        }

        @Override
        public void authenticate(HttpServletRequest request) throws ServletException, IOException {
            ApiLoginUser apiLoginUser = apiTokenService.getLoginUser(request);
            if (StringUtils.isNotNull(apiLoginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
                apiTokenService.verifyToken(apiLoginUser);
                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(apiLoginUser, null, apiLoginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
    }

    static class DefaultAuthenticationStrategy implements AuthenticationStrategy {
        private final TokenService tokenService;

        DefaultAuthenticationStrategy(TokenService tokenService) {
            this.tokenService = tokenService;
        }

        @Override
        public void authenticate(HttpServletRequest request) throws ServletException, IOException {
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
                tokenService.verifyToken(loginUser);
                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
    }

    @Component
    static class AuthenticationStrategyFactory {
        private final ApiAuthenticationStrategy apiStrategy;
        private final DefaultAuthenticationStrategy defaultStrategy;

        @Autowired
        public AuthenticationStrategyFactory(ApiTokenService apiTokenService, TokenService tokenService) {
            this.apiStrategy = new ApiAuthenticationStrategy(apiTokenService);
            this.defaultStrategy = new DefaultAuthenticationStrategy(tokenService);
        }

        public AuthenticationStrategy createStrategy(HttpServletRequest request) {
            String requestURI = request.getRequestURI();
            if (requestURI.startsWith("/api")) {
                return apiStrategy;
            } else {
                return defaultStrategy;
            }//把返回哪个策略挪到工厂里面来
        }
    }
}
 类似资料:
  • 本文向大家介绍SpringBoot集成JWT实现token验证的流程,包括了SpringBoot集成JWT实现token验证的流程的使用技巧和注意事项,需要的朋友参考一下 JWT官网: https://jwt.io/ JWT(Java版)的github地址:https://github.com/jwtk/jjwt 什么是JWT Json web token (JWT), 是为了在网络应用环境间传递

  • 问题内容: 我曾经遇到过Java的验证框架,您在其中编写了一种方法来保护数据类型的完整性以及对该数据类型的任何CRUD操作的自动调用此方法。 有谁知道这个框架是什么?我只是想避免对附加到数据类型的每个CRUD方法进行重复验证。 问题答案: 这是Java验证库/框架的巨大列表-http: //java-source.net/open- source/validation

  • ORM(Object-relational mapping),对象关系映射。 是为了解决面向对象与关系型数据库存在的不匹配问题。 ORM框架的优点: 开发效率更高 数据访问更抽象、轻便 支持面向对象封装

  • 本文向大家介绍JavaScript框架是什么?怎样才能叫做框架?,包括了JavaScript框架是什么?怎样才能叫做框架?的使用技巧和注意事项,需要的朋友参考一下 刚初学js时,总会听到关于框架的一些事情。等学完JQ后我才知道什么是框架。一下是转载的一篇文章,希望对还迷茫的童鞋们有点帮助。 什么是 JavaScript 框架? JavaScript 本身就是一种功能强大的语言,您不需要额外的框架就

  • 我正在验证数据访问对象类的字段。在一次尝试中,我已经开始向属性(@NotNull、@NotBlank、@Min、@Max等)添加Bean验证注释。我还有更多的注释jackson(JsonProperty(..))用于swagger库和文档(@api(...))。在我看来,这个类非常“脏”,有很多注释(每个属性至少有三个注释)。一个字段的示例: 在另一次尝试中,我使用spring的接口执行了自己的验

  • web上有大量关于使用JWT()进行身份验证的信息。但是我仍然没有找到关于在多域环境中为单点登录解决方案使用JWT令牌时流程应该是什么的清晰解释。 我工作的公司有很多网站在不同的主机。让我们使用example1.com和example2.com。我们需要一个单点登录解决方案,这意味着如果一个用户在example1.com上进行身份验证,我们希望他也在example2.com上自动进行身份验证。 J

  • 问题内容: 我想知道 _什么是Spring Framework? 为什么和何时应该在Java Enterprise开发中使用它? _ 答案将是“依赖注入框架”。好了,使用依赖注入框架时我们有什么优势?用setter值和/或构造函数参数描述类的想法对我来说似乎很奇怪。为什么这样 因为我们可以更改属性而无需重新编译项目?这就是我们所获得的一切吗? 那么,我们应该用什么对象来描述?所有对象还是只有几个?