title: Getting 500 Internal serve "An Authentication object was not found in the SecurityContext" when trying from browser angular+ spring boot+ jwt
body: <p>I have issue in using @preAuthorize annotaton when i use this annotation in my get method inside a controller, when i send request from browser i get 500 internal server error "An Authentication object was not found in the SecurityContext" but when i send it through postman it is getting 200 ok status with response, please help me identifying the issue.</p>
  
  <p>Angular front end:</p>
  
  <pre><code>export class WelcomeservicedataService {
  
  
    constructor(private route:ActivatedRoute ,private http:HttpClient) { }
  
  
    ServiceHelloDatawithpath(name){
     return this.http.get(`${API_URL}/hello-world/${name}`);
    }
  </code></pre>
  
  <p>Subscriber:</p>
  
  <pre><code>  Message(){
    this.serverMessage.ServiceHelloDatawithpath(this.Username).subscribe(
    data=&gt; {
      this.message= JSON.parse(JSON.stringify(data)).response;
      this.called=true;
    },
    error=&gt;{
    this.message="Only Admin can access";
    this.error=true;
    }
    );
  </code></pre>
  
  <p>Web security configurer</p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  
      @Autowired
      private JwtUnAuthorizedResponseAuthenticationEntryPoint jwtAuthenticationEntryPoint;
  
      @Autowired
      private UserDetailsService jwtUserDetailsService;
  
      @Autowired
      private JwtTokenAuthorizationOncePerRequestFilter jwtRequestFilter;
  
      @Value("${jwt.get.token.uri}")
      private String authenticationPath; 
  
  
            @Override
            public void configure(AuthenticationManagerBuilder auth) throws Exception {
              auth.userDetailsService(jwtUserDetailsService);  // &lt;-- replacing the in-memory anthentication setup
            }
  
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
          // configure AuthenticationManager so that it knows from where to load
          // user for matching credentials
          // Use BCryptPasswordEncoder
          auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
      }
  
      @Bean
      public PasswordEncoder passwordEncoder() {
          return new BCryptPasswordEncoder();
      }
  
      @Bean
      @Override
      public AuthenticationManager authenticationManagerBean() throws Exception {
          return super.authenticationManagerBean();
      }
  
      @Override
      protected void configure(HttpSecurity httpSecurity) throws Exception {
          // Add a filter to validate the tokens with every request
  
          httpSecurity
                  // dont authenticate this particular request
                   .authorizeRequests().antMatchers(HttpMethod.POST,"/authenticate", "/register").permitAll().
                  // all other requests need to be authenticated
                  anyRequest()
              .authenticated().
              and().
                  // make sure we use stateless session; session won't be used to
                  // store user's state.
                  exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                  .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
  
          httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
  
          httpSecurity
          .authorizeRequests().antMatchers("/swagger-ui.html/").hasAuthority("ADMIN")
          .antMatchers("/hello-world/**").hasAuthority("ADMIN")
          .and()
          .csrf()                   
          .and()
      .exceptionHandling().accessDeniedPage("/Access_Denied");
      }
  
  
  
      @Override
      public void configure(WebSecurity webSecurity) throws Exception {
  
          webSecurity
          .ignoring()
          .antMatchers("/v2/api-docs/**") // enables api docs
          .and()
          .ignoring().antMatchers("/swagger-ui.html/**")// enable swagger
          .and()
          .ignoring().antMatchers("/actuator/**")// enables actuators
          .and()
          .ignoring().antMatchers("/**")
          .and()
              .ignoring()
              .antMatchers(
                  HttpMethod.POST,
                  authenticationPath)
              .antMatchers(HttpMethod.OPTIONS, "/**")
              .and()
              .ignoring()
              .antMatchers(
                  HttpMethod.GET,
                  "/products/**" //Other Stuff You want to Ignore
              )
              ;           
      }
  }
  </code></pre>
  
  <p>Authorization filter:</p>
  
  <pre><code>@Component
  public class JwtTokenAuthorizationOncePerRequestFilter extends OncePerRequestFilter {
  
      private final Logger logger = LoggerFactory.getLogger(this.getClass());
  
      @Autowired
      private UserDetailsService userService;
  
      @Autowired
      private JwtTokenUtil jwtTokenUtil;
  
      @Value("${jwt.http.request.header}")
      private String tokenHeader;
  
      @Override
      protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
          logger.debug("Authentication Request For '{}'", request.getRequestURL());
  
          final String requestTokenHeader = request.getHeader(this.tokenHeader);
  
          String username = null;
          String jwtToken = null;
          if (requestTokenHeader != null &amp;&amp; requestTokenHeader.startsWith("Bearer")) {
              jwtToken = requestTokenHeader.substring(7);
              try {
                  username = jwtTokenUtil.getUsernameFromToken(jwtToken);
              } catch (IllegalArgumentException e) {
                  logger.error("JWT_TOKEN_UNABLE_TO_GET_USERNAME", e);
              } catch (ExpiredJwtException e) {
                  logger.warn("JWT_TOKEN_EXPIRED", e);
              }
          } else {
              logger.warn("JWT_TOKEN_DOES_NOT_START_WITH_BEARER_STRING");
          }
  
          logger.debug("JWT_TOKEN_USERNAME_VALUE '{}'", username);
          if (username != null &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) {
  
              UserDetails userDetails = this.userService.loadUserByUsername(username);
  
              if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
                  UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),
                          userDetails.getPassword(), userDetails.getAuthorities());
                  usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
  
  
                  SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                 }
          }
  
          chain.doFilter(request, response);
      }
  }
  </code></pre>
  
  <p>Controller class: trying to hit @GetMapping("hello-world/")</p>
  
  <pre><code>package com.luv2code.springboot.thymeleafdemo.controller;
  
  import java.net.URI;
  import java.util.List;
  
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.http.HttpStatus;
  import org.springframework.http.ResponseEntity;
  import org.springframework.security.access.prepost.PreAuthorize;
  import org.springframework.web.bind.annotation.CrossOrigin;
  import org.springframework.web.bind.annotation.DeleteMapping;
  import org.springframework.web.bind.annotation.GetMapping;
  import org.springframework.web.bind.annotation.PathVariable;
  import org.springframework.web.bind.annotation.PostMapping;
  import org.springframework.web.bind.annotation.PutMapping;
  import org.springframework.web.bind.annotation.RequestBody;
  import org.springframework.web.bind.annotation.RestController;
  import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
  
  import com.luv2code.springboot.thymeleafdemo.entity.Employee;
  import com.luv2code.springboot.thymeleafdemo.entity.StringResponse;
  import com.luv2code.springboot.thymeleafdemo.service.EmployeeService;
  
  
  @RestController
  @CrossOrigin
  public class HelloWorldController {
  
  
      private EmployeeService producer; 
  
      @Autowired
      public HelloWorldController(EmployeeService producer) {
  
          this.producer = producer;
      }
  
  
  
      @GetMapping("/hello-world/{name}")
      @PreAuthorize("hasAuthority('ADMIN')")
      public StringResponse helloworld(@PathVariable String name){
          StringResponse hello= new StringResponse("welcome "+ name);
          return hello;
      }
  </code></pre>
  
  <p>when i'm using postman it works fine! but when i hit the same from broswer i"m getting error.</p>
  
  <p>Error:</p>
  
  <pre><code>2020-06-14 20:51:51.309  WARN 18320 --- [nio-8080-exec-3] wtTokenAuthorizationOncePerRequestFilter : JWT_TOKEN_DOES_NOT_START_WITH_BEARER_STRING
  2020-06-14 20:51:51.325 ERROR 18320 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext] with root cause
  
  org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
      at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:379) ~[spring-security-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
      at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:223) ~[spring-security-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
      at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:65) ~[spring-security-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at com.luv2code.springboot.thymeleafdemo.controller.HelloWorldController$$EnhancerBySpringCGLIB$$2a6a708f.helloworld(&lt;generated&gt;) ~[classes/:na]
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_221]
      at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_221]
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_221]
      at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_221]
      at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.13.jar:9.0.13]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at com.luv2code.springboot.thymeleafdemo.jwt.JwtTokenAuthorizationOncePerRequestFilter.doFilterInternal(JwtTokenAuthorizationOncePerRequestFilter.java:74) ~[classes/:na]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90) ~[spring-boot-actuator-2.1.1.RELEASE.jar:2.1.1.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:209) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
      at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
      at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117) ~[spring-boot-actuator-2.1.1.RELEASE.jar:2.1.1.RELEASE]
      at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106) ~[spring-boot-actuator-2.1.1.RELEASE.jar:2.1.1.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791) [tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417) [tomcat-embed-core-9.0.13.jar:9.0.13]
      at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.13.jar:9.0.13]
      at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_221]
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_221]
      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.13.jar:9.0.13]
      at java.lang.Thread.run(Unknown Source) [na:1.8.0_221]
  </code></pre>