0

我正在尝试使用 facebook connect 在我的 ASP.NET MVC 应用程序中对用户进行身份验证。我编写了控制器,它获取 facebook access_token、facebook 用户的电子邮件,然后使用以下方法对用户进行身份验证:

FormsAuthentication.SetAuthCookie(loggedUserEmail, true);

毕竟,我将用户重定向到主页,在那里我尝试获取 User.Identity.Name 以显示登录用户的名称(在这种情况下,我猜是电子邮件)。不幸的是,User.Identity.Name 为空。但是,身份验证过程似乎可以正常工作,因为 Request.IsAuthenticated 返回 true ......

@if (Request.IsAuthenticated) {
    <p>
        @* ###THIS LINE THROWS EXCEPTION AS User.Identity.Names IS NULL### Hello, @Html.ActionLink(User.Identity.Name, "ChangePassword", "Account", routeValues: null, htmlAttributes: new { @class = "username", title = "Change password" })!*@ 
        @Html.ActionLink("Log off", "LogOff", "Account")
    </p>
}

为什么没有启动 User.Identity.Name 的任何想法?谢谢,

巴特

PS代替

FormsAuthentication.SetAuthCookie(loggedUserEmail, true);

我也试过

var authCookie = FormsAuthentication.GetAuthCookie(loggedUserEmail, true);
var ticket = FormsAuthentication.Decrypt(authCookie.Value);
// We want to change the expiration of our forms authentication cookie
// to match the token expiration date, but you can also use your own expiration
DateTime expiration = ticket.IssueDate.AddSeconds(facebookTokenExpirationSeconds);
var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name,
                  ticket.IssueDate, expiration, 
                  ticket.IsPersistent, facebookName);

// Encrypt the cookie again
authCookie.Value = FormsAuthentication.Encrypt(newTicket);

// Manually set it (instead of calling FormsAuthentication.SetAuthCookie)
Response.Cookies.Add(authCookie);

但它也不User.Identity.Names包含任何东西......

4

2 回答 2

0

也许我认为,重定向页面后访问令牌已过期。

于 2012-06-18T17:30:25.600 回答
0

我不相信在发出下一个请求之前会设置身份。过去,我通过手动将 HttpContext.Current.User 设置为在执行登录逻辑后从 Forms Auth 票证创建的 IPrincipal 来解决此问题。

像这样的东西(您的里程可能会有所不同):

var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
var ticket = FormsAuthentication.Decrypt(authCookie.Value);
var identity = new GenericIdentity(ticket.Name);
var principal = new GenericPrincipal(identity, null);
HttpContext.Current.User = principal
于 2016-01-25T21:33:04.933 回答