具有OpenIdAuthentication的ASP.NET:如果未授权,则重定向到url

And*_*erd 4 asp.net asp.net-identity azure-active-directory owin-middleware openid-connect

我正在尝试编写使用混合身份验证方案的ASP.NET应用程序。用户可以将其用户名和密码哈希存储在UserStore中,也可以通过Azure Active Directory进行身份验证。

我创建了如图所示的登录表单。它具有标准UserNamePassword输入,还具有“通过Active Directory登录”按钮。

在此处输入图片说明

这很好。

现在解决问题:应用程序的主页具有[Authorize]属性。

public class DefaultController : Controller
{
    [Authorize]
    public ViewResult Index()
    { 
    // Implementation
    }
}
Run Code Online (Sandbox Code Playgroud)

如果用户未登录,我希望它重定向到page Account/Login,允许用户选择身份验证方法。

一旦添加IAppBuilder.UseOpenIdConnectAuthentication到管道设置中,它就不再重定向到该页面。而是直接转到“ Microsoft登录”页面。

如何配置它,使OpenID身份验证成为系统的一部分,但允许我指定在未验证用户身份时如何执行重定向?

这是我建立管道的代码:

appBuilder.SetDefaultSignInAsAuthticationType(CookieAuthenticationDefaults.AuthenticationType_;
var cookieAuthenticationOptions = new CookieAuthenticationOptions
{
     AuthenticationType = DefaultAuthenticationType.ApplicationCookie,
     LoginPath = new Microsoft.Owin.PathString("/Account/Login"),
     Provider = new Security.CookieAuthenticationProvider()
};
appBuilder.UseCookieAuthentication(cookieAuthenticationOptions);
// Now the OpenId authentication
var notificationHandlers = new OpenIdConnectAuthenticationNotificationHandlers 
{
   AuthorizationCodeReceived = async(context) => {
       var jwtSecurityToken = context.JwtSecurityToken;
       // I've written a static method to convert the claims
       // to a user
       var user = await GetOrCreateUser(context.OwinContext, jwtSecurityToken.Claims);
       var signInManager = context.OwinContext.Get<SignInManager>();
       await signInManager.SignInAsync(user, true, false);
   }
}
var openIdOptions = new OpenIdConnectAuthenticationOptions
{
     ClientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx",
     Authority = "https://login.microsoftonline.com/xxxxx.onmicrosoft.com",
     PostLogoutRedirectUri = "https://localhost:52538/Account/Login",
     Notifications = notifcationHandlers
}
appBuilder.UseOpenIdConnectAuthentication(openIdOptions);
Run Code Online (Sandbox Code Playgroud)

当您单击“ Active Directory登录”时,它将发布到“ Account / SignInWithOpenId”

public ActionResult SignInWithOpenId()
{
    // Send an OpenID Connect sign-in request.
    if (!Request.IsAuthenticated)
    {
        var authenticationProperties = new AuthenticationProperties
        {
            RedirectUri = "/"
        };
        HttpContext.GetOwinContext().Authentication.Challenge
        (
            authenticationProperties,
            OpenIdConnectAuthenticationDefaults.AuthenticationType
        );
        return new EmptyResult();
    }
    else
    {
        return RedirectToAction("Index", "Default");
    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*erd 6

调用IAppBuilder.UseOpenIdConnectAuthentication(...)将Owin中间件组件放入管道中。当ASP.NET MVC返回401(未经授权)的HttpResponse时,Owin中间件组件会检测到该错误并将其更改为Http重定向(代码302),并且重定向路径将指向Open Id提供程序。

但是有一种解决方法:在中间件组件执行重定向之前,它会调用callback RedirectToIdentityProvider。从这里,您可以覆盖此重定向。

这是我的代码,它将覆盖重定向,除非它来自请求路径Account/SignInWithOpenId

var notificationHandlers = new OpenIdConnectAuthenticationNotifications
{
    AuthorizationCodeReceived = async(context) => {
       // Sign in the user here
    },
    RedirectToIdentityProvider = (context) => {
        if(context.OwinContext.Request.Path.Value != "/Account/SignInWithOpenId")
        {
             context.OwinContext.Response.Redirect("/Account/Login");
             context.HandleResponse();
        }
        return Task.FromResult(0);
    }
}
var openIdOptions = new OpenIdConnectAuthenticationOptions
{
     ClientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx",
     Authority = "https://login.microsoftonline.com/xxxxx.onmicrosoft.com",
     PostLogoutRedirectUri = "https://localhost:52538/Account/Login",
     Notifications = notifcationHandlers
}
appBuilder.UseOpenIdConnectAuthentication(openIdOptions);
Run Code Online (Sandbox Code Playgroud)