title: Getting Unauthorized error: Full authentication is required to access this resource
body: <p>I'm implementing <code>JWT</code> and <code>Spring Security</code> for authentication in my application.</p>
  <p>I have 3 roles: Admin, Moderator and User.</p>
  <p>For example, after logging with <strong>user role</strong>, I got the <strong>home page</strong>, but once I go to hit the <strong>user space</strong> by clicking on a button, I got:</p>
  <blockquote>
  <p>2020-09-04 09:01:22.819 ERROR 10148 --- [nio-8080-exec-5]
  c.b.s.security.jwt.AuthEntryPointJwt     : Unauthorized error: Full
  authentication is required to access this resource</p>
  </blockquote>
  <p>the file <strong>webSecurityConfig.java</strong> is:</p>
  <pre><code>@Configuration
  @EnableWebSecurity
  @EnableGlobalMethodSecurity(
          // securedEnabled = true,
          // jsr250Enabled = true,
          prePostEnabled = true)
  public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
      @Autowired
      UserDetailsServiceImpl userDetailsService;
  
      @Autowired
      private AuthEntryPointJwt unauthorizedHandler;
  
      @Bean
      public AuthTokenFilter authenticationJwtTokenFilter() {
          return new AuthTokenFilter();
      }
  
      @Override
      public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
          authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
      }
  
      @Bean
      @Override
      public AuthenticationManager authenticationManagerBean() throws Exception {
          return super.authenticationManagerBean();
      }
  
      @Bean
      public PasswordEncoder passwordEncoder() {
          return new BCryptPasswordEncoder();
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.cors().and().csrf().disable()
              .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
              .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
              .authorizeRequests().antMatchers(&quot;/api/auth/**&quot;).permitAll()
              .antMatchers(&quot;/api/test/**&quot;).permitAll()
              .anyRequest().authenticated();
  
          http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
      }
  }
  </code></pre>
  <ul>
  <li><p>The class <strong>AuthEntryPointJwt</strong> is:</p>
  <p>@Component
  public class AuthEntryPointJwt implements AuthenticationEntryPoint {</p>
  <pre><code>  private static final Logger logger = LoggerFactory.getLogger(AuthEntryPointJwt.class);
  
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException, ServletException {
        logger.error(&quot;Unauthorized error: {}&quot;, authException.getMessage());
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, &quot;Error: Unauthorized&quot;);
    }
  </code></pre>
  <p>}</p>
  </li>
  <li><p>The class <strong>AuthTokenFilter</strong> is:</p>
  <p>public class AuthTokenFilter extends OncePerRequestFilter {
  @Autowired
  private JwtUtils jwtUtils;</p>
  <pre><code>  @Autowired
    private UserDetailsServiceImpl userDetailsService;
  
    private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);
  
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        try {
            String jwt = parseJwt(request);
            if (jwt != null &amp;&amp; jwtUtils.validateJwtToken(jwt)) {
                String username = jwtUtils.getUserNameFromJwtToken(jwt);
  
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
  
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception e) {
            logger.error(&quot;Cannot set user authentication: {}&quot;, e);
        }
  
        filterChain.doFilter(request, response);
    }
  
    private String parseJwt(HttpServletRequest request) {
        String headerAuth = request.getHeader(&quot;Authorization&quot;);
  
        if (StringUtils.hasText(headerAuth) &amp;&amp; headerAuth.startsWith(&quot;Bearer &quot;)) {
            return headerAuth.substring(7, headerAuth.length());
        }
  
        return null;
    }
  </code></pre>
  <p>}</p>
  </li>
  <li><p>The class <strong>JwtUtils</strong> is:</p>
  <p>@Component
  public class JwtUtils {
  private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);</p>
  <pre><code>  @Value(&quot;${bezkoder.app.jwtSecret}&quot;)
    private String jwtSecret;
  
    @Value(&quot;${bezkoder.app.jwtExpirationMs}&quot;)
    private int jwtExpirationMs;
  
    public String generateJwtToken(Authentication authentication) {
  
        UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal();
  
        return Jwts.builder()
                .setSubject((userPrincipal.getUsername()))
                .setIssuedAt(new Date())
                .setExpiration(new Date((new Date()).getTime() + jwtExpirationMs))
                .signWith(SignatureAlgorithm.HS512, jwtSecret)
                .compact();
    }
  
    public String getUserNameFromJwtToken(String token) {
        return Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody().getSubject();
    }
  
    public boolean validateJwtToken(String authToken) {
        try {
            Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
            return true;
        } catch (SignatureException e) {
            logger.error(&quot;Invalid JWT signature: {}&quot;, e.getMessage());
        } catch (MalformedJwtException e) {
            logger.error(&quot;Invalid JWT token: {}&quot;, e.getMessage());
        } catch (ExpiredJwtException e) {
            logger.error(&quot;JWT token is expired: {}&quot;, e.getMessage());
        } catch (UnsupportedJwtException e) {
            logger.error(&quot;JWT token is unsupported: {}&quot;, e.getMessage());
        } catch (IllegalArgumentException e) {
            logger.error(&quot;JWT claims string is empty: {}&quot;, e.getMessage());
        }
  
        return false;
    }
  </code></pre>
  <p>}</p>
  </li>
  <li><p>The class <strong>AuthController</strong> is:</p>
  <p>@CrossOrigin(origins = &quot;*&quot;, maxAge = 3600)
  @RestController
  @RequestMapping(&quot;/api/auth&quot;)
  public class AuthController {
  @Autowired
  AuthenticationManager authenticationManager;</p>
  <pre><code>      @Autowired
        UserRepository userRepository;
  
        @Autowired
        RoleRepository roleRepository;
  
        @Autowired
        PasswordEncoder encoder;
  
        @Autowired
        JwtUtils jwtUtils;
  
        @PostMapping(&quot;/signin&quot;)
        public ResponseEntity&lt;?&gt; authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
  
            System.out.println(&quot;---------------- auth 1 &quot;);
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
  
            SecurityContextHolder.getContext().setAuthentication(authentication);
            String jwt = jwtUtils.generateJwtToken(authentication);
  
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();      
            List&lt;String&gt; roles = userDetails.getAuthorities().stream()
                    .map(item -&gt; item.getAuthority())
                    .collect(Collectors.toList());
  
            return ResponseEntity.ok(new JwtResponse(jwt, 
                                                     userDetails.getId(), 
                                                     userDetails.getUsername(), 
                                                     userDetails.getEmail(), 
                                                     roles));
        }
  
  
  
        @GetMapping(&quot;/user&quot;)
        @PreAuthorize(&quot;hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')&quot;)
        public String userAccess()
        {
            System.out.println(&quot;---------------- test User &quot;);
            return &quot;User Content.&quot;;
        }
    }
  </code></pre>
  </li>
  </ul>
  <p>The file <strong>application.properties</strong>, I put:</p>
  <pre><code>spring.datasource.url=...
  spring.datasource.username=...
  spring.datasource.password=...
  spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation= true
  spring.jpa.properties.hibernate.dialect=...
  spring.jpa.hibernate.ddl-auto=update
  bezkoder.app.jwtSecret= bezKoderSecretKey
  bezkoder.app.jwtExpirationMs= 86400000
  </code></pre>
  <p>In Browser console, I got <a href="https://i.stack.imgur.com/ABFMU.png" rel="nofollow noreferrer">that exception</a>.</p>
  <p>Could you please help me solving that issue ?. Big thanks.</p>