如何在 Asp.Net Core 2.0“AddJwtBearer"中设置多个受众中间件? [英] How to set multiple audiences in Asp.Net Core 2.0 "AddJwtBearer" middleware?

查看:17
本文介绍了如何在 Asp.Net Core 2.0“AddJwtBearer"中设置多个受众中间件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个针对 AAD 进行身份验证的 Asp.Net Core 2.0 WebApi:

I have an Asp.Net Core 2.0 WebApi which is authenticating against AAD:

            services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; })
                .AddJwtBearer(options =>
                            {
                                options.Authority = "https://login.microsoftonline.com/TENANT.onmicrosoft.com";
                                options.Audience = "CLIENT_ID";
                            });

我的 SPA 应用从 AAD 获取令牌并将其作为 bearer 标头发送.一切正常.

My SPA app gets the token from AAD and sent it as bearer header. All works fine.

我在 Azure Scheduler 中创建了一个作业并设置了 Active Directory OAuth:

I have create a Job in Azure Scheduler and setup Active Directory OAuth:

运行作业后出现此错误:Bearer error="invalid_token", error_description="The Audience is invalid".

After running a job I get this error: Bearer error="invalid_token", error_description="The audience is invalid".

当我将 AddJwtBearer(...) 中的 options.Audience 设置为 https://management.core.windows.net/Job 有效,但 SPA 无效.

When I set options.Audience in AddJwtBearer(...) to https://management.core.windows.net/ the Job works but not the SPA.

我想,我需要将 Audience 设置为数组 ['CLIENT_ID', "https://management.core.windows.net/"] 但是options.Audiencestring 的类型.如果我根本不设置 Audience,Spa 和 Job 都不起作用(401 未经身份验证).将 Audience 设置为 CLIENT_ID,https://management.core.windows.net/ 也不起作用.

I guess, I need to set Audience to an array ['CLIENT_ID', "https://management.core.windows.net/"] but the options.Audience is type of string. If I don't set Audience at all, both Spa and Job does not work (401 unauthenticated). Setting Audience to CLIENT_ID,https://management.core.windows.net/ does not work either.

有没有办法在 AddJwtBearer 中启用多个受众?

Is there a way how to enable multiple audiences in AddJwtBearer?

推荐答案

我想我遇到了和你一样的问题.为了让它发挥作用,我将观众从 options 转移到接受多个条目的 TokenValidationParameters 中.检查下面的代码:

I think I ran into the same problem as you. To make it work I moved audience from options and into the TokenValidationParameters, which accepts multiple entries. Check the code below:

.AddJwtBearer(options =>
{
    options.Authority = "https://login.windows.net/trades.no";
    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidAudiences = new List<string> 
        {
            "AUDIENCE1",
            "AUDIENCE2" 
        }
    };

这篇关于如何在 Asp.Net Core 2.0“AddJwtBearer"中设置多个受众中间件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆