【问题标题】:Unable to get Azure AD token in PostMan无法在 PostMan 中获取 Azure AD 令牌
【发布时间】:2020-01-14 07:38:12
【问题描述】:

我正在研究 .Net 核心 Azure AD 身份验证。我创建了示例 .Net 核心应用程序。下面是我的代码。

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAd", options));

            services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
                options.Authority = options.Authority + "/v2.0/";
                options.TokenValidationParameters.ValidateIssuer = false;
            });

            services.AddMvc(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
            });
    }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseHttpsRedirection();

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });
            app.UseAuthentication();
            app.UseMvc();
        }

下面是我的配置文件。

 "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "[Enter the domain of your tenant, e.g. contoso.onmicrosoft.com]",
    "TenantId": "organizations",
    "ClientId": "",
    "CallbackPath": "/signin-oidc"
  }

下面是我的控制器代码。

[Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }

上面的代码工作正常。我能够点击 api 并获得价值。所以我假设我的身份验证工作正常。我正在尝试从邮递员那里获取此 API,因此我正在尝试在邮递员中获取令牌。

我收到错误无法完成 OAuth 2.0 登录。有人可以帮我解决这个问题吗?任何帮助,将不胜感激。谢谢

【问题讨论】:

    标签: azure authentication jwt azure-active-directory


    【解决方案1】:

    这是一个complete sample,它使用 Azure AD 在 ASP.NET Core Web 应用程序中调用 Web API。

    虽然您现在没有客户端应用程序,但您仍然需要在 Azure 门户中注册两个应用程序。一个用于客户端,另一个用于服务器 api。

    对于您的服务器应用程序,您需要公开一个 API 并将您的客户端应用程序添加到其中。

    然后您可以使用您的客户端应用程序请求访问令牌以访问服务器 api。范围应为api://{server_client_id}/.default

    【讨论】:

    • 在上面的应用程序中,我添加了 Authorize 属性。当我运行localhost:44351/api/values 时,它返回 ["value1","value2"]。那么你需要假设我的身份验证工作正常吗?还有什么方法可以测试吗?
    • @Niranjan 打开一个隐身窗口,检查您是否可以在不提供授权的情况下访问 localhost:44351/api/values。
    • 我做到了。我打开了隐身窗口。它要求我输入用户名和密码。我输入了我的凭据。然后我的localhost:44351/api/values 显示 ["value1","value2"]
    • 接下来我想添加一些 api 并使用邮递员访问该 api。因此,对于邮递员,我可以使用我们在另一个问题中讨论过的早期令牌来获取令牌,对吗?
    • @Niranjan 我刚刚检查了代码,您需要更改为使用 JWT Bearer 令牌身份验证。就像 juunas 指出的那样。
    【解决方案2】:

    您似乎已经在您的应用上定义了 OpenID Connect + cookie 身份验证。 您需要改为使用 JWT Bearer 令牌身份验证。 我在这里有一个示例应用程序:https://github.com/juunas11/Joonasw.AzureAdApiSample/blob/master/Joonasw.AzureAdApiSample.Api/Startup.cs#L68

    样本片段:

                services
                    .AddAuthentication(o =>
                    {
                        o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    })
                    .AddJwtBearer(o =>
                    {
                        //In a multi-tenant app, make sure the authority is:
                        //o.Authority = "https://login.microsoftonline.com/common";
                        o.Authority = Configuration["Authentication:Authority"];
                        o.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidAudiences = new List<string>
                            {
                                Configuration["Authentication:AppIdUri"],
                                Configuration["Authentication:ClientId"]
                            },
                            // In multi-tenant apps you should disable issuer validation:
                            // ValidateIssuer = false,
                            // In case you want to allow only specific tenants,
                            // you can set the ValidIssuers property to a list of valid issuer ids
                            // or specify a delegate for the IssuerValidator property, e.g.
                            // IssuerValidator = (issuer, token, parameters) => {}
                            // the validator should return the issuer string
                            // if it is valid and throw an exception if not
                        };
                    });
    

    如果您的 API 访问令牌是 v2 访问令牌,您需要设置使用 v2.0 的权限。

    【讨论】:

    • 感谢您的回答。我在想我的代码实现将如何影响获取令牌? Token 直接来自 azure。在 azure 中,当我们创建应用程序时,我们是否需要分配任何权限以允许邮递员获取令牌?
    • @Niranjan 不,不需要分配权限以允许邮递员获取令牌
    • 谢谢。我在谷歌搜索。很少有人说oauth2.0不需要发送资源参数。如果我添加资源,它会抛出错误,说不需要资源标识符。我可以检查的其他可能性是什么
    猜你喜欢
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2019-09-15
    • 2016-07-10
    • 2022-11-01
    • 2019-05-15
    相关资源
    最近更新 更多