首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Asp.net核心、JWT和CORS标头

Asp.net核心、JWT和CORS标头
EN

Stack Overflow用户
提问于 2016-01-26 07:51:30
回答 4查看 3K关注 0票数 5

当我在同一服务上同时启用JWT承载身份验证和CORS时,从服务器获取适当的Access-Control-Allow-Origin标头时遇到问题。当我从配置中删除UseJwtBearerAuthentication时,一切都正常。

代码语言:javascript
复制
public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("AllowAllOrigins", builder =>
            {
                builder.AllowAnyOrigin();
                builder.AllowAnyHeader();
                builder.AllowAnyMethod();
                builder.AllowCredentials();
            });
        });

        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseJwtBearerAuthentication(options =>
        {
            options.AutomaticAuthenticate = true;
            options.RequireHttpsMetadata = false;
            options.Audience = "c2cf422a-a432-2038-b183-cda64e16239e";
            options.Authority = "domain.com";
        });

        app.UseCors("AllowAllOrigins");

        app.UseIISPlatformHandler();

        app.UseMvc();
    }

我已经尝试更改配置的顺序,但似乎都不起作用。我还尝试将EnableCors("AllowAllOrigins")添加到我调用的控制器中。

我已经根据评论中的建议更改了配置顺序,并确定了导致问题的属性:

代码语言:javascript
复制
app.UseIISPlatformHandler();

        app.UseCors("AllowAllOrigins");

        app.UseJwtBearerAuthentication(options =>
        {
            options.AutomaticAuthenticate = true;
            options.RequireHttpsMetadata = false;
            options.Audience = "c8cf662a-ac73-4050-b285-cda90e22992e";
            options.Authority = "iwdwk.com";
        });

        app.UseMvc();

在上面的代码中,下面这行代码似乎是导致问题的原因:

代码语言:javascript
复制
options.AutomaticAuthenticate = true;

不幸的是,我需要启用它,这样我才能传递JWT令牌进行授权……除非有其他方法可以做到这点?

EN

Stack Overflow用户

发布于 2016-05-10 07:55:22

如果服务器抛出异常,它们会清除报头,因此您只会看到CORS错误。我过去了解实际情况的方法是,首先使用Chrome dev工具从我失败的请求中获取Bearer Token

接下来,我将该令牌复制并粘贴到Postman中,作为请求中Authorization标头的值。当我这样做的时候,我终于收到了一个很好的开发人员异常页面,它确切地告诉我我做错了什么。我使用的是Azure AD提供的ClientId GUID,而不是App URI

因此,如果你正在使用Azure AD,那么你的JWT选项应该如下所示:

代码语言:javascript
复制
    app.UseJwtBearerAuthentication(options =>
    {
        options.AutomaticAuthenticate = true;
        options.AutomaticChallenge = true;
        options.Authority = "https://login.microsoftonline.com/yourtenant.onmicrosoft.com"
        options.Audience = "https://yourtenant.onmicrosoft.com/AppURI"
    });
票数 1
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35004673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档