无法在PostMan中获得Azure AD令牌

时间:2019-09-12 12:14:22

标签: azure authentication jwt azure-active-directory

我正在研究.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,所以我试图在邮递员中获取令牌。

enter image description here

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

2 个答案:

答案 0 :(得分:2)

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

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

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

enter image description here

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

答案 1 :(得分:1)

您似乎已在应用程序上定义了OpenID Connect + Cookies身份验证。 您需要更改为使用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的权限。