title: Role Based Authorization using JWT - Spring security
body: <p>Hope you all are doing great! I am implementing JWT Role Based Authorization in spring boot.</p>
  <p>I have been able to implement it. The tutorial that I am following is this</p>
  <p><a href="https://github.com/only2dhir/spring-security-jwt" rel="nofollow noreferrer">https://github.com/only2dhir/spring-security-jwt</a></p>
  <p>The user is being sucessfully registered. And then I assign that user a role like ADMIN.</p>
  <p>Now I have this api <code> @GetMapping(&quot;/users&quot;)</code></p>
  <p>that should be accessed by ADMIN. However when I access this api, it gives me this error</p>
  <pre><code>java.lang.NullPointerException: Cannot invoke &quot;Object.toString()&quot; because the return value of 
  &quot;io.jsonwebtoken.Claims.get(Object)&quot; is null 
  </code></pre>
  <p>This errors comes from these methods:</p>
  <p>JwtTokenUtil:</p>
  <pre><code> public static final String AUTHORITIES_KEY = &quot;scopes&quot;;
   UsernamePasswordAuthenticationToken getAuthentication(final String token, final Authentication 
    exsitingAuth, final UserDetails userDetails){
  
      final JwtParser jwtParser = Jwts.parser().setSigningKey(secret);
  
      final Jws&lt;Claims&gt; claimsJws = jwtParser.parseClaimsJws(token);
  
      final Claims claims = claimsJws.getBody();
  
      final Collection&lt;? extends GrantedAuthority&gt; authorities=
      java.util.Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(&quot;,&quot;))
           .map(SimpleGrantedAuthority::new)
           .collect(Collectors.toList());
  
      return new UsernamePasswordAuthenticationToken(userDetails, &quot;&quot;, authorities);
  }
  </code></pre>
  <p>This line gives error</p>
  <pre><code> java.util.Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(&quot;,&quot;))
  </code></pre>
  <p>Creating authentication:</p>
  <pre><code> UserDetailsWithToken UserDetailsWithToken = new UserDetailsWithToken();
      authenticate(authenticationRequest.getEmpID(), 
   authenticationRequest.getPswd());
  
      final UserDetails userDetails = 
   userDetailsService.loadUserByUsername(authenticationRequest.getEmpID());
  
      
      final Authentication authentication = authenticationManager.authenticate(
              new UsernamePasswordAuthenticationToken(
                  authenticationRequest.getEmpID(),
                  authenticationRequest.getPswd()
              )
      );
      SecurityContextHolder.getContext().setAuthentication(authentication);
      
      final String token = 
     jwtTokenUtil.generateToken(userDetails,authentication);
      
  </code></pre>