Im using Spring-Security and JWT library to generate token. When the user is authenticated i get the authorization token in response:
Authorization: Bearer eyJhbGciOiJIUzUxMiJ...
In all tutorials I've seen authors pasting this token in authorization header when sending a GET request using POSTMAN, but no tutorial how it works in real request. Although in my Postman it works when I paste in the headers and I'm getting 200 OK.
I'm wondering how can I include this header in real code?
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);
}
}
EDIT
Here's my frontend request. After this call I get Response headers with authorization token. Now the question is how can I use this token to implement future requests? :
$.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"
});