【发布时间】:2017-11-01 21:36:22
【问题描述】:
我正在构建一个带有 Spring Boot 后端的 Angular 2 应用程序。我正在尝试解决 CORS 预检的问题好几天。根据这个topic,它应该像这样与CORS过滤器一起使用:
@Component
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, xsrf-token");
response.addHeader("Access-Control-Expose-Headers", "xsrf-token");
if ("OPTIONS".equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(request, response);
}
}
}
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class)
.headers()
.frameOptions().disable()
.and()
.authorizeRequests()
.antMatchers("/", "/home", "/register", "/login").permitAll()
.antMatchers("/cottages").authenticated();
}
}
角度前端:
import {Injectable} from '@angular/core';
import {Headers, Http} from "@angular/http";
import {AppSettings} from "../app.settings";
import { URLSearchParams } from '@angular/http'
import {User} from "../_models/_index";
import {Observable} from "rxjs";
@Injectable()
export class AuthenticationService {
private headers = new Headers({'Content-Type': 'application/json'});
private tokenHeaders = new Headers({
'Content-Type': 'application/json',
'client_id': 'xxx',
'client_secret': 'xxx'});
constructor(private http: Http) {
}
login(user: User) {
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('username', user.username);
urlSearchParams.append('password', user.password);
let body = urlSearchParams.toString();
return this.http.post(AppSettings.getApiUrl() + "oauth/token", body, { withCredentials: true, headers: this.tokenHeaders })
.map((responseData) => {
return responseData.json();
})
.map((item: any) => {
return new User(item);
})
.catch((error: any) => Observable.of(error.json().error || 'Server error'));
}
}
我尝试了在 this 和 Spring 文档的其他来源中找到的其他配置。
我总是收到此错误消息:
跨域请求被阻止:同源策略不允许读取 http://localhost:8080/oauth/token 的远程资源。 (原因: CORS 预检通道未成功)。
对我自己的控制器的简单 CORS 请求(例如注册用户)效果很好。
谁能向我解释我做错了什么?我的 Java 或 Typescript 代码有错误吗?
编辑:
授权服务器配置:
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("my-trusted-client").authorizedGrantTypes("client_credentials", "password")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT").scopes("read", "write", "trust")
.resourceIds("oauth2-resource").accessTokenValiditySeconds(5000).secret("xxx");
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.checkTokenAccess("isAuthenticated()");
}
}
【问题讨论】:
-
您是否将路径
/oauth/token添加到您的permitAll()部分? -
感谢您的回答@ochi。我没有。我在 ResourceServerConfiguration 中尝试过这种方式:
.authorizeRequests().antMatchers("/", "/oauth/token").permitAll().antMatchers("/cottages").authenticated();不幸的是它不能解决问题或让我出错?
标签: typescript spring-boot spring-security cors spring-security-oauth2