我正在使用VS 2013中的默认MVC 5项目。在_LoginPartial.cshtml中,它会对Request.IsAuthenitcated进行检查并对其返回的内容进行分支。我的问题是,设置在哪里?我修改了我的代码,以便能够使用Google直接从主页登录,但是在它执行此操作并返回到索引后,此IsAuthenticated值仍为false。
我创建了“使用Google登录”链接,点击后我将其指向现有的ExternalLogin()操作。之后验证谷歌它调用ExternalLoginCallback(),我稍微修改,从GUID自动创建一个UserName,然后登录。但是,IsAuthenticated仍然是假的。我错过了什么?
代码确实到达ExternalLoginCallback()内的SignInAsync()并且没有错误发生并且它返回到索引就好了,所以不确定是什么问题。
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
//
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var user = await UserManager.FindAsync(loginInfo.Login);
if (user != null)
{
await SignInAsync(user, isPersistent: false);
return RedirectToLocal(returnUrl);
}
else
{
// Get the information about the user from the external login provider
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
//var user = new ApplicationUser() { UserName = model.UserName };
user = new ApplicationUser() { UserName = Guid.NewGuid().ToString().Replace("-", "") };
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
return View();
}
答案 0 :(得分:0)
SignInAsync导致创建cookie,然后由框架读取,以便在加载页面时设置IsAuthenticated。
有可能,您的Cookie已损坏,导致其无法正确设置。清除cookie可能会解决问题。