title: Spring boot +Spring security oauth2(jwt token) + angular5 frontend
body: <p>I am using the below technologies to handle login, authentication and Authorization purpose:
  Spring Boot
  Spring Security Oauth2 jwt token(running in one port 3032 local)
  Angular-5 is front end (with port 4200 in local)</p>
  
  <p>Please find the below configuration files  </p>
  
  <p><strong>Application.class</strong></p>
  
  <pre><code>@SpringBootApplication
  public class Application {
  
  public static void main(String[] args) {
      SpringApplication.run(Application.class, args);
    }
  }
  </code></pre>
  
  <p><strong>application.properties</strong> </p>
  
  <pre><code>server.port: 3032
  spring.datasource.driverClassName=org.postgresql.Driver
  spring.datasource.url=jdbc:postgresql://localhost:5433/CommandCenter
  spring.datasource.username=postgres
  spring.datasource.password=admin
  spring.jpa.generate-ddl=true
  
  spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
  spring.jpa.show-sql=true
  spring.jpa.hibernate.ddl-auto=none
  
  #Application specific
  authentication.oauth.clientid=springSecurityClient
  authentication.oauth.secret=P@ssw0rd
  authentication.oauth.tokenValidityInSeconds=86400
  spring.datasource.testOnBorrow=true
  spring.datasource.validationQuery=SELECT 1
  </code></pre>
  
  <p><strong>OAuth2ResourceServerConfig.class</strong>             </p>
  
  <pre><code>@Configuration
  @EnableResourceServer
  public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
  @Autowired
  private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
  
  @Autowired
  private CustomLogoutSuccessHandler customLogoutSuccessHandler;
  
  
  @Override
  public void configure(HttpSecurity http) throws Exception {
      http.exceptionHandling()
              .authenticationEntryPoint(customAuthenticationEntryPoint)
              .and()
              .logout()
              .logoutUrl("/oauth/logout")
              .logoutSuccessHandler(customLogoutSuccessHandler)
              .and()
              .csrf()
              .requireCsrfProtectionMatcher(
                      new AntPathRequestMatcher("/oauth/authorize"))
              .disable().headers().frameOptions().disable().and().sessionManagement()
              .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
              .authorizeRequests().antMatchers("/registration")
              .hasRole(Authority.Admin.name()).antMatchers("/users")
              .hasRole(Authority.User.name());
  }
  }
  </code></pre>
  
  <p><strong>OAuth2AuthorizationServerConfig.class</strong></p>
  
  <pre><code>    @Configuration
      @EnableAuthorizationServer
      public class OAuth2AuthorizationServerConfig extends
          AuthorizationServerConfigurerAdapter implements EnvironmentAware {
      @Autowired
      @Qualifier("authenticationManagerBean")
      private AuthenticationManager authenticationManager;
      private static final String ENV_OAUTH = "authentication.oauth.";
      private static final String PROP_CLIENTID = "clientid";
      private static final String PROP_SECRET = "secret";
      private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds"; 
      private RelaxedPropertyResolver propertyResolver;
  
      @Override
      public void configure(ClientDetailsServiceConfigurer clients)
              throws Exception {
          clients.inMemory()
                  .withClient(propertyResolver.getProperty(PROP_CLIENTID))
                  .scopes("read", "write")
                  .autoApprove(true)
                  .authorities(Authorities.ROLE_Admin.name(),
                          Authorities.ROLE_User.name())
                  .authorizedGrantTypes("password", "refresh_token")
                  .secret(propertyResolver.getProperty(PROP_SECRET))
                  .accessTokenValiditySeconds(
                          propertyResolver.getProperty(
                                  PROP_TOKEN_VALIDITY_SECONDS, Integer.class,
                                  1800));
      }
  
      @Override
      public void configure(AuthorizationServerEndpointsConfigurer endpoints)
              throws Exception {
          TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
          tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(),
                  accessTokenConverter()));
          endpoints.tokenStore(tokenStore()).tokenEnhancer(tokenEnhancerChain)
                  .accessTokenConverter(accessTokenConverter())
                  .authenticationManager(authenticationManager);
      }
  
  
      @Bean
      public TokenEnhancer tokenEnhancer() {
          return new CustomTokenEnhancer();
      }
  
      @Bean
      public TokenStore tokenStore() {
          return new JwtTokenStore(accessTokenConverter());
      }
  
      @Bean
      public JwtAccessTokenConverter accessTokenConverter() {
          JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
          KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(
                  new ClassPathResource("jwt.jks"),
                  "JjbGllbnRfaWQiOiJyYWppdGhhcHAiLC".toCharArray());
          converter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt"));
          return converter;
      }
  
  
      @Override
      public void setEnvironment(Environment environment) {
          this.propertyResolver = new RelaxedPropertyResolver(environment,
                  ENV_OAUTH);
      }
  
      }
  </code></pre>
  
  <p><strong>Web security configuration</strong></p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  
  @Autowired
  private UserDetailsService userDetailsService;
  
  @Bean
  public PasswordEncoder passwordEncoder(){
      return new BCryptPasswordEncoder();
  }
  
  @Bean
  public DaoAuthenticationProvider authProvider() {
      DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
      authProvider.setUserDetailsService(userDetailsService);
      authProvider.setPasswordEncoder(passwordEncoder());
      return authProvider;
  }
  @Autowired
  public void configure(AuthenticationManagerBuilder auth)
          throws Exception {
      auth.authenticationProvider(authProvider());
  
  }
  
  @Override
  public void configure(WebSecurity web) throws Exception {
      web.ignoring();
  }
  
  @Override
  @Bean
  public AuthenticationManager authenticationManagerBean() throws Exception {
      return super.authenticationManagerBean();
  }
  }
  </code></pre>
  
  <p><strong>CORS filter configuration</strong></p>
  
  <pre><code>@Component
  @Order(Ordered.HIGHEST_PRECEDENCE)
  public class SimpleCorsFilter implements Filter {
  
  public SimpleCorsFilter() {
  }
  
  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
      HttpServletResponse response = (HttpServletResponse) res;
      HttpServletRequest request = (HttpServletRequest) req;
  
      Enumeration&lt;String&gt; headerNames = request.getHeaderNames();
  
      if (headerNames != null) {
              while (headerNames.hasMoreElements()) {
                      System.out.println("Header: " + request.getHeader(headerNames.nextElement()));
              }
      }
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
      response.setHeader("Access-Control-Max-Age", "3600");
      response.setHeader("Access-Control-Allow-Headers", "Origin, x-requested-with, Content-Type, Accept, Authorization");
  
      if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
          response.setStatus(HttpServletResponse.SC_OK);
      } else {
          chain.doFilter(req, res);
      }
  }
  
  @Override
  public void init(FilterConfig filterConfig) {
  }
  
  @Override
  public void destroy() {
  }
  }
  </code></pre>
  
  <p><strong>And front end angular 5 is</strong></p>
  
  <pre><code>login() {
  if(this.auth.username &amp;&amp; this.auth.password) {
      this.loginButton = true;
      this.LoginUnauthorized = false;
      this.authenticationService.login(this.auth.username, this.auth.password)
          .subscribe(
              data =&gt; {
                  if (data) {
                      this.cookieService.set('access_token', data.access_token);
                      this.cookieService.set('refresh_token', data.refresh_token);
                      this.cookieService.set('jti', data.jti);
                       this.cookieService.set('token_type',data.token_type)
                       this.cookieService.set('scope',data.scope);
                       this.cookieService.set('loginUser',this.auth.username);
                      this.authenticationService.getLoggedInUserRoles().subscribe(
      data =&gt; console.log(data),
      err =&gt; console.log(err)
    );
  
                  }
              },
              error =&gt; {
                  this.LoginUnauthorized = true
                  this.auth.username ="" , this.auth.password = "";
                  this.loginButton = false;
              });
  }
  }
  login(username: string, password: string) {
  
      let headers = new HttpHeaders();
      var urlBase = 'http://localhost:3032/oauth/token?grant_type=password&amp;username=' + username +'&amp;password=' + password;
  headers = headers.append('Authorization', 'Basic ' + btoa('springSecurityClient' + ':' + 'P@ssw0rd'));
      return this.http.post&lt;any&gt;(urlBase, {username, password}, {headers:headers})
  .map(res =&gt; {
      return res;
  });
  
  }
  
  getLoggedInUserRoles() {
      var urlBase = 'http://localhost:3032/AuthUser/';      
      return this.http.get&lt;any&gt;(urlBase);     
  
  }
  </code></pre>
  
  <p>Here coming to my prbm is </p>
  
  <p>I can able to login with <a href="http://localhost:4200" rel="nofollow noreferrer">http://localhost:4200</a></p>
  
  <p>But after login need to get the list of roles by</p>
  
  <p><a href="http://localhost:4200/AuthUser" rel="nofollow noreferrer">http://localhost:4200/AuthUser</a></p>
  
  <p>I am getting the below error in browser looks like again redirecting to login page please help me on this.</p>
  
  <pre><code>HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:3032/login", ok: false, …}
  error
  :
  {error: SyntaxError: Unexpected token &lt; in JSON at position 0 at JSON.parse (&lt;anonymous&gt;) at XMLHttp…, text: "&lt;html&gt;&lt;head&gt;&lt;title&gt;Login Page&lt;/title&gt;&lt;/head&gt;&lt;body …b-f01c9e439632" /&gt;↵&lt;/table&gt;↵&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;"}
  headers
  :
  HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
  message
  :
  "Http failure during parsing for http://localhost:3032/login"
  name
  :
  "HttpErrorResponse"
  ok
  :
  false
  status
  :
  200
  statusText
  :
  "OK"
  url
  :
  "http://localhost:3032/login"
  __proto__
  :
  HttpResponseBase
  </code></pre>
  
  <p>And while trying to access directly <strong>localhost:3032</strong> can able to get the roles</p>
  
  <p>In SoapUI i can able to see error like below</p>
  
  <blockquote>
    <p>{    "timestamp": 1515303716945,    "status": 403,    "error":
    "Forbidden",    "message": "Could not verify the provided CSRF token
    because your session was not found.",    "path": "/AuthUser" }</p>
  </blockquote>