在MVC 6中对OpenIdConnect使用[Authorize]会立即产生401空响应 [英] Using [Authorize] with OpenIdConnect in MVC 6 results in immediate empty 401 response

查看:271
本文介绍了在MVC 6中对OpenIdConnect使用[Authorize]会立即产生401空响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Azure AD身份验证添加到我的ASP.NET 5 MVC 6应用程序中,并遵循此

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

但是,如果我尝试使用[Authorize]属性,则会立即得到一个空的401响应.

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

如何使[Authorize]正确重定向到Azure AD?

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

我的配置如下:

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

推荐答案

要在遇到受保护的资源(即捕获401响应)时自动将用户重定向到AAD,最好的选择是启用automatic模式:

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

这篇关于在MVC 6中对OpenIdConnect使用[Authorize]会立即产生401空响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆