gpt4 book ai didi

java - 如何将 JwtFilter 异常传递给服务器 JSON 答案?

转载 作者:行者123 更新时间:2023-11-30 12:02:14 27 4
gpt4 key购买 nike

我的智威特过滤器:

 public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

public JWTAuthorizationFilter(AuthenticationManager authManager) {
super(authManager);
}

@Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain) throws IOException, ServletException {
String header = req.getHeader("Authorization");

if (header == null || !header.startsWith("Bearer ")) {
chain.doFilter(req, res);
return;
}

UsernamePasswordAuthenticationToken authentication = getAuthentication(req);

SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(req, res);
}

private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
String token = request.getHeader("Authorization");
if (token != null) {
// parse the token.


byte[] keyBytes = Decoders.BASE64.decode("kaslsafdhlkjsdfhlksjdafhlaksjdfhlaskajdhflaksdaf87687687asdafasdhfasdfsdfdfjalskjfhlaskdhflasdjhl3434");
Key key = Keys.hmacShaKeyFor(keyBytes);

String cleanToken = token.replace("Bearer ", "");
String user = Jwts.parser().setSigningKey(key).parseClaimsJws(cleanToken).getBody().getSubject();

if (user != null) {
return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
}
return null;
}
return null;
}
}

它抛出“JWT 签名与本地计算的签名不匹配。JWT 有效性无法断言,不应被信任。”异常。

我尝试用 authenticationEntryPoint(new JwtAuthenticationEntryPoint()) 捕获它:

    @Component("restAuthenticationEntryPoint")
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {

response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getOutputStream().println("{ \"error\": \"" + authenticationException.getMessage() + "\" }");

}

}

但是我得到:

{
"error": "Full authentication is required to access this resource"
}

如何从过滤器中获取异常并传递给 http 应答?

最佳答案

我终于找到了答案。在过滤器中我修改响应:

try {
UsernamePasswordAuthenticationToken authentication = getAuthentication(req);

SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(req, res);
}catch (Exception e){


res.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
res.getWriter().write(convertObjectToJson(e));
}

关于java - 如何将 JwtFilter 异常传递给服务器 JSON 答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58724736/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com