Doncarlito87
Doncarlito87

Reputation: 459

How to get JWT Token from RequestHeader

enter image description hereI try to get my bearer token from the header of the getrequest. If I want to display the token, then NULL is returned. Does anyone have any idea why I don't get the token?

public String sendSmsToCustomer(HttpServletRequest request, @PathVariable("name") String name,@PathVariable("customer_phone_number") String customer_phone_number, @PathVariable("text") String text) throws Exception
            {
            String user = request.getHeader("Authorization");
            System.out.println(user);

UPDATE 1

public static String getUsernameFromToken(HttpServletRequest request) {
        String token = request.getHeader(HEADER_STRING);
        String user = null;
        if (token != null) {
            // parse the token.

            try {
                user = Jwts.parser()
                        .setSigningKey(SECRET)
                        .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                        .getBody()
                        .getSubject();


            } catch (Exception e) {

                throw e;

            }
            return user;
        }
        else
        return null;
    }

UPDATE 2

        @GetMapping("/contacts/token")
            public String getToken(HttpServletRequest request) throws Exception
            {
            String user = request.getHeader(HEADER_STRING);
            System.out.println(user);
            return user;
            }

UPDATE 3 After I have had the complete header output, I see that "Authorization" is not available.

{
    "x-forwarded-host": "localhost:8800",
    "x-forwarded-proto": "http",
    "x-forwarded-prefix": "/contacts",
    "postman-token": "081ea72c-e270-46db-8703-e5afc9887ba1",
    "host": "localhost:8100",
    "x-forwarded-port": "8800",
    "content-type": "application/json",
    "connection": "Keep-Alive",
    "x-forwarded-for": "0:0:0:0:0:0:0:1",
    "accept-encoding": "gzip, deflate, br",
    "user-agent": "PostmanRuntime/7.26.2",
    "accept": "*/*"
}

Therefore I will not be able to find the token there either. Is it maybe my dependencies? I only integrated the jjwt dependency for the token. Does anyone have a solution? Been sitting on this bug for several hours

Upvotes: 1

Views: 10103

Answers (2)

Saddam Hussain
Saddam Hussain

Reputation: 156

If request is the Request object, then you can do:

request.getHeader(HttpHeaders.AUTHORIZATION);

Upvotes: 0

Alexandre Couzi
Alexandre Couzi

Reputation: 38

You should provide us the request you are sending to check if the token was send. Maybe you can also try receiving it like this by adding this header

@RequestHeader("Authorization") String token

Upvotes: 1

Related Questions