1.集成环境
主要依赖版本信息:Springboot 2.3.9 + Swagger2 + Springfox 2.9.2 + swagger-bootstrap-ui 1.9.3
2.问题描述
{"msg":"请求访问:/ops-api/error,认证失败,无法访问系统资源","code":401}
3.解决办法
修改SecurityFilter类,增加如下处理
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.hnxr.ops.common.core.domain.model.LoginUser;
import com.hnxr.ops.common.utils.SecurityUtils;
import com.hnxr.ops.common.utils.StringUtils;
import com.hnxr.ops.framework.web.service.TokenService;
/**
* token过滤器 验证token有效性
*
* @author ruoyi
*/
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
@Autowired
private TokenService tokenService;
private static String ignoreUrls = "/doc.html,/v2/api-docs,/webjars/*,/swagger-resources";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException
{
if(handleExcludeURL(request)){
chain.doFilter(request, response);
return;
}
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);
}
private boolean handleExcludeURL(HttpServletRequest request)
{
List<String> excludes = Arrays.asList(ignoreUrls.split(","));
if (excludes == null || excludes.isEmpty())
{
return false;
}
String url = request.getServletPath();
for (String pattern : excludes)
{
Pattern p = Pattern.compile("^" + pattern);
Matcher m = p.matcher(url);
if (m.find())
{
return true;
}
}
return false;
}
}