我正在使用IdentityServer3处理ASP MVC网站中的用户身份验证。
登录屏幕托管在应用程序本身的视图中(不使用Identity Server隐式流程)。我还提供了“使用Google登录”选项,用户可以通过单击登录屏幕上的按钮进行选择。
具有[Authorize](授权)的任何页面都应将未经身份验证的用户重定向到登录屏幕:
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies",
LoginPath = new PathString("/Account/Login")
});
}
帐户控制器的轮廓如下所示。“表单身份验证”方案将起作用(如此处所述)。
通过指定“ acr_values”参数,“使用Google登录”按钮的工作如此处所述(跳过ID服务器登录页面,直接转到Google)。
使用Google登录后,如何处理来自OpenID Connect的回调?我尝试添加OpenId Connect中间件,但不能与Cookie身份验证上的“ LoginPath”功能配合使用:未经身份验证的用户现在被重定向到ID Server登录屏幕,而不是我的本地登录屏幕。
我在IdentityServer示例中看不到任何解决此问题的方法。
public class AccountController : Controller
{
[HttpGet]
public ActionResult Login()
{
ViewBag.GoogleLogin = CreateLoginUrl("Google");
return View();
}
[HttpPost]
public ActionResult Login(LoginViewModel vm)
{
// Call IdentityServer here with credentials
// Validate token and do the Owin Authentication SignIn
// Redirect to 'ReturnUrl'
// If errors:
return View(vm);
}
public ActionResult Callback()
{
// What goes here??
return new RedirectResult("/");
}
private string CreateLoginUrl(string provider)
{
var state = Guid.NewGuid().ToString("N");
var nonce = Guid.NewGuid().ToString("N");
var request = new AuthorizeRequest(new Uri("https://localhost:44312/connect/authorize"));
var startUrl = request.CreateAuthorizeUrl(
clientId: "mvc",
responseType: "id_token token",
scope: "openid profile roles sampleApi",
redirectUri: "https://localhost:44319/Account/Callback",
state: state,
acrValues: "idp:" + provider,
nonce: nonce);
return startUrl;
}
}
我通过使用Map IAppBuilder扩展仅将Open Id Connect中间件应用于单个端点来避免了身份验证提供程序冲突的问题。这样,社交登录流程完全由中间件处理,并且身份验证cookie由两个身份验证提供程序共享。
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies",
LoginPath = new PathString("/Account/Login")
});
app.Map(new PathString("/Account/SocialLogin"), ctx =>
{
ctx.UseOpenIdConnectAuthentication(Options());
});
}
和AccountController位:
public class AccountController : Controller
{
[HttpGet]
public ActionResult Login(string returnUrl)
{
return View(new LoginViewModel { ReturnUrl = returnUrl });
}
[HttpPost]
public async Task<ActionResult> Login(LoginViewModel vm)
{
if (!ModelState.IsValid)
{
return View(vm);
}
// Call IdentityServer here with credentials
TokenResponse token = await GetToken(vm.UserName, vm.Password);
// Validate token and do the Owin Authentication SignIn
// Redirect to 'ReturnUrl'
await SignInAsync(token);
return new RedirectResult(vm.ReturnUrl);
}
[Authorize]
public ActionResult SocialLogin(string returnUrl)
{
return new RedirectResult(returnUrl);
}
// Some helpers omitted
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句