1
votes

I try to integrate Azure Active Directory and Asp.net CORE 2.2.

public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
            .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    // 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
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseAuthentication();
        app.UseMvc();
    }

Appsettings.json

{"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "xxxxx.onmicrosoft.com",
"TenantId": "xxxxxx", 
"ClientId": "xxxx" } },"AllowedHosts": "*"}

The results: Error : info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2] Authorization failed.

Please, i found any solution for this issue.

Thank you very much

2
I dont know if this is your case, but if you are trying to authenticate with a token for MS Graph, it wont work. You need to issue a token for your own Web API and not reuse tokens from other resources.Tiago B

2 Answers

0
votes

May be a good solution is to modify the startup.cs

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(sharedOptions =>
        {
            sharedOptions.DefaultChallengeScheme = AzureADDefaults.AuthenticationScheme;
            sharedOptions.DefaultAuthenticateScheme = AzureADDefaults.AuthenticationScheme;
        })
        .AddAzureAD(options => Configuration.Bind("AzureAD", options));

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

And includes in the controller

[Authorize(AuthenticationSchemes = "AzureAD")]
[Route("api/[controller]")]
[ApiController]
0
votes

AddAzureADBearer adds JWT Bearer authentication to your app for Azure Active Directory Applications. It is usually used by protecting your application with AAD tokens . If that is you scenario , check the detailed error message of Authorization failed. You can refer to below link for code samples :

https://stackoverflow.com/a/57619013/5751404

Another scenario is you want to add Azure AD login authentication .The simplest way is to use the default Azure AD template : Change Authentication --> Work or School Accounts . Or manually add the Microsoft.AspNetCore.Authentication.AzureAD.UI package and use AddAzureAD extension:

https://stackoverflow.com/a/54546245/5751404