gpt4 book ai didi

java - 为什么 Spring Security 返回空响应正文?

转载 作者:行者123 更新时间:2023-12-01 18:08:42 26 4
gpt4 key购买 nike

我有以下 Spring Security 配置:

@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.authorizeRequests().antMatchers("/user/authenticate")
.permitAll().anyRequest().authenticated()
.and()
.addFilter(new JwtAuthenticationFilter(authenticationManager()))
.addFilter(new JwtAuthorizationFilter(authenticationManager()))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

我做了一个扩展UsernamePasswordAuthenticationFilter的过滤器来执行我的身份验证端点。有两种方法处理此端点的响应:一种是身份验证成功,另一种是身份验证失败:

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain, Authentication authentication) throws IOException {
UserDto user = ((UserDto) authentication.getPrincipal());

//Here is converted the roles/authorities from the user.
List<String> roles = user.getAuthorities().stream().map(GrantedAuthority::getAuthority)
.collect(Collectors.toList());

byte[] signingKey = Constants.JWT_SECRET.getBytes();

//Token builder.
String token = Jwts.builder().signWith(Keys.hmacShaKeyFor(signingKey), SignatureAlgorithm.HS512)
.setHeaderParam("typ", Constants.TOKEN_TYPE)
.setIssuer(Constants.TOKEN_ISSUER)
.setAudience(Constants.TOKEN_AUDIENCE)
.setSubject(user.getUsername())
.setExpiration(new Date(System.currentTimeMillis() + 864000000))
.claim("rol", roles)
.compact();

response.setContentType("application/json");
response.sendError(response.getStatus(), "Bearer " + token);
}

@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) throws IOException, ServletException {
System.out.println("MESSAGE UNAUTHORIZED : " + failed.getMessage());

response.sendError(response.SC_UNAUTHORIZED, failed.getMessage());
}

我使用authenticated()方法来保护(过滤)路由。但同样,仅在过滤器端点(/user/authenticate)中返回状态和空白响应正文。当我不使用它时,sendError()生成的响应正常返回。

最佳答案

所以实际上我认为您想要的是 getWriter 方法,因为 sendError 不用于成功结果。

尝试以下操作:

response.setStatus(HttpServletResponse.SC_OK); // You can use another constant if u like
response.getWritter().print("Bearer " + token);

关于java - 为什么 Spring Security 返回空响应正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60508533/

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