Kernandez Buhub
Kernandez Buhub

Reputation: 23

How to include authorization header in GET request to secured endpoint in Spring with JWT token

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"
                    });

Upvotes: 2

Views: 6055

Answers (2)

Nate T
Nate T

Reputation: 785

Once the user is authenticated, you want to store the returned token on the client side using either local storage or session storage. Next, you will protect any route/endpoint which requires said token (protected route) . There should be an authorization guard in place which checks to see if token is present in the header (in the same format as you've used it when sending requests via Postman). If the token is invalid or missing from the header altogether, it will usually redirect to a different route (often the login page).

This isn't specific to Spring, but to JSON Web Tokens. The implementation differs from one language/framework to the next, bus as far as I know, this is always the general procedure.

Upvotes: 2

parham dm
parham dm

Reputation: 86

I suggest using Single page frameworks like angular or react because the provide better tools. But what framework you are using completely depends on your application. for JQuery and javascript you can use this:
you must store the token inside your browser. one of the ways is using "local storage":

  success: function(response) {
    // not sure how you send token
    localStorage.setItem('token', response.token)
  },

and add token header to ajax request after that. note that you must handle empty token or expired token in your code.

token = localStorage.getItem('token')
$.ajaxSetup({
  headers: { Authorization: 'Bearer ' + token }
})
//call ajax

Upvotes: 1

Related Questions