我正在尝试编写一个使用混合身份验证方案的 ASP.NET 应用程序。用户可以将其用户名和密码哈希存储在 UserStore 中,也可以通过 Azure Active Directory 进行身份验证。
我已经创建了如图所示的登录表单。它具有标准UserName
和Password
输入,还具有“通过 Active Directory 登录”按钮。
这很好用。
现在解决问题:应用程序的主页具有该[Authorize]
属性。
public class DefaultController : Controller
{
[Authorize]
public ViewResult Index()
{
// Implementation
}
}
如果用户未登录,我希望它重定向到页面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);
当您单击“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");
}
}