title: Spring Boot Jwt returns access denied
body: <p>Hey everyone i have problem with jwt with Java.Here is the codes.
  Here is returned value from postman</p>
  
  <pre><code>{
      "timestamp": "2020-02-29T20:53:35.761+0000",
      "status": 403,
      "error": "Forbidden",
      "message": "Access Denied",
      "path": "/login"
  }
  </code></pre>
  
  <p>TokenManager.java</p>
  
  <pre><code>
  @Service
  public class TokenManager {
      private static final int expiredAt = 10 * 60 * 60 * 1000;
      Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
      public String generateToken(String username){
  
  
           return Jwts.builder().setSubject(username)
                  .setIssuedAt(new Date(System.currentTimeMillis()))
                  .setExpiration(new Date(System.currentTimeMillis() + expiredAt))
                  .signWith(key).compact();
      }
  
      public boolean tokenValidate(String token){
          if(getUserFromToken(token) != null &amp;&amp;  isExpired(token)) {
              return true;
          }
          return false;
      }
  
      public String getUserFromToken(String token){
          Claims claims = getClaims(token);
          return claims.getSubject();
      }
  
      public boolean isExpired(String token){
          Claims claims = getClaims(token);
          return claims.getExpiration().after(new Date(System.currentTimeMillis()));
      }
  
      private Claims getClaims(String token) {
          return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
      }
  } 
  </code></pre>
  
  <p>And then JwtTokenFilter.java</p>
  
  <pre><code>@Component
  public class JwtTokenFilter extends OncePerRequestFilter {
      @Autowired
      private TokenManager tokenManager;
      @Override
      protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                      @NotNull HttpServletResponse httpServletResponse,
                                      @NotNull FilterChain filterChain) throws ServletException, IOException {
  
  
          final String authHeader = httpServletRequest.getHeader("Authorization");
  
          String username = null;
          String token = null;
  
  
          if (authHeader != null &amp;&amp; authHeader.contains("Bearer")) {
              token = authHeader.substring(7);
              try {
                  username = tokenManager.getUserFromToken(token);
              } catch (Exception e) {
                  System.out.println(e.getMessage());
              }
          }
  
          if (username != null &amp;&amp; token != null
                  &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) {
              if (tokenManager.tokenValidate(token)) {
                  UsernamePasswordAuthenticationToken upassToken =
                          new UsernamePasswordAuthenticationToken(username, null, new ArrayList&lt;&gt;());
                  upassToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
                  SecurityContextHolder.getContext().setAuthentication(upassToken);
              }
          }
  
          filterChain.doFilter(httpServletRequest, httpServletResponse);
      }
  }
  
  And my custom UserDetailService
  
  </code></pre>
  
  <pre><code>@Service
  public class CustomUserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {
  
      @Autowired
      private UserRepository userRepository;
      @Override
      public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
          return userRepository.findByUsername(username);
      }
  }
  
  </code></pre>
  
  <p>Here is WebSecurityConfig</p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
      @Autowired
      private JwtTokenFilter tokenFilter;
      @Override
      protected void configure(HttpSecurity http) throws Exception {
  
          http.csrf().disable()
                  .authorizeRequests().antMatchers("/signup","/login").permitAll()
                  .anyRequest().authenticated();
  
  
          http.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class);
  
      }
  
      @Bean
      public AuthenticationManager getAuthenticationManager() throws Exception {
          return super.authenticationManagerBean();
      }
  
  }
  </code></pre>
  
  <p>And last one is my controller.I checked the request body and and print the data it just work fine but /login path returns access denied.</p>
  
  <pre><code>@RestController
  public class UserController {
      @Autowired
      private UserService userService;
      @Autowired
      private AuthenticationManager authenticationManager;
      @Autowired
      private TokenManager tokenManager;
  
      public UserController(UserService userService, AuthenticationManager authenticationManager, TokenManager tokenManager) {
          this.userService = userService;
          this.authenticationManager = authenticationManager;
          this.tokenManager = tokenManager;
      }
  
      @RequestMapping(value = "/signup", method = RequestMethod.POST)
      public ResponseEntity&lt;User&gt; signup(@RequestBody User user){
          return ResponseEntity.ok(userService.save(user));
      }
  
      @RequestMapping(value = "/login", method = RequestMethod.POST)
      public ResponseEntity&lt;String&gt; login(@Valid @RequestBody AuthRequest authRequest){
          try{
              authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authRequest.getUsername(),authRequest.getPassword()));
              return ResponseEntity.ok(tokenManager.generateToken(authRequest.getUsername()));
          }catch (Exception e){
              throw e;
          }
      }
  
  }
  </code></pre>
  
  <p>When I remove authenticationManager.authenticate method inside login function it returns a valid token.But when I add authenticationManager again it returns access denied.</p>