我正在开发一个MVC 5.0 .ASP NET应用程序。我使用Identity来授权用户。我在AccountController中添加了另一种方法,用户可以使用Token登录。在我的方法中“登录”而不是渲染选定的视图应用程序后重定向到默认登录方法。当您键入mysite / home /时,它显示用户已登录。 我无法找到重定向到登录的时间。 任何想法如何解决这个问题?
要在我的操作中验证用户,我使用此方法:
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
我的自定义登录操作
[AllowAnonymous]
public async Task<ActionResult> LoginWithToken(string token, string returnUrl)
{
AccountService accountService = new AccountService(db);
string userId;
try
{
userId = await accountService.GetUserIdFromToken(token);
}
catch (Exception exception)
{
ModelState.AddModelError(exception.Message, exception);
return RedirectToAction("Login");
}
var user = await UserManager.FindByIdAsync(userId);
try
{
await SignInAsync(user, false);
}
catch (Exception)
{
ModelState.AddModelError("Logowanie nieudane. Konto mogło zostać zablokowane lub usunięte. Skontaktuj się z administratorem serwisu.", new AccessViolationException());
return RedirectToAction("Login");
}
LogUserLogin(user.UserName, Request.UserHostAddress);
string decodedUrl = "";
if (!string.IsNullOrEmpty(returnUrl))
decodedUrl = Server.UrlDecode(returnUrl);
if (Url.IsLocalUrl(decodedUrl))
{
return View((object)decodedUrl);
}
else
{
return RedirectToAction("Home", "Index", new { });
}
}
编辑: 我发现当我的方法命中时返回View((object)decodingUrl);请求不包含“.AspNet.ApplicationCookie”。我已经在Application_BeginRequest上设置了断点,并且在renturn View((object)decodingUrl之后)有请求登录操作。此时请求中有“.AspNet.ApplicationCookie”。
答案 0 :(得分:0)
最后,我发现身份验证Cookie未设置为当前请求,而是设置为下一个请求。 现在我的LoginWithToken方法重定向到另一个[AllowAnonymous] Action,因此设置了cookie。然后该操作重定向到授权限制区域。