Using [Authorize] with OpenIdConnect in MVC 6 results in immediate empty 401 response

久未见 提交于 2019-12-23 17:10:04

问题


I'm trying to add Azure AD authentication to my ASP.NET 5 MVC 6 application and have followed this example on GitHub. Everything works fine if I put the recommended code in an action method:

Context.Response.Challenge(
    new AuthenticationProperties { RedirectUri = "/" },
    OpenIdConnectAuthenticationDefaults.AuthenticationType);

However, if I try using the [Authorize] attribute instead, I get an immediate empty 401 response.

How can I make [Authorize] redirect properly to Azure AD?

My configuration is as follows:

public void ConfigureServices(IServiceCollection services) {
    ...
    services.Configure<ExternalAuthenticationOptions>(options => {
        options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    });
    ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
    ...
    app.UseCookieAuthentication(options => {
       options.AutomaticAuthentication = true;
    });

    app.UseOpenIdConnectAuthentication(options => {
        options.ClientId = Configuration.Get("AzureAd:ClientId");
        options.Authority = String.Format(Configuration.Get("AzureAd:AadInstance"), Configuration.Get("AzureAd:Tenant"));
        options.RedirectUri = "https://localhost:44300";
        options.PostLogoutRedirectUri = Configuration.Get("AzureAd:PostLogoutRedirectUri");
        options.Notifications = new OpenIdConnectAuthenticationNotifications {
            AuthenticationFailed = OnAuthenticationFailed
        };
    });
    ...
}

回答1:


To automatically redirect your users to AAD when hitting a protected resource (i.e when catching a 401 response), the best option is to enable the automatic mode:

app.UseOpenIdConnectAuthentication(options => {
    options.AutomaticAuthentication = true;

    options.ClientId = Configuration.Get("AzureAd:ClientId");
    options.Authority = String.Format(Configuration.Get("AzureAd:AadInstance"), Configuration.Get("AzureAd:Tenant"));
    options.RedirectUri = "https://localhost:44300";
    options.PostLogoutRedirectUri = Configuration.Get("AzureAd:PostLogoutRedirectUri");
    options.Notifications = new OpenIdConnectAuthenticationNotifications {
        AuthenticationFailed = OnAuthenticationFailed
    };
});


来源:https://stackoverflow.com/questions/31321329/using-authorize-with-openidconnect-in-mvc-6-results-in-immediate-empty-401-res

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!