Jos*_*rán 3 spring-security oauth-2.0 spring-security-oauth2 angular angular5
我是新手,使用Angular HttpClient(也写英文)
我有一个问题,我正在尝试使用POST方法发送HTTP请求,以便协商OAuth令牌阻塞,但是angular发送OPTIONS请求:
服务:
login(username: string, password: string) {
const body = `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}&grant_type=password`;
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa(TOKEN_AUTH_USERNAME + ':' + TOKEN_AUTH_PASSWORD)
})
};
return this.http.post<string>(AuthenticationService.AUTH_TOKEN, body, httpOptions);
Run Code Online (Sandbox Code Playgroud)
结果:
对于我的后端,我使用的是Spring Security,并且添加了一个过滤器以允许CORS:
@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;
}
Run Code Online (Sandbox Code Playgroud)
它与角度无关,而是您的浏览器在做。
我假设您的服务器运行在localhost:8080,而您的角度应用程序运行在localhost:4200。由于您的请求是跨源请求,因此浏览器首先发送一个OPTIONS请求以查看它是否安全。此时,您的服务器返回带有HTTP代码401的响应,该响应阻止发出发布请求。您必须在服务器中进行一些配置,或者可以使用webpack代理。这仅适用于您的本地计算机。如果您从服务器提供捆绑的angular应用程序,那么您将无需为生产做任何事情。我使用这种技术已经有一段时间了,并且效果很好。
例,
用户从mydomain.com/ng-app访问我的角度应用程序,我也从同一个域mydomain.com/api提供我的其余api
因此,我的应用程序总是向正在服务的服务器发出请求,从而不会在生产中造成任何问题。
对于后者,您可以执行以下操作
proxy.conf.json在项目的根目录(旁边package.json)中创建一个,然后在其中放入以下内容
{
"/api/": {
"target": "http://localhost:8080",
"secure": false,
"changeOrigin": true
}
}
Run Code Online (Sandbox Code Playgroud)
在package.json中,编辑start脚本并制作它ng serve --proxy-config proxy.conf.json
另外,不要从前端将请求直接发送到localhost:8080,而要编写类似http.post('/api/getSomeData')将请求发送到localhost:4200的东西,然后将其重定向到localhost:8080。这样,您将不必处理CORS。
| 归档时间: |
|
| 查看次数: |
5341 次 |
| 最近记录: |