2011-04-20 69 views
1

在使用OpenId的网站中跟踪当前用户的建议解决方案是什么?假设我有一个用户表,其中包含一个ID和一个声明的标识符,然后是我的网站特定信息,用户希望更新他们的网站特定信息。跟踪当前用户的最佳方式是什么,因为我没有使用内置成员资格?每当用户尝试更新他们的个人资料时,我是否应该向openid发送一个请求以获取ClaimedIdentifier?或者,也许只是强制UserName是唯一的,并获取基于User.Identity.Name的用户信息?OpenId更新配置文件信息

回答

1

我用一个cookie做到这一点:)......你可能会发现我的回答有用:What OpenID solution is really used by Stack Overflow?

我也做了一个简单的博客文章吧:http://codesprout.blogspot.com/2011/03/using-dotnetopenauth-to-create-simple.html

public class User 
{ 
    [DisplayName("User ID")] 
    public int UserID{ get; set; } 

    [Required] 
    [DisplayName("Open ID")] 
    public string OpenID { get; set; } 

    [DisplayName("User Name")] 
    public string UserName{ get; set; } 
} 

在我的例子我与OpenID登录,然后我将其存储在cookie中,但是,你可以存储在cookie中的其他信息,如用户名:

public class FormsAuthenticationService : IFormsAuthenticationService 
{ 
    public void SignIn(string userName, bool createPersistentCookie) 
    { 
     if (String.IsNullOrEmpty(serName)) throw new ArgumentException("The user name cannot be null or empty.", "UserName"); 

     FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); 
    } 

    public void SignOut() 
    { 
     FormsAuthentication.SignOut(); 
    } 
} 

更新2.0:
如何这样的事情(这是视图):

<% 
    if (Request.IsAuthenticated) 
    { 
     string name = Request.Cookies[Page.User.Identity.Name] == null ? string.Empty : Request.Cookies[Page.User.Identity.Name].Value; 
     if (string.IsNullOrEmpty(name)) 
     { 
      name = Page.User.Identity.Name; 
     } 
%> 

     [<%: Html.ActionLink(name, "Profile", "User")%> | 
     <%: Html.ActionLink("Log out", "LogOut", "User") %> | 
<% 
    } 
    else 
    { 
%> 
     [ <%: Html.ActionLink("Log in", "LogIn", "User") %> | 
<% 
    } 

%> 

和控制器,想必你您登录(或者你可以设置Response.Cookies后带到Profile页在LogIn法),当你加载了你的模型在cookie中设置的显示名称:

[Authorize] 
    [HttpGet] 
    public ActionResult Profile(User model) 
    { 
     if (User.Identity.IsAuthenticated) 
     { 
      userRepository.Refresh(); 
      model = userRepository.FetchByOpenID(User.Identity.Name); 

      // If the user wasn't located in the database 
      // then add the user to our database of users 
      if (model == null) 
      { 
       model = RegisterNewUser(User.Identity.Name); 
      } 

      Response.Cookies[model.OpenID].Value = model.DisplayName; 
      Response.Cookies[model.OpenID].Expires = DateTime.Now.AddDays(5); 

      return View(model); 
     } 
     else 
     { 
      return RedirectToAction("LogIn"); 
     } 
    } 

你可以看到这一切在行动上的一个小项目,我有:mydevarmy。我将很快发布用户配置文件,您将可以更改显示名称(目前会自动生成)。

+0

同意。尽管没有使用ASP.NET Membership,但您仍然可以使用FormsAuthentication登录cookie来记住哪个用户登录。 – 2011-04-20 13:41:35

+0

@Andrew,来自THE MAN自己!我觉得我正在做的事情正确:))无论如何,感谢给我们DotNetOpenAuth:它使我的生活更容易,作为回报,我在我去的任何地方实施它! – Kiril 2011-04-20 14:18:51

+0

@Lirik,很酷,这与我所拥有的非常相似,所以我认为我在正确的轨道上。当我尝试更新他的个人资料信息时,我有点卡住了,但是如何获得当前用户。你用来设置cookie的名字是一个友好的名字,所以不能有多个用户使用这个友好的名字?或者您是否使用了声明的ID,如果是,您是否必须使用会话状态才能使用友好名称? – 2011-04-20 19:09:33