title: spirng boot 2 jwt oauth2 + angular 5 can't get the JWT
body: <p>I'm new working with spring boot and spring security and I'm trying to implement oauth2 to generate a JWT and used this token in an angular5 application, my situation is that after implementation I can get the token if a use postman or curl but when I use my web client in angular I can't get the token.</p>
  
  <p><a href="https://i.stack.imgur.com/oQhku.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oQhku.png" alt="Imagen when a do the request by postman"></a></p>
  
  <p><a href="https://i.stack.imgur.com/D3rFg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D3rFg.png" alt="Imagen when a do the request by curl"></a></p>
  
  <p><a href="https://i.stack.imgur.com/5vAAo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5vAAo.png" alt="Imagen when a do the request by angular"></a></p>
  
  <p>this is what I did.</p>
  
  <p>My login method is angular </p>
  
  <pre><code>login(username: string, password: string ) {
      const params:  HttpParams = new  HttpParams();
      const headers: Headers = new Headers();
  
      params.set('username', 'GDELOSSANTOS');
      params.set('password', 'ADMIN');
      params.set('client_id', 'ADMIN');
      params.set('client_secret', 'ADMIN');
      params.set('grant_type', 'password');
      params.set('scope', '*');
  
      headers.set('Content-Type', 'application/x-www-form-urlencoded');
  
        return this.http.post(Constante.BACKEND_TOKEN_REQUEST, {headers}, {params} ).subscribe
            (res =&gt; this.setSession);
    }
  </code></pre>
  
  <p>My authorization server</p>
  
  <pre><code>@Configuration
  @EnableAuthorizationServer
  public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  
      private static final Logger logger = LogManager.getLogger(AuthorizationServerConfig.class);
  
      @Value("${security.oauth2.resource.id}")
      private String resourceId;
  
      @Autowired
      @Qualifier("authenticationManagerBean")
      private AuthenticationManager authenticationManager;
  
      @Override
      public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
          oauthServer.tokenKeyAccess("permitAll()")
          .checkTokenAccess("isAuthenticated()");
      }
  
      @Override
      public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
          logger.traceEntry();
  
          clients
          .inMemory()
          .withClient(ConstanteUtil.Seguridad.CLIEN_ID)
          .secret(Seguridad.CLIENT_SECRET)
          .authorizedGrantTypes(Seguridad.GRANT_TYPE_PASSWORD, Seguridad.AUTHORIZATION_CODE, Seguridad.REFRESH_TOKEN, Seguridad.IMPLICIT )
          .authorities(UsusarioRoles.ROLE_ADMIN, UsusarioRoles.ROLE_USER)
          .resourceIds(resourceId)
          .scopes(Seguridad.SCOPE_READ, Seguridad.SCOPE_WRITE, Seguridad.TRUST)
          .accessTokenValiditySeconds(Seguridad.ACCESS_TOKEN_VALIDITY_SECONDS).
          refreshTokenValiditySeconds(Seguridad.FREFRESH_TOKEN_VALIDITY_SECONDS);
          logger.info("Configuracion " + clients);
          logger.traceExit();
      }
  
      @Bean
      @Primary
      public DefaultTokenServices tokenServices() {
          final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
          defaultTokenServices.setTokenStore(tokenStore());
          defaultTokenServices.setSupportRefreshToken(true);
          return defaultTokenServices;
      }
  
      @Override
      public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
          final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
          tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), accessTokenConverter()));
          endpoints.tokenStore(tokenStore())
          .tokenEnhancer(tokenEnhancerChain)
          .authenticationManager(authenticationManager);
      }
  
      @Bean
      public TokenStore tokenStore() {
          return new JwtTokenStore(accessTokenConverter());
      }
  
      @Bean
      public JwtAccessTokenConverter accessTokenConverter() {
          final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
          converter.setSigningKey("123");
          return converter;
      }
  
      @Bean
      public TokenEnhancer tokenEnhancer() {
          return new CustomTokenEnhancer();
      }
  
  }
  </code></pre>
  
  <p>My Resource Server</p>
  
  <pre><code>@Configuration
  @EnableResourceServer
  public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
  
      private static final Logger logger = LogManager.getLogger(AuthorizationServerConfig.class);
  
      @Value("${security.oauth2.resource.id}")
      private String resourceId;
  
      @Override
      public void configure(final HttpSecurity http) throws Exception {
          logger.traceEntry("Entrada configure");
          // @formatter:off
          http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
          .and()
          .authorizeRequests().anyRequest().permitAll();
          logger.info("Ejecucion de metodo " + http);
          // @formatter:on                
      }
  
      @Override
      public void configure(final ResourceServerSecurityConfigurer config) {
          config.resourceId(resourceId).stateless(true);  }
  }
  </code></pre>
  
  <p>The WebSecurity</p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  
      private static final Logger logger = LogManager.getLogger(WebSecurityConfig.class);
  
  
      @Autowired
      @Resource(name = "UsuarioService")
      private UserDetailsService userDetailsService;
  
      @Override
      @Bean
      public AuthenticationManager authenticationManagerBean() throws Exception {
          return super.authenticationManagerBean();
      }
  
      @Autowired
      public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
          logger.traceEntry("globalUserDetails", auth);
          auth.userDetailsService(userDetailsService)
          .passwordEncoder(encoder());
  
          logger.traceExit("globalUserDetails", auth);
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          logger.traceEntry();
          logger.info("ejecutando configuracion " + http);
          http.cors().disable()
          .csrf().disable()
          .anonymous().disable()
          .authorizeRequests()
          .antMatchers("/login", "/logout.do").permitAll() 
          .antMatchers("/**").authenticated()
          .and().formLogin().loginPage("/login").permitAll()
          .and().httpBasic();
  
          logger.info("se ejecuto configuracion " + http);
  
      }
  
      @Bean
      public BCryptPasswordEncoder encoder(){
          return new BCryptPasswordEncoder();
      }
  
      @Bean
      public FilterRegistrationBean corsFilter() {
          UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
          CorsConfiguration config = new CorsConfiguration();
          config.setAllowCredentials(true);
          config.addAllowedOrigin("*");
          config.addAllowedHeader("*");
          config.addAllowedMethod("*");
          source.registerCorsConfiguration("/**", config);
          FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
          bean.setOrder(0);
          return bean;
      }
  
      @Bean
      public WebMvcConfigurer corsConfigurer() {
          return new WebMvcConfigurerAdapter() {
              @Override
              public void addCorsMappings(CorsRegistry registry) {
                  registry.addMapping("/auth/token").allowedOrigins("http://localhost:9000");
              }
          };
      }
  }
  </code></pre>
  
  <p>The implementation of loadUserDetail of UserDetailService
  @Override
      public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
          logger.traceEntry("Iniciando loadUserByUsername");
          /<em>Here we are using dummy data, you need to load user data from
           database or other third party application</em>/
          try {
          Usuario usuario = findAllUsuarioRoleByName(username);
          logger.info("Se encontro el usaurio " + usuario);</p>
  
  <pre><code>    UserBuilder builder = null;
      if (usuario != null) {
          List&lt;String&gt; roles =  new ArrayList&lt;&gt;();
  
          Collection&lt;UsuarioRole&gt; usuarioRoleByUsuarioName = usuarioRoleRepository.findAllUsuarioRoleByUsuarioName(usuario.getNombreUsuario());
          logger.info("Roles encontrados " + usuarioRoleByUsuarioName.size());
          for(UsuarioRole usuarioRole : usuarioRoleByUsuarioName) {
              roles.add(usuarioRole.getRole().getNombreRole());
          }
  
          String[] rolesArray = new String[roles.size()];
          rolesArray = roles.toArray(rolesArray);
  
          builder = org.springframework.security.core.userdetails.User.withUsername(username);
          builder.password(new BCryptPasswordEncoder().encode(usuario.getClaveUsuario()));
          for (String string : rolesArray) {
              logger.debug("**** " + string);
          }
          builder.roles(rolesArray);
      } else {
          throw new UsernameNotFoundException("User not found.");
      }
  
      return builder.build();
      }finally {
          logger.traceExit("Finalizando loadUserByUsername");
      }
  }
  </code></pre>