请求的资源 Asp.Net Web Api Owin 和 Angular 8 上不存在 'Access-Control-Allow-Origin' header
No 'Access-Control-Allow-Origin' header is present on the requested resource Asp.Net Web Api Owin and Angular 8
我有一个具有 JWT Oauth 身份验证机制的 Asp.Net Web Api。所以在 Startup.cs
文件中,我定义了这样的 cors 策略:
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
并且我在 CustomOAuthProvider
class:
使用这样的验证票
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var allowedOrigin = "*";
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
if (!user.EmailConfirmed)
{
context.SetError("invalid_grant", "User did not confirm email.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
var ticket = new AuthenticationTicket(oAuthIdentity, null);
context.Validated(ticket);
}
}
如您所见,我在此处为响应 headers 定义:
var allowedOrigin = "*";
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
我无法在任何地方设置 EnableCors
,只能在 StartUp.cs
.
但是我在客户端收到这个错误(Angular 8):
Access to XMLHttpRequest at 'http://localhost:50522/oauth/token' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我正在尝试在 angular 中使用 login
方法,如下所示:
login(username: string, password: string, grant_type: string) {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.http.post<any>(`${environment.urlAddress}/oauth/token`, JSON.stringify({ username, password, grant_type }), { headers })
.pipe(map(user => {
console.log(user);
// store user details and jwt token in local storage to keep user logged in between page refreshes
console.log(user);
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
return user;
}))
}
我没明白到底是什么问题。
请帮忙。
已通过从 GrantResourceOwnerCredentials
方法中删除 context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
代码解决了这个问题。
而且我在 Startup.cs
的 ConfigureOAuthTokenGeneration(app)
代码之前更改了 app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
代码的运行时顺序
我有一个具有 JWT Oauth 身份验证机制的 Asp.Net Web Api。所以在 Startup.cs
文件中,我定义了这样的 cors 策略:
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
并且我在 CustomOAuthProvider
class:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var allowedOrigin = "*";
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
if (!user.EmailConfirmed)
{
context.SetError("invalid_grant", "User did not confirm email.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
var ticket = new AuthenticationTicket(oAuthIdentity, null);
context.Validated(ticket);
}
}
如您所见,我在此处为响应 headers 定义:
var allowedOrigin = "*";
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
我无法在任何地方设置 EnableCors
,只能在 StartUp.cs
.
但是我在客户端收到这个错误(Angular 8):
Access to XMLHttpRequest at 'http://localhost:50522/oauth/token' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我正在尝试在 angular 中使用 login
方法,如下所示:
login(username: string, password: string, grant_type: string) {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.http.post<any>(`${environment.urlAddress}/oauth/token`, JSON.stringify({ username, password, grant_type }), { headers })
.pipe(map(user => {
console.log(user);
// store user details and jwt token in local storage to keep user logged in between page refreshes
console.log(user);
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
return user;
}))
}
我没明白到底是什么问题。
请帮忙。
已通过从 GrantResourceOwnerCredentials
方法中删除 context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
代码解决了这个问题。
而且我在 Startup.cs
ConfigureOAuthTokenGeneration(app)
代码之前更改了 app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
代码的运行时顺序