-1

i'm starting an app with spring mvc 5 & angular 6, when i try to get the token by sending a post request with angular it show in my browser console this message:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/gestion/oauth/token. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

this is my spring configuration :

@Configuration
@EnableAuthorizationServer

@EnableGlobalMethodSecurity(prePostEnabled = true)
@Import(ServerSecurityConfig.class)
public class AuthServerOAuth2Config extends AuthorizationServerConfigurerAdapter {

@Autowired
private DataSource dataSource;

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private UserDetailsService userDetailsService;

@Autowired
private PasswordEncoder oauthClientPasswordEncoder;

@Bean
public TokenStore tokenStore() {
    return new JdbcTokenStore(dataSource);
}

@Bean
public OAuth2AccessDeniedHandler oauthAccessDeniedHandler() {
    return new OAuth2AccessDeniedHandler();
}

@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
    oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()").passwordEncoder(oauthClientPasswordEncoder);
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.jdbc(dataSource);
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {

    endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager).userDetailsService(userDetailsService);
}
}

My Resource Server Configuration class :

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

@Override
public void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable()
    .requestMatchers().antMatchers("/api/**").and().authorizeRequests()
    .antMatchers(HttpMethod.POST, "/api/**").access("#oauth2.hasScope('write')")
    .anyRequest().access("#oauth2.hasScope('read')");

}
}

This is my Web Security Configurer class:

@Configuration
@EnableWebSecurity
@Import(Encoders.class)
public class ServerSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Autowired
private PasswordEncoder userPasswordEncoder;

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(userPasswordEncoder);
}


}

This my APP Initializer:

public class AppInitializer extends  AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] { 
            AppConfig.class};
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return null;
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}

@Override
protected Filter[] getServletFilters() {
        Filter [] filters = {new CorsFilter()};
        return filters;
}

}

My Custom Filter:

public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
} 

My angular service:

  public login(credentials: any): Observable<any> {
const body = `username=${credentials.username}&password=${credentials.password}&grant_type=password&client_id=admin`;
return this.httpClient.post<any>(this.URL, body, { headers: new HttpHeaders({
    'Authorization': `Basic ${btoa('admin:admin')}`,
    'Content-type': 'application/x-www-form-urlencoded'
  })});

}

my question is how to make Angular HttpClient send this post request to generate token

Djamel Kr
  • 759
  • 1
  • 4
  • 14
  • Please debug your browser and post the result here. You should find an 401 error under the network tab of chrome dev tools. – AchillesVan Sep 21 '18 at 12:42

2 Answers2

0

You need to define proxy.conf.json we can do

{
  "/serverapplicationName/*": {
    "target": "http://localhost:8080",
    "secure": false,
    "logLevel":"debug",
    "changeOrigin": true
  }
}

and please run by npm "npm start"

  • thanks for help !! but it didn't work for me !! the problem is when i disable the spring security module - everything will work fine & when i enable the security its says : (Reason: CORS header ‘Access-Control-Allow-Origin’ missing) – Djamel Kr Sep 21 '18 at 18:33
0

Try to make highest priority to your CorsFilter implementation.

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
    ...
}
  • I resolve the problem by just adding set allowed methods on my filter, Thank you "Valentyn Riabukhin" for helping !! – Djamel Kr Sep 21 '18 at 22:59