asp.net用户身份验证最佳方法webforms
对web用户进行身份验证和存储其详细信息的最佳方法是什么?我有一个类: 我应该使用会话还是表单验证cookie 我如何从任何一种方式(比如像userclass.username)访问它 我想存储相当多的用户信息来停止数据库调用,比如:用户类型、用户全名、地址、邮政编码、foo1、foo2、foo3、foo4等等。我知道这可能会进入会话或验证cookie用户数据。这个问题和我没有得到任何帮助的链接有关 真的可以做一些帮助和建议在这里,因为我有一些系统,我需要这样做。任何意见,谢谢 谢谢 ************************************链接***************************** 我的代码大致基于: ************************************编辑***************************** 自定义标识模块asp.net用户身份验证最佳方法webforms,asp.net,authentication,webforms,forms-authentication,Asp.net,Authentication,Webforms,Forms Authentication,对web用户进行身份验证和存储其详细信息的最佳方法是什么?我有一个类: 我应该使用会话还是表单验证cookie 我如何从任何一种方式(比如像userclass.username)访问它 我想存储相当多的用户信息来停止数据库调用,比如:用户类型、用户全名、地址、邮政编码、foo1、foo2、foo3、foo4等等。我知道这可能会进入会话或验证cookie用户数据。这个问题和我没有得到任何帮助的链接有关 真的可以做一些帮助和建议在这里,因为我有一些系统,我需要这样做。任何意见,谢谢 谢谢 *****
Public Module IdentityExtensions
Sub New()
End Sub
Private _CustomIdentityUser As CustomIdentityUser
<System.Runtime.CompilerServices.Extension> _
Public Function CustomIdentity(identity As System.Security.Principal.IIdentity) As CustomIdentityUser
'If _CustomIdentityUser Is Nothing Then
'_CustomIdentityUser = DirectCast(identity, CustomIdentityUser)
_CustomIdentityUser = Nothing
If identity.GetType = GetType(FormsIdentity) Then
_CustomIdentityUser = New CustomIdentityUser(DirectCast(identity, FormsIdentity).Ticket)
Else
If identity.IsAuthenticated Then
FormsAuthentication.RedirectToLoginPage()
End If
End If
Return _CustomIdentityUser
End Function
End Module
然后,正如您所看到的,user类调用一个auth类,该类基本上拥有用户的所有属性,并获取和设置它,等等
Public Class Auth
Inherits BaseUser
Public Property _ticket As Web.Security.FormsAuthenticationTicket
Public RememberMe As Boolean
Private _IssueDate As DateTime?
Public ReadOnly Property IssueDate As DateTime?
Get
Return _IssueDate
End Get
End Property
Private _Expired As Boolean
Public ReadOnly Property Expired As Boolean
Get
Return _Expired
End Get
End Property
Private _Expiration As DateTime?
Public ReadOnly Property Expiration As DateTime?
Get
Return _Expiration
End Get
End Property
Public Sub New(ticket As System.Web.Security.FormsAuthenticationTicket)
Me._ticket = ticket
Dim SignOutUser As Boolean = False
Try
If Not GetUserDetails() Then
SignOutUser = True
End If
Catch ex As Exception
SignOutUser = True
End Try
If SignOutUser Then
HttpContext.Current.Response.Redirect("~/", True)
SignOut()
End If
End Sub
Public ReadOnly Property IsAuthenticated() As Boolean
Get
Return HttpContext.Current.User.Identity.IsAuthenticated
End Get
End Property
Public Function SetAuthCookie() As Int16
Dim encTicket As String
Dim userData As String = CreateUserDataString()
If userData.Length > 0 And userData.Length < 4000 Then
Dim cookiex As HttpCookie = FormsAuthentication.GetAuthCookie(MyBase.Username, True)
Dim ticketx As FormsAuthenticationTicket = FormsAuthentication.Decrypt(cookiex.Value)
'Dim newTicket = New FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData, ticket.CookiePath)
'encTicket = FormsAuthentication.Encrypt(newTicket)
'Use existing cookie. Could create new one but would have to copy settings over...
'cookie.Value = encTicket
'cookie.Expires = newTicket.Expiration.AddHours(24)
'HttpContext.Current.Response.Cookies.Add(cookie)
Dim ticket As New FormsAuthenticationTicket(1, ticketx.Name, DateTime.Now, ticketx.Expiration, False, userData, ticketx.CookiePath)
encTicket = FormsAuthentication.Encrypt(ticket)
cookiex.Value = encTicket
'Dim cookie As New HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
HttpContext.Current.Response.Cookies.Add(cookiex)
Else
Throw New ArgumentOutOfRangeException("User data length exceeds maximum", New ArgumentOutOfRangeException)
End If
Return encTicket.Length
End Function
Public Function GetUserDetails() As Boolean
Dim valid As Boolean = False
If _ticket IsNot Nothing Then
With _ticket
RememberMe = .IsPersistent
Username = .Name
_IssueDate = .IssueDate
_Expired = .Expired
_Expiration = .Expiration
Try
If .UserData.Length > 0 Then
valid = SetUserDataFromString(.UserData)
Else
'we have a problem
Return False
End If
Catch ex As Exception
'sign them out as they may have a cookie but the code may have changed so it errors thus make them login again.
'SignOut()
Throw ex
End Try
End With
End If
Return valid
End Function
Private Function CreateUserDataString() As String
Dim sData As New System.Text.StringBuilder
With sData
.Append(MyBase.UserID)
.Append("|") 'delimeter we are using
.Append(Int16.Parse(MyBase.UserType))
.Append("|")
.Append(Int16.Parse(MyBase.Security))
.Append("|") 'delimeter we are using
.Append(MyBase.FirstName)
.Append("|")
.Append(MyBase.LastName)
.Append("|")
.Append(MyBase.foo1)
.Append("|")
.Append(MyBase.foo2)
.Append("|")
.Append(MyBase.foo3)
.Append("|")
.Append(MyBase.foo4)
End With
Return sData.ToString
End Function
Public Function SetUserDataFromString(userData As String) As Boolean
Dim valid As Boolean = False
Dim sData As New System.Text.StringBuilder
'check we have a delimeter
Dim arUserData As String() = userData.Split("|")
Try
If arUserData.Count >= 9 Then '9 because that the user only stuff
With arUserData
MyBase.UserID = arUserData(0)
MyBase.UserType = arUserData(1)
MyBase.Security = arUserData(2)
MyBase.FirstName = arUserData(3)
MyBase.LastName = arUserData(4)
MyBase.foo1 = arUserData(5)
MyBase.foo2 = arUserData(6)
MyBase.foo3 = arUserData(7)
MyBase.foo4 = arUserData(8)
End With
valid = True
Else
valid = False
End If
Catch ex As Exception
Throw New ArgumentOutOfRangeException("User data length to short", New ArgumentOutOfRangeException)
End Try
Return valid
End Function
Public Sub SignOut()
FormsAuthentication.SignOut()
End Sub
公共类身份验证
继承BaseUser
公共财产\u票证为Web.Security.formsAuthentication票证
作为布尔值的公共记忆
Private?发布日期为DateTime?
公共只读属性是否作为日期时间发布?
得到
返回已发布日期
结束
端属性
Private\u作为布尔值过期
公共只读属性已作为布尔值过期
得到
退货过期
结束
端属性
Private\u到期日期为DateTime?
公共只读属性到期日期为DateTime?
得到
返回到期日
结束
端属性
Public Sub New(票证为System.Web.Security.FormsAuthentication票证)
我
Dim SignOutUser为布尔值=False
尝试
如果不是GetUserDetails(),则
SignOutUser=True
如果结束
特例
SignOutUser=True
结束尝试
如果是SignOutUser,则
HttpContext.Current.Response.Redirect(“~/”,True)
签出()
如果结束
端接头
公共只读属性已作为布尔值进行身份验证()
得到
返回HttpContext.Current.User.Identity.IsAuthenticated
结束
端属性
公共函数SetAuthCookie()作为Int16
以字符串形式显示票据
Dim userData As String=CreateUserDataString()
如果userData.Length>0且userData.Length<4000,则
Dim cookiex As HttpCookie=FormsAuthentication.GetAuthCookie(MyBase.Username,True)
Dim ticketx As FormsAuthenticationTicket=FormsAuthentication.Decrypt(cookiex.Value)
'Dim newTicket=新表单身份验证票证(ticket.Version、ticket.Name、ticket.IssueDate、ticket.Expiration、ticket.IsPersistent、userData、ticket.CookiePath)
'encTicket=FormsAuthentication.Encrypt(newTicket)
'使用现有cookie。可以创建一个新的,但必须通过复制设置。。。
'cookie.Value=encTicket
'cookie.Expires=newTicket.expirement.AddHours(24)
'HttpContext.Current.Response.Cookies.Add(cookie)
Dim票证作为新表单身份验证票证(1,ticketx.Name,DateTime.Now,ticketx.Expiration,False,userData,ticketx.CookiePath)
encTicket=FormsAuthentication.Encrypt(票据)
cookiex.Value=encTicket
'Dim cookie作为新的HttpCookie(FormsAuthentication.FormScookeName,encTicket)
HttpContext.Current.Response.Cookies.Add(cookiex)
其他的
抛出新ArgumentOutOfRangeException(“用户数据长度超过最大值”,新ArgumentOutOfRangeException)
如果结束
回程票。长度
端函数
作为布尔值的公共函数GetUserDetails()
Dim有效值为布尔值=False
如果票不是空的话
凭票
RememberMe=.IsPersistent
用户名=.Name
_IssueDate=.IssueDate
_过期=.Expired
_过期=.Expiration
尝试
如果.UserData.Length>0,则
valid=SetUserDataFromString(.UserData)
其他的
“我们有个问题
返回错误
如果结束
特例
'注销他们,因为他们可能有一个cookie,但代码可能已更改,因此它会出错,从而使他们再次登录。
'注销()
投手
结束尝试
以
如果结束
返回有效
端函数
私有函数CreateUserDataString()作为字符串
将sData设置为新System.Text.StringBuilder
与sData
.Append(MyBase.UserID)
.Append(“|”)我们正在使用的delimeter
.Append(Int16.Parse(MyBase.UserType))
.附加(“|”)
.Append(Int16.Parse(MyBase.Security))
.Append(“|”)我们正在使用的delimeter
.Append(MyBase.FirstName)
.附加(“|”)
.Append(MyBase.LastName)
.附加(“|”)
.Append(MyBase.foo1)
.附加(“|”)
.Append(MyBase.foo2)
.附加(“|”)
.Append(MyBase.foo3)
.附加(“|”)
.Append(MyBase.foo4)
以
返回sData.ToString
端函数
公共函数SetUserDataFromString(userData作为字符串)为布尔值
Dim有效值为布尔值=False
将sData设置为新System.Text.StringBuilder
“检查一下,我们有一个计价器
Dim arUserData As String()=userData.Split(“|”)格式
尝试
如果arUserData.Count>=9,则为“9”,因为该用户只需要填充
使用arUserData
MyBase.UserID=arUserData(0)
MyBase.UserType=arUserData(1)
MyBase.Security=arUserData(2)
MyBase.FirstName=arUserData(3)
MyBase.LastName=arUserData(4)
MyBase.foo1=arUserData(5)
MyBase.foo2=arUserData(6)
MyBase.foo3=arUserData(7)
MyBase.foo4=arUserData(8)
以
有效=真
其他的
有效=错误
如果结束
特例
将新的论点抛出范围之外
Public Class Auth
Inherits BaseUser
Public Property _ticket As Web.Security.FormsAuthenticationTicket
Public RememberMe As Boolean
Private _IssueDate As DateTime?
Public ReadOnly Property IssueDate As DateTime?
Get
Return _IssueDate
End Get
End Property
Private _Expired As Boolean
Public ReadOnly Property Expired As Boolean
Get
Return _Expired
End Get
End Property
Private _Expiration As DateTime?
Public ReadOnly Property Expiration As DateTime?
Get
Return _Expiration
End Get
End Property
Public Sub New(ticket As System.Web.Security.FormsAuthenticationTicket)
Me._ticket = ticket
Dim SignOutUser As Boolean = False
Try
If Not GetUserDetails() Then
SignOutUser = True
End If
Catch ex As Exception
SignOutUser = True
End Try
If SignOutUser Then
HttpContext.Current.Response.Redirect("~/", True)
SignOut()
End If
End Sub
Public ReadOnly Property IsAuthenticated() As Boolean
Get
Return HttpContext.Current.User.Identity.IsAuthenticated
End Get
End Property
Public Function SetAuthCookie() As Int16
Dim encTicket As String
Dim userData As String = CreateUserDataString()
If userData.Length > 0 And userData.Length < 4000 Then
Dim cookiex As HttpCookie = FormsAuthentication.GetAuthCookie(MyBase.Username, True)
Dim ticketx As FormsAuthenticationTicket = FormsAuthentication.Decrypt(cookiex.Value)
'Dim newTicket = New FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData, ticket.CookiePath)
'encTicket = FormsAuthentication.Encrypt(newTicket)
'Use existing cookie. Could create new one but would have to copy settings over...
'cookie.Value = encTicket
'cookie.Expires = newTicket.Expiration.AddHours(24)
'HttpContext.Current.Response.Cookies.Add(cookie)
Dim ticket As New FormsAuthenticationTicket(1, ticketx.Name, DateTime.Now, ticketx.Expiration, False, userData, ticketx.CookiePath)
encTicket = FormsAuthentication.Encrypt(ticket)
cookiex.Value = encTicket
'Dim cookie As New HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
HttpContext.Current.Response.Cookies.Add(cookiex)
Else
Throw New ArgumentOutOfRangeException("User data length exceeds maximum", New ArgumentOutOfRangeException)
End If
Return encTicket.Length
End Function
Public Function GetUserDetails() As Boolean
Dim valid As Boolean = False
If _ticket IsNot Nothing Then
With _ticket
RememberMe = .IsPersistent
Username = .Name
_IssueDate = .IssueDate
_Expired = .Expired
_Expiration = .Expiration
Try
If .UserData.Length > 0 Then
valid = SetUserDataFromString(.UserData)
Else
'we have a problem
Return False
End If
Catch ex As Exception
'sign them out as they may have a cookie but the code may have changed so it errors thus make them login again.
'SignOut()
Throw ex
End Try
End With
End If
Return valid
End Function
Private Function CreateUserDataString() As String
Dim sData As New System.Text.StringBuilder
With sData
.Append(MyBase.UserID)
.Append("|") 'delimeter we are using
.Append(Int16.Parse(MyBase.UserType))
.Append("|")
.Append(Int16.Parse(MyBase.Security))
.Append("|") 'delimeter we are using
.Append(MyBase.FirstName)
.Append("|")
.Append(MyBase.LastName)
.Append("|")
.Append(MyBase.foo1)
.Append("|")
.Append(MyBase.foo2)
.Append("|")
.Append(MyBase.foo3)
.Append("|")
.Append(MyBase.foo4)
End With
Return sData.ToString
End Function
Public Function SetUserDataFromString(userData As String) As Boolean
Dim valid As Boolean = False
Dim sData As New System.Text.StringBuilder
'check we have a delimeter
Dim arUserData As String() = userData.Split("|")
Try
If arUserData.Count >= 9 Then '9 because that the user only stuff
With arUserData
MyBase.UserID = arUserData(0)
MyBase.UserType = arUserData(1)
MyBase.Security = arUserData(2)
MyBase.FirstName = arUserData(3)
MyBase.LastName = arUserData(4)
MyBase.foo1 = arUserData(5)
MyBase.foo2 = arUserData(6)
MyBase.foo3 = arUserData(7)
MyBase.foo4 = arUserData(8)
End With
valid = True
Else
valid = False
End If
Catch ex As Exception
Throw New ArgumentOutOfRangeException("User data length to short", New ArgumentOutOfRangeException)
End Try
Return valid
End Function
Public Sub SignOut()
FormsAuthentication.SignOut()
End Sub
interface ICustomPrincipal : IPrincipal
{
int UserId { get; set; }
string FirstName { get; set; }
string LastName { get; set; }
}
public class CustomPrincipal : ICustomPrincipal
{
public CustomPrincipal()
{
}
public CustomPrincipal(string userName)
{
Identity = new GenericIdentity(userName);
}
public int UserId
{
get;
set;
}
public string FirstName
{
get;
set;
}
public string LastName
{
get;
set;
}
public IIdentity Identity
{
get;
private set;
}
public bool IsInRole(string role)
{
return false;
}
}
public class User
{
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
public static class FormsAuthHelper
{
public static void SetAuthTicket(User user, HttpContextBase context)
{
var serializer = new JavaScriptSerializer();
var userData = serializer.Serialize(user);
var authTicket = new FormsAuthenticationTicket(
1, user.UserName,
DateTime.Now, DateTime.Now.AddMinutes(30),
false, userData);
var ticket = FormsAuthentication.Encrypt(authTicket);
var faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticket);
context.Response.Cookies.Add(faCookie);
}
public static void Logout()
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
}
public static CustomPrincipal GetPrincipal(User user)
{
return new CustomPrincipal(user.UserName) { FirstName = user.FirstName, LastName = user.LastName, UserId = user.EntityId };
}
}
protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
var authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null || authCookie.Value == string.Empty)
return;
try
{
var ticket = FormsAuthentication.Decrypt(authCookie.Value);
var serializer = new JavaScriptSerializer();
var user = serializer.Deserialize<User>(ticket.UserData);
var newUser = FormsAuthHelper.GetPrincipal(user);
HttpContext.Current.User = newUser;
}
catch
{
//do nothing
}
}
public ActionResult Login(LoginModel loginModel)
{
if (ModelState.IsValid)
{
var user = _userRepository.Get(x => x.UserName == loginModel.UserName).SingleOrDefault();
if (user != null && PasswordHash.ValidatePassword(loginModel.Password, user.Password))
{
FormsAuthHelper.SetAuthTicket(user, HttpContext);
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError("NotFound", "User not found");
}
return View(loginModel);
}