继续我的移动应用程序开发学习过程,我发现了一个新的障碍:跨源请求共享或CORS.
我正在使用AngularJS + jQuery Mobile(Cordova手机客户端)和ASP.NET Web API(后端)的组合.我的问题是我无法完成对API控制器的POST请求(或任何其他类型的请求).
我的AngularJS控制器使用$http.post()服务方法来调用Web API控制器.但是,Chrome调试器表示OPTIONS请求中的调用失败(可能是CORS预检请求).
我已经从以下帖子实现了CORS操作选择器:在Web API项目中启用CORS.即使很难,我也可以从Fiddler调用api方法,AngularJS一直在OPTIONS预检请求上失败.
关于AngularJS和跨域调用,我应该注意什么?我困境的任何可能解决方案?
谢谢.
是否可以自动将Access-Control-Allow-Origin标题添加到由X-Requested-With金字塔中的ajax请求(带标题)启动的所有响应中?
我正在为JSON运行$ http.get并且状态为0.我已经下载了相同的JSON并且get在本地工作,而在Python中使用请求库我可以得到JSON没问题,但是AngularJS它没有用.我不明白为什么角度没有得到它,但其他一切都是.下面的代码片段.
function AgentListCtrl($scope, $http) {
$http.get('http://foo.bar/api/objects').success(function(data) {
$scope.objects = data;
}).error(function(data, status) {
$scope.status1 = status;
});
Run Code Online (Sandbox Code Playgroud)
这提供了JSON并在使用本地文件时对其进行解析,但否则会失败并将status1设置为0.
我有一个ASP.NET Web API,由三个不同的SPA调用.我正在为Web API使用Windows身份验证.我最初尝试在Web.config中配置CORS,如下所示:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:63342" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
Run Code Online (Sandbox Code Playgroud)
这导致了这个预检问题:
Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin (...) is therefore not allowed access.
Run Code Online (Sandbox Code Playgroud)
我通过在Global.asax.cs中添加以下方法解决了:
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.Flush();
}
}
Run Code Online (Sandbox Code Playgroud)
这种方法适用于单一SPA.我以为我可以去Web.config并添加其他类似的来源:
<add name="Access-Control-Allow-Origin" value="http://localhost:63342,http://localhost:63347,http://localhost:63345/>
Run Code Online (Sandbox Code Playgroud)
但显然这是不允许的.这产生了以下错误:
The 'Access-Control-Allow-Origin' header contains …Run Code Online (Sandbox Code Playgroud) 最近我开始实现一个带有angularjs和spring mvc的基于令牌的安全系统.其思路如下:1.访问/ user/authenticate获取安全令牌并将令牌保存到本地存储2.对于angularJS客户端发送的每个请求,使用拦截器将X-Auth-Token头注入请求.
在我的Spring后端,我实现了AuthenticationTokenProcessingFilter和CustomAuthenticationEntryPoint.第一个用于从标头中提取令牌并检查它是否有效,第二个用于在未对请求进行身份验证时返回401未授权状态.
请查找有关我的后端代码的一些详细信息
AuthenticationController.java
@RestController
@RequestMapping(value="user")
public class AuthenticationController {
@RequestMapping(value="authenticate", method = RequestMethod.POST)
public ResponseEntity<?> login(@RequestParam("email") String email,
@RequestParam("password") String password) {
//Check if user is valid and return token
}
}
Run Code Online (Sandbox Code Playgroud)
SecurityConfig.java
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UsersRepository usersRepo;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {...}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(
new AuthenticationTokenProcessingFilter(usersRepo),
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(this.corsFilter(), UsernamePasswordAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf().disable().exceptionHandling()
.and()
.httpBasic()
.authenticationEntryPoint(new CustomAuthenticationEntryPoint())
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/user/authenticate").permitAll() …Run Code Online (Sandbox Code Playgroud) 我坚持这2天我找不到解决方案.当我做一个AngularJS POST时,它在标题中发送OPTIONS并从API返回错误代码看起来没什么特别的.
$http.defaults.headers.post["Content-Type"] = "application/json";
$http.post(URL, JSON.stringify(data)).
success(function(data, status, headers, config) {
alert(data);
error(function(data, status, headers, config) {
console.log("Error");
});
Run Code Online (Sandbox Code Playgroud)
CORS在它具有Headers的API上启用,当我在Chrome中使用fiddler或POSTMan进行POST时,只有当我使用angularJS帖子它才能正常工作时它才能正常运行.
我为什么得到 OPTIONS /SubmitTicket HTTP/1.1 instead of POST?
POST需要做什么?我已经读过它,它说像CORS这样的东西正在添加OPTIONS标题,但为什么呢?
我一直在寻找解决这个问题的方法.
我有一个带有Laravel 4后端实现的AngularJS Web应用程序,如下所示:
http://app.mydomain.io/ = AngularJS web app
http://api.mydomain.io/ = Laravel Back-end
Run Code Online (Sandbox Code Playgroud)
在Laravel的routes.php文件中,我有以下PHP代码来设置Access-Control标头:
header('Access-Control-Allow-Origin: http://app.mydomain.io');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
Run Code Online (Sandbox Code Playgroud)
我还有一个登录请求的路由设置,如下所示:
Route::post('/login', function()
{
$email = Input::get('email');
$password = Input::get('password');
if (Auth::attempt(array('email' => $email, 'password' => $password)))
{
return "Success!";
} else {
return "Fail!";
}
});
Run Code Online (Sandbox Code Playgroud)
在AngularJS中,我有一个AuthService,如下所示:
app.factory('AuthService', ['$resource', '$q', '$cookieStore', function($resource, $q, $cookieStore) {
var user = null;
var Service = $resource('//api.mydomain.io/login/', {}, {});
return {
login: function(email, password) {
var deferred = $q.defer();
Service.save({email: email, …Run Code Online (Sandbox Code Playgroud) 我正在做一个CORS请求(来自angular资源)并执行预检OPTIONS调用.我确实有自定义标题行,我认为这就是它被调用的原因.
但是,如果我可以设置东西,以便自定义标题(我们称之为X-Auth-Token)不生成OPTIONS请求,我会徘徊?或者它是为任何自定义标题设置的石头行为?
OPTION请求正在触发服务器上的某些事务,我想摆脱它.