【问题标题】:sprin mvc 5 rest + aouth 2 + angular 6 - oauth/token ‘Access-Control-Allow-Origin’ missingspring mvc 5 rest + oauth2 + angular 6 - oauth/token ‘Access-Control-Allow-Origin’缺失
【发布时间】:2019-02-25 18:17:18
【问题描述】:

我正在使用 spring mvc 5 和 angular 6 启动应用程序,当我尝试通过发送带有 angular 的发布请求来获取令牌时,它会在我的浏览器控制台中显示此消息:

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).

这是我的弹簧配置:

@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);
}
}

我的资源服务器配置类:

@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')");

}
}

这是我的网络安全配置器类:

@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);
}


}

这是我的 APP 初始化程序:

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;
}

}

我的自定义过滤器:

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() {
}
} 

我的角度服务:

  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'
  })});

}

我的问题是如何让 Angular HttpClient 发送这个 post 请求来生成令牌

【问题讨论】:

  • 请调试您的浏览器并在此处发布结果。您应该会在 chrome 开发工具的网络选项卡下找到 401 错误。

标签: spring angular spring-mvc spring-security spring-oauth2


【解决方案1】:

尽量为您的 CorsFilter 实现设置最高优先级。

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
    ...
}

【讨论】:

  • 我通过在我的过滤器上添加设置允许的方法来解决问题,感谢“Valentyn Riabukhin”的帮助!
【解决方案2】:

你需要定义proxy.conf.json 我们可以做

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

请通过 npm "npm start" 运行

【讨论】:

  • 感谢您的帮助!但这对我不起作用!问题是当我禁用弹簧安全模块时 - 一切都会正常工作&当我启用安全时它说:(原因:CORS 标头“Access-Control-Allow-Origin”缺失)
猜你喜欢
  • 2018-11-09
  • 2021-11-10
  • 2021-02-11
  • 1970-01-01
  • 2016-12-28
  • 2012-07-14
  • 2019-05-12
  • 2013-09-14
  • 2019-02-07
相关资源
最近更新 更多