我使用 Spring-Security 和 JWT 库来生成 token 。当用户通过身份验证时,我会得到授权 token 作为响应:
Authorization: Bearer eyJhbGciOiJIUzUxMiJ...
在所有教程中,我都看到作者在使用 POSTMAN 发送 GET 请求时将此 token 粘贴到授权 header 中,但没有教程它在实际请求中如何工作。尽管在我的 postman 中,当我粘贴标题时它可以工作并且我得到 200 OK。
我想知道如何在实际代码中包含此 header ?
public class JwtUsernameAndPasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final AuthenticationManager authenticationManager;
private final JwtConfig jwtConfig;
private final SecretKey secretKey;
public JwtUsernameAndPasswordAuthenticationFilter(
AuthenticationManager authenticationManager,
JwtConfig jwtConfig,
SecretKey secretKey) {
this.authenticationManager = authenticationManager;
this.jwtConfig = jwtConfig;
this.secretKey = secretKey;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
try {
System.out.println("Authentication token " + request.getInputStream());
UsernameAndPasswordAuthenticationRequest authenticationRequest =
new ObjectMapper().readValue(request.getInputStream(),
UsernameAndPasswordAuthenticationRequest.class);
Authentication authentication = new UsernamePasswordAuthenticationToken(
authenticationRequest.getUsername(),
authenticationRequest.getPassword()
);
SecurityContextHolder.getContext().setAuthentication(authentication);
Authentication authenticate = authenticationManager.authenticate(authentication);
return authenticate;
} catch(IOException e) {
throw new RuntimeException("new runtime exception " + e);
}
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
FilterChain chain, Authentication authResult) throws IOException, ServletException {
String token = Jwts.builder()
.setSubject(authResult.getName())
.claim("authorities", authResult.getAuthorities())
.setIssuedAt(new Date())
.setExpiration(java.sql.Date.valueOf(LocalDate.now().plusDays(jwtConfig.getTokenExpirationAfterDays())))
.signWith(secretKey)
.compact();
System.out.println("This is token: " + token);
response.addHeader(jwtConfig.getAuthorizationHeader(), jwtConfig.getTokenPrefix() + token);
}
}
编辑
这是我的前端请求。在此调用之后,我得到带有授权 token 的响应 header 。现在的问题是我如何使用这个 token 来实现 future 的请求? :
$.ajax({
type: 'POST',
url: "/login",
data: JSON.stringify({
"username" : "linda",
"password" : "password",
}),
success: function(response) {
// some logic
},
error: function(e) {
console.log(e);
},
processData: false,
//dataType: "json",
contentType: "application/json; charset=utf-8"
});
最佳答案
用户通过身份验证后,您希望使用本地存储或 session 存储将返回的 token 存储在客户端。接下来,您将保护需要所述 token 的任何路由/端点( protected 路由)。应该有一个授权守卫来检查 header 中是否存在 token (与通过 Postman 发送请求时使用的格式相同)。如果 token 无效或完全从 header 中丢失,它通常会重定向到不同的路由(通常是登录页面)。
这不是 Spring 特有的,而是 JSON Web Tokens 特有的。据我所知,一种语言/框架与另一种语言/框架的实现有所不同,这始终是一般过程。
关于java - 如何使用 JWT token 在 Spring 中向安全端点的 GET 请求中包含授权 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60156663/