#JWT Authentication is not working in my spring boot project. 401 Unauthorized is appearing.

4 messages · Page 1 of 1 (latest)

devout harbor
#

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String jwt = request.getHeader(JwtConstants.JWT_HEADER);

    if (jwt != null) {
        System.out.println("jwtoriginal "+jwt.toString());
        jwt = jwt.substring(7);
        System.out.println("jwt "+jwt.toString());
        try {
            SecretKey key = Keys.hmacShaKeyFor(JwtConstants.SECRET_KEY.getBytes());
            System.out.println("key "+key);
            Claims claims = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jwt).getBody();
            System.out.println("claims "+claims);
            String email = String.valueOf(claims.get("email"));
            System.out.println("email "+email);
            String authorities = String.valueOf(claims.get("authorities"));
            System.out.println("authorities "+authorities);
            List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList(authorities);
            Authentication authentication = new UsernamePasswordAuthenticationToken(email, null, auths);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } catch (Exception e) {
            e.printStackTrace();;
            throw new BadCredentialsException("Invalid token.... from jwt validator");
        }
    }

    filterChain.doFilter(request, response);
}

While printing jwtoriginal it is showing as g== . From claims, there is no print statement.

In postman, requestbody of user contains,
{
"firstName":"Adwaith",
"lastName":"Manoj",
"email":"adwaith654@gmail.com",
"password":"123456",
"mobile":"9788787866"
}

User class : -

wraith carbonBOT
#

This post has been reserved for your question.

Hey @devout harbor! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

wraith carbonBOT