这是我的做法(也许不是最好的方法,但它有效):
- 我创建标准会员表
2.添加另一个表,我将用户链接到普通 ID 而不是 Guid,所以当有人想查看用户个人资料时,我不必将 guid 放在 url 中,我也有字段 DisplayName,所以多个用户可以有相同的 DisplayName
C# 的使用和OpenID库
- 将以下代码片段(这还没有完成,但它可以工作)添加到 Account Controller:
[AllowAnonymous]
public ActionResult LoginOpenID(string provider, string returnUrl)
{
using (var openid = new OpenIdRelyingParty())
{
var response = openid.GetResponse();
if (response == null)
{
try
{
var request = openid.CreateRequest(provider);
var fetchRequest = new FetchRequest();
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Alias);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.FullName);
request.AddExtension(fetchRequest);
request.AddCallbackArguments("returnUrl", returnUrl);
return request.RedirectingResponse.AsActionResult();
}
catch (ProtocolException pExp)
{
}
catch (WebException Wexp)
{
}
catch (ArgumentException aexp)
{
}
}
else
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
var fetch = response.GetExtension<FetchResponse>();
string alias = fetch.GetAttributeValue(WellKnownAttributes.Name.Alias);
string email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
string fullname = fetch.GetAttributeValue(WellKnownAttributes.Name.FullName);
if (string.IsNullOrEmpty(alias))
alias = response.ClaimedIdentifier;
if (alias.Contains("google"))
{
Random random = new Random();
int randomNumber = random.Next(1000000000);
alias = "user" + randomNumber;
}
if (string.IsNullOrEmpty(email))
email = response.ClaimedIdentifier;
//Now see if the user already exists, if not create them
if (email.Contains("gmail.com") && Membership.FindUsersByEmail(email).Count > 0)
{
var cookie = FormsAuthentication.GetAuthCookie(Membership.GetUserNameByEmail(email), true);
Response.AppendCookie(cookie);
}
else if (Membership.GetUser(response.ClaimedIdentifier) == null && Membership.FindUsersByEmail(email).Count == 0)
{
MembershipCreateStatus membershipCreateStatus;
string password = GetRandomString(6, 9);
MembershipUser user = Membership.CreateUser(response.ClaimedIdentifier.ToString(),
password,
email,
"This is an OpenID account. You should log in with your OpenID.",
GetRandomString(5, 7),
true,
out membershipCreateStatus);
if (membershipCreateStatus != MembershipCreateStatus.Success)
{
TempData["message"] = "Unsuccessful creation of Account. " + membershipCreateStatus.ToString();
return RedirectToAction("Login", "Account");
}
if (membershipCreateStatus == MembershipCreateStatus.Success)
{
user.Comment = alias;
Membership.UpdateUser(user);
using (MyContext context = new MyContext())
{
Data.UserShortId userShortId = new Data.UserShortId { Guid = (Guid)user.ProviderUserKey, DisplayName = alias };
context.UserShortIds.InsertOnSubmit(userShortId);
context.SubmitChanges();
}
}
// Use FormsAuthentication to tell ASP.NET that the user is now logged in,
// with the OpenID Claimed Identifier as their username.
var cookie = FormsAuthentication.GetAuthCookie(response.ClaimedIdentifier, true);
Response.AppendCookie(cookie);
}
else
{
var cookie = FormsAuthentication.GetAuthCookie(response.ClaimedIdentifier, true);
Response.AppendCookie(cookie);
}
break;
case AuthenticationStatus.Canceled:
TempData["message"] = "Login was cancelled at the provider";
return RedirectToAction("Login", "Account");
case AuthenticationStatus.Failed:
TempData["message"] = "Login failed using the provided OpenID identifier";
return RedirectToAction("Login", "Account");
}
}
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
}
private static Random random = new Random(46258975);
public static int GetRandomInteger(int min, int max)
{
return random.Next(min, max + 1);
}
public static string GetRandomString(int minLength, int maxLength)
{
int strLength = GetRandomInteger(minLength, maxLength);
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < strLength; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString().ToLower();
}
认证时:
@using (Html.BeginForm("LoginOpenId", "Account", FormMethod.Post))
{
@Html.Hidden("returnUrl", Request.QueryString["ReturnUrl"])
<p>Login using:</p>
<input type="submit" class="login-btn facebook" name="provider" value="http://facebook-openid.appspot.com/" />
<input type="submit" class="login-btn google" name="provider" value="https://www.google.com/accounts/o8/id" />
<input type="submit" class="login-btn yahoo" name="provider" value="http://me.yahoo.com/" />
}
如您所见,这还没有完成,我使用非官方 FB OpenID 提供程序,但您可以编写案例以使用 OAuth 单独处理 Fb 登录。