若依框架api走jwt验证的实现流程是什么样的?
我是个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);
}
}
这样是可以实现我的需求,但总感觉不太优雅。请教各位大佬,是否有其它的方法,可以实现不同的路由走不同的过滤链。
回复
1个回答

test
2024-09-07
用策略模式这么写:1、定义一个策略接口 AuthenticationStrategy
,用于定义认证逻辑2、创建具体策略实现 ApiAuthenticationStrategy
和 DefaultAuthenticationStrategy
,后续有需要继续创建新的策略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;
}//把返回哪个策略挪到工厂里面来
}
}
}
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容