Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 角度8+;Jwt+;[授权]+;dotnetcore2.1api+;Chrome post请求失败,出现cors错误_C#_Angular_.net Core_Jwt_Token - Fatal编程技术网

C# 角度8+;Jwt+;[授权]+;dotnetcore2.1api+;Chrome post请求失败,出现cors错误

C# 角度8+;Jwt+;[授权]+;dotnetcore2.1api+;Chrome post请求失败,出现cors错误,c#,angular,.net-core,jwt,token,C#,Angular,.net Core,Jwt,Token,我知道这是我过去遇到的一个非常常见的问题,但我总是能够在DotNet Core Api startup.cs中启用cors来处理它,但这次发生的事情似乎有点奇怪 我的Angular 8应用程序在登录时首先执行post请求(该请求不包含httpHeader,因为还没有令牌),并且它可以工作(我之前已启用cors使其工作) 在我得到一个令牌后,我将其存储在localstorage中以备以后使用,但令我大吃一惊的是,当api控制器有[Authorize]标记并且post包含带有令牌的标头时,请求失败,

我知道这是我过去遇到的一个非常常见的问题,但我总是能够在DotNet Core Api startup.cs中启用cors来处理它,但这次发生的事情似乎有点奇怪

我的Angular 8应用程序在登录时首先执行post请求(该请求不包含httpHeader,因为还没有令牌),并且它可以工作(我之前已启用cors使其工作)

在我得到一个令牌后,我将其存储在localstorage中以备以后使用,但令我大吃一惊的是,当api控制器有[Authorize]标记并且post包含带有令牌的标头时,请求失败,出现cors错误,甚至没有命中服务器方法

vscode控制台中出现错误:

Access to XMLHttpRequest at 'http://localhost:55909/api/manifest/add' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. [http://localhost:4200/]
Angular 8 post请求有效(登录),我得到返回(令牌):

失败的8 post请求:

this.headers = new HttpHeaders({
    'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('currentUser')).token,
    'Content-Type': 'application/json'
});

return this.http.post<any>(`${environment.apiUrl}/api/manifest/add`, { name, surname, seat, flight }, { headers: this.headers })
    .pipe(map(result => {
        return result;
    }));
startup.cs“ConfigureServices”方法,其中我启用cors:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    // Add functionality to inject IOptions<T>
    services.AddOptions();

    // Add our Config object so it can be injected
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

    services.AddCors(o => o.AddPolicy("Cors", builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowCredentials()
               .AllowAnyHeader();
    }));

    //Add repository to scope
    services.AddScoped<UserRepository>();
    services.AddScoped<PassengerRepository>();

    //sql connection and context (with crypted pass)
    var connection = getConnectionString();
    services.AddDbContext<Context>(options => options.UseSqlServer(connection));
}
public void配置服务(IServiceCollection服务)
{
AddHttpContextAccessor();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//添加功能以注入IOptions
services.AddOptions();
//添加我们的配置对象,以便可以注入它
services.Configure(Configuration.GetSection(“AppSettings”);
services.AddCors(o=>o.AddPolicy(“Cors”,builder=>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader();
}));
//将存储库添加到范围
services.addScope();
services.addScope();
//sql连接和上下文(带有加密的过程)
var connection=getConnectionString();
services.AddDbContext(options=>options.UseSqlServer(connection));
}
奇怪的是,如果我从“Add”方法中删除[Authorize]指令,它就会工作,但我显然会丢失令牌验证


请帮忙:)

经过几个小时的苦苦挣扎,我发现:

首先我忘了用

app.UseAuthentication();
在startup.cs中配置

第二,而不是仅仅

[Authorize]
我必须使用

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
定义默认验证架构

第三,我不知道我必须安装

"AspNet.Security.OAuth.Validation"
实现令牌验证。是通过Nuget manager完成的

现在它起作用了,所以我回答我自己的问题,我希望这能帮助其他有同样问题的人

编辑1:避免“401未授权”错误

通过上面提到的所有步骤,我让控制器方法开始被命中,但响应总是401(即使有有效的令牌),因此我必须在启动时添加下一段代码,以使其正确验证:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("thisisasupersecuresecretkey")),
                        RequireSignedTokens = false,
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = "http://localhost:55909",
                        ValidAudience = "http://localhost:55909"
                    };
                });
我知道显然有很多不同的方法来实现这一点,但在我的案例中,这段代码的组合对于case的基本使用是有效的

[Authorize]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
"AspNet.Security.OAuth.Validation"
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("thisisasupersecuresecretkey")),
                        RequireSignedTokens = false,
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = "http://localhost:55909",
                        ValidAudience = "http://localhost:55909"
                    };
                });