Niranjan
Niranjan

Reputation: 2229

Unable to get Azure AD token in PostMan

I am working on .Net core Azure AD authentication. I have created sample .Net core Application. Below is my code.

 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();
        }

Below is my config file.

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

Below is my Controller code.

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

Above code works fine. I am able to hit api and get value. So I am assuming my authentication is working fine. I am trying to hit this API from postman so I am trying to get token in Postman.

enter image description here

I am getting error Could not complete OAuth 2.0 login. Can someone help me to fix this issue? Any help would be appreciated. Thanks

Upvotes: 0

Views: 2880

Answers (2)

Tony Ju
Tony Ju

Reputation: 15609

Here is an complete sample which calling a web API in an ASP.NET Core web application using Azure AD.

Though you don't have a client application now, you still need to register two applications in Azure portal. One is for client and the other one is for server api.

For your server application, you need to expose an API and add your client application to it.

enter image description here

Then you can use your client application to request the access token to access server api. The scope should be api://{server_client_id}/.default.

Upvotes: 2

juunas
juunas

Reputation: 58733

It looks like you've defined OpenID Connect + cookies authentication on your app. You need to change to use JWT Bearer token authentication instead. I have a sample app here: https://github.com/juunas11/Joonasw.AzureAdApiSample/blob/master/Joonasw.AzureAdApiSample.Api/Startup.cs#L68

Snippet from the sample:

            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
                    };
                });

You'll want to set the authority to use v2.0 if your API access tokens are v2 access tokens.

Upvotes: 1

Related Questions