Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the username from the JWT?

I have 2 microservices. An API gateway and microservices that send messages to customers. My API returns a JWT token after authentication. The username of the user is contained in the token.

        public String extractUsername(String token)
        {
            return extractClaim(token, Claims::getSubject);
        }
        public Date extractExpiration(String token)
        {
            return extractClaim(token, Claims::getExpiration);
        }
        public <T> T extractClaim(String token, Function<Claims,T> claimsResolver)
        {
            final Claims claims = extractAllClaims(token);
            return claimsResolver.apply(claims);
        }
        private Claims extractAllClaims(String token)
        {
            return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
        }
        private Boolean isTokenExpired(String token)
        {
            return extractExpiration(token).before(new Date());
        }
        public String generateToken(UserDetails userDetails)
        {
            Map<String,Object> claims =new HashMap<>();
            return createToken(claims,userDetails.getUsername());
        }
        private String createToken(Map<String, Object> claims, String subject)
        {
            return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
                    .setExpiration(new Date(System.currentTimeMillis() + 1000*60*60*24*360))
                    .signWith(SignatureAlgorithm.HS256, SECRET_KEY).compact();
        }
        public Boolean validateToken(String token, UserDetails userDetails)
        {
            final String username = extractUsername(token);
            return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
        }

If I want to address my SendMessage microservice through the API gateway, he needs the username to send the message. I am currently passing on the username via Rest-Api. I would prefer that the SendMessage Microservice takes the username from the token. I have read that this works with the TokenEnhancer. But I have found no further information. Can someone tell me how I can do this or where I can find more information?

UPDATE

@GetMapping("/contacts/sms/{name}/{customer_phone_number}/{text}")
            public String sendSmsToCustomer(@PathVariable("name") String name,@PathVariable("customer_phone_number") String customer_phone_number, @PathVariable("text") String text) throws Exception
            {
            
String user= getUsernameFromToken(HttpServletRequest request);
            
            
            SmsSubmissionResponse responses = client.getSmsClient().submitMessage(new TextMessage(
                    name,
                    customer_phone_number,
                    text));
            for (SmsSubmissionResponseMessage response : responses.getMessages()) {
                System.out.println (response);
            }
        
            if (responses.getMessages().get(0).getStatus() == MessageStatus.OK) {
                String date=new SimpleDateFormat("yyyy.MM.dd - HH:mm:ss").format(new java.util.Date());
                    SQL_Connection.SaveDataInSmsDB(name, customer_phone_number, text,date);
                    return "Message sent successfully.";
                } else {
                    return "Message failed with error: " + responses.getMessages().get(0).getErrorText();
                }
            }

UPDATE 2

@GetMapping("/contacts/sms/{name}/{customer_phone_number}/{text}")
            public String sendSmsToCustomer(@RequestHeader(HEADER_STRING) HttpServletRequest request, @PathVariable("name") String name,@PathVariable("customer_phone_number") String customer_phone_number, @PathVariable("text") String text) throws Exception
            {
            String user= getUsernameFromToken(request);
            System.out.println(user);
{
    "timestamp": "2020-07-07T08:08:34.975+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "Missing request header 'Authorization' for method parameter of type HttpServletRequest",
    "path": "/contacts/sms/segos/44256674/hallo%20Container%20kommt"
}
like image 590
Doncarlito87 Avatar asked Nov 03 '25 07:11

Doncarlito87


2 Answers

You can extract user from Token using below code

 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;

        }

You can refer the full code and project

https://github.com/techiesantosh/taskmanager-service/blob/develop/src/main/java/com/web/taskmanager/auth/TokenAuthenticationService.java

like image 186
techiesantosh Avatar answered Nov 05 '25 01:11

techiesantosh


Use following to parse username from jwt token

 final String authHeader = request.getHeader("Authorization");
    String username = null;
    String jwt = null;

    if (authHeader != null && authHeader.startsWith("Bearer")) {
        jwt = authHeader.substring(7);
        username = jwtUtil.extractUsername(jwt);
    }
like image 27
Aditya Avatar answered Nov 05 '25 01:11

Aditya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!