asp.net authentication of users best methods webforms - asp.net

Whats the best way for authenticating web users and storing their details which i have a class for:
Should i use sessions or the forms auth cookie?
How can i access it from either way say like userclass.username?
I would like to store quite a lot of user information to stop database calls for stuff like: user type, user a full name, addresss, post code, foo1, foo2, foo3, foo4 and more. I know this could go in session or auth cookie user data. This question relates and links to https://stackoverflow.com/questions/18393122/whats-the-best-way-to-authenticate-a-user-and-store-user-details-sessions-or-fo which i have not had any help on
Really could do with some help and advice here as i have a few system which i need to do this for. Any comments appreciated.
thanks
************************************ Links *****************************
My code based roughly on:
http://www.shawnmclean.com/blog/2012/01/storing-strongly-typed-object-user-profile-data-in-asp-net-forms-authentication-cookie/
http://www.danharman.net/2011/07/07/storing-custom-data-in-forms-authentication-tickets/
************************************ EDIT *****************************
custom identity module
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
My Custom identity user
Public Class CustomIdentityUser
Implements System.Security.Principal.IIdentity
Private ticket As System.Web.Security.FormsAuthenticationTicket
Private _Auth As Auth
Public Sub New(ticket As System.Web.Security.FormsAuthenticationTicket)
Me.ticket = ticket
_Auth = New projectabc.Auth(Me.ticket)
End Sub
Public ReadOnly Property Auth As Auth
Get
Return Me._Auth
End Get
End Property
Public ReadOnly Property Username As String
Get
Return Auth.Username
End Get
End Property
Public ReadOnly Property UserType As Enumerations.EnumUserType
Get
Return Auth.UserType
End Get
End Property
Public ReadOnly Property OwnerType As Enumerations.EnumOwnerType
Get
Return Auth.OwnerType
End Get
End Property
Public ReadOnly Property AuthenticationType As String Implements System.Security.Principal.IIdentity.AuthenticationType
Get
Return "Custom"
End Get
End Property
Public ReadOnly Property IsAuthenticated As Boolean Implements System.Security.Principal.IIdentity.IsAuthenticated
Get
Return ticket IsNot Nothing
End Get
End Property
Public ReadOnly Property Name As String Implements System.Security.Principal.IIdentity.Name
Get
Return Username
End Get
End Property
End Class
Then as you can see the user class calls an auth class which basically has all the properties for the user and gets and set it etc.
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

As you have posted the code may be you would get some good answer. I would try to answer as per my understanding, hope that helps.
From where do you invoke CustomIdentity? In the first method in the Else part I think you might want to use Not IsAuthenticated if you want the user to redirect to the login page. Most of the times if the ticket is invalid you don't even have to do it the framework does it for you.
In the CustomIdentityUser you have a private member _Auth which you never use while returning some values through the properties. You are using Auth.UserName instead of _Auth.UserName, I am not sure how that works unless the UserName is static member.
Why is you custom Identity dependent on Auth? You can pass on the required data to the custom identity through contructor or by exposing public setters. Why do you need the auth ticket inside the identity?
The Auth Class has the expiration date and other stuff which is not required. You can have a simple User class to store the basic details of the user. Why are you redirecting the user from the constructor of Auth?
The GetUserDetails and SetUserDataFromString I do not know why do you need all these methods. Its just matter of Serializing and Deserializing the User class.
I understand that you must have referred some blog out there to implement this authentication, but you have lot of scope to simplify this.
Read this post. Specifically how the custom principal is implemented and how the authticket is set and the PostAuthenticateRequest method.
Here is some sample code that might help
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 };
}
}
Post authenticate request event looks like this
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
}
}
And finally when the user logs in
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);
}

Related

How to get User Name from External Login in ASP.NET Core?

I have set up an external login (Google) in my ASP.NET Core application. I am finding it hard to get the User Name / Email after login. I can see the email stored in AspNetUsers table But I don't see User Name anywhere.
I searched over and found this code:
var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
But this is giving me userId as is present in table AspNetUsers. ClaimTypes.Email returns null but the value is present in table (probably this email is something else). I want to fetch User Name and User Email. Is it possible?
Do you have access to SignInManager or can you inject it? If yes, then this is how you would access user id (username), email, first & last name:
public class MyController : Microsoft.AspNetCore.Mvc.Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
public MyController (
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager
)
{
_userManager = userManager;
_signInManager = signInManager;
}
public async Task<IActionResult> MyAction(){
ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync();
string userId = info.Principal.GetUserId()
string email = info.Principal.FindFirstValue(ClaimTypes.Email);
string FirstName = info.Principal.FindFirstValue(ClaimTypes.GivenName) ?? info.Principal.FindFirstValue(ClaimTypes.Name);
string LastName = info.Principal.FindFirstValue(ClaimTypes.Surname);
}
}
GetUserId extension:
public static class ClaimsPrincipalExtensions
{
public static string GetUserId(this ClaimsPrincipal principal)
{
if (principal == null)
return null; //throw new ArgumentNullException(nameof(principal));
string ret = "";
try
{
ret = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
}
catch (System.Exception)
{
}
return ret;
}
}

How to implement recaptcha 2.0 on ASP.NET?

I want to implement recaptcha 2.0 on my web page. I followed the steps from there by putting on client side:
<script src='https://www.google.com/recaptcha/api.js'></script>
and:
<div class="g-recaptcha" data-sitekey="my_data-sitekey"></div>
but, as far I understood, that's not enough. There is also something which must be done on server side. What and how should I do?
I made a simple and easy to use implementation.
Add the below class to your web project.
using System.Linq;
using System.Net.Http;
using Abp.Threading;
using Abp.Web.Models;
using Abp.Web.Mvc.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Newtonsoft.Json;
namespace WebDemo.Web.Attributes
{
public class ValidateRecaptchaAttribute : ActionFilterAttribute
{
private readonly string _propertyName;
private readonly string _secretKey;
private readonly string _errorViewName;
private readonly string _errorMessage;
private const string GoogleRecaptchaUrl = "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}";
private const string SecretKey = "***YOUR PRIVATE KEY HERE***";
public ValidateRecaptchaAttribute(string propertyName = "RepatchaValue", string secretKey = SecretKey, string errorViewName = "Error", string errorMessage = "Invalid captcha!")
{
_propertyName = propertyName;
_secretKey = secretKey;
_errorViewName = errorViewName;
_errorMessage = errorMessage;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
var model = context.ActionArguments.First().Value;
var propertyInfo = model.GetType().GetProperty(_propertyName);
if (propertyInfo != null)
{
var repatchaValue = propertyInfo.GetValue(model, null) as string;
var captchaValidationResult = ValidateRecaptcha(repatchaValue, _secretKey);
if (captchaValidationResult.Success)
{
base.OnActionExecuting(context);
return;
}
}
SetInvalidResult(context);
}
private void SetInvalidResult(ActionExecutingContext context)
{
var errorModel = new ErrorViewModel(new ErrorInfo(_errorMessage));
var viewResult = new ViewResult
{
ViewName = _errorViewName,
ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
{
Model = errorModel
}
};
context.Result = viewResult;
}
private static RecaptchaResponse ValidateRecaptcha(string userEnteredCaptcha, string secretKey)
{
if (string.IsNullOrEmpty(userEnteredCaptcha))
{
return new RecaptchaResponse
{
Success = false,
ErrorCodes = new[] { "missing-input-response" }
};
}
using (var client = new HttpClient())
{
var result = AsyncHelper.RunSync<string>(() => client.GetStringAsync(string.Format((string)GoogleRecaptchaUrl, secretKey, userEnteredCaptcha)));
var captchaResponse = JsonConvert.DeserializeObject<RecaptchaResponse>(result);
return captchaResponse;
}
}
public class RecaptchaResponse
{
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("challenge_ts")]
public string ChallengeTs { get; set; } // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
[JsonProperty("hostname")]
public string Hostname { get; set; } // the hostname of the site where the reCAPTCHA was solved
[JsonProperty("error-codes")]
public string[] ErrorCodes { get; set; } // optional
}
}
}
And usage is very simple;
[HttpGet]
[ValidateRecaptcha]
public ActionResult CreateProject(CreateModel model)
{
//your main code that needs to be done after captcha validation.
}
You have to get an api in order to use this google service.
https://developers.google.com/recaptcha/docs/start
Here is the vb.net code to validate captcha on server side
Public Function ValidateCaptcha() As Boolean
Dim valid As Boolean = False
Dim Ressponse As String = Request("g-recaptcha-response")
Dim strKey As String = ConfigurationManager.AppSettings("google.recaptcha.secretkey")
Dim req As HttpWebRequest = Net.WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=" + strKey + "&response=" + Ressponse)
Try
Using wResponse As WebResponse = req.GetResponse()
Using readStream As New StreamReader(wResponse.GetResponseStream())
Dim jsonResponse As String = readStream.ReadToEnd()
Dim js As New JavaScriptSerializer()
Dim data As MyObject = js.Deserialize(Of MyObject)(jsonResponse)
' Deserialize Json
valid = Convert.ToBoolean(data.success)
End Using
End Using
Return valid
Catch ex As Exception
Throw ex
End Try
End Function
here is the class MYObject
Public Class MyObject
Public Property success() As String
Get
Return m_success
End Get
Set(ByVal value As String)
m_success = Value
End Set
End Property
Private m_success As String
End Class
And you need to call this ValidateCaptcha() function from your button click event as below:
Protected Sub btnTrial_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnTrial.Click
If ValidateCaptcha() Then
'''''Do your query here'''''
End If
End Sub
Please refer How to Validate Recaptcha V2 Server side to get more details

I am binding dropdownlist with SQL2008 database in my WebUserControl, but my approach could use some improvement

I am doing lab. I am trying hard to bind dropdownlist with SQL2008 database in my WebUserControl. It was a piece of cake to implement when all my front and back code stood in webusercontrol, but after that I was told that this way of implementation is quite not professional. Also, I was told that I need to built a middle class with private variables and public properties:
public class UsersIntoDLL
{
public UsersIntoDLL(int userID, string userName, string userFamilyName)
{
userID = UserID;
userName = UserName;
userFamilyName = UserFamilyName;
}
public int UserID
{ get; set; }
public string UserName
{ get; set; }
public string UserFamilyName
{ get; set; }
}
Stored Procedure:
create procedure [dbo].[GetStudentsToDDL]
as
select UserID, UserName,UserFamilyName
from dbo.Users
New Method:
public List<UsersIntoDLL> GetStudents()
{
SqlConnection conn = new SqlConnection(Config.DbConnectionString);
SqlCommand cmd = new SqlCommand("GetStudentsToDDL", conn);
cmd.CommandType = CommandType.StoredProcedure;
List<UsersIntoDLL> udll = new List<UsersIntoDLL>();
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
//ListItem lst = new ListItem();
//udll.Text = reader["StudentName"].ToString() + " " + reader["StudentFamilyname"].ToString();
UsersIntoDLL students = new UsersIntoDLL((int)reader["UserID"], (string)reader["UserName"],(string)reader["UserFamilyName"]);
udll.Add(students);
}
reader.Close();
}
catch (Exception ex)
{
// here should be some reference to label located in webusercontrol. don't know
// how to do it
Label err = new Label();
err.Text = ex.Message;
}
finally
{
conn.Close();
}
return udll;
}
BadaBinding in back-code of webusercontrol:
CatalogAccess ca = new CatalogAccess();
ddlStudents.DataSource = ca.GetStudents();
ddlStudents.DataTextField = "UserName";
ddlStudents.DataValueField = "UserID";
ddlStudents.DataBind();
I am getting no errors and no binding. Students do not appear in my dropdownlist. Please help!!!
Ahh you weren't setting the variables in your class properly.
Use this instead:
public class UsersIntoDLL {
public UsersIntoDLL(int userID, string userName, string userFamilyName)
{
UserID = userID;
UserName = userName;
UserFamilyName = userFamilyName;
}
public int UserID
{
get;
set;
}
public string UserName
{
get;
set;
}
public string UserFamilyName
{
get;
set;
}
}
Nothing immediately jumps out but have you thought about using ObjectDataSource (linky)
p.s. Have you checked the list isn't empty?
Assuming you're running this in Visual Studio, could you set a breakpoint on the ddlStudents.DataSource = ca.GetStudents() line and make sure it is not empty?
To rule other potential issues out, change that line temporarily to:
ddlStudents.DataSource = new { UserName = "Test", UserID = "1" };
and see if at least one item shows in the drop-down.

Forms Authentication Cookie not expiring on Server Shutdown/Failure

Here is a use case of my login using a CustomMembershipProvider
User Logs in MembershipProvider validates user account
User property of Membership is set to user details coming from the database
An authentication ticket is created
Forms authentication cookie is added.
User is logged in
Here is a use case of my problem
Stop whe web development server
Start the web development server, and user is still logged in (due to cookie?)
User property Membership is set to null due to server restart/failure
Application throws exception due to null user value
The only solution I could think off is to clear all cookies on Application_Start() but I don't know how is that even possible as Request is out of context during application start.
Do you have any ideas how to solve this kind of problem?
Here is the code:
CustomMembershipProvider
public class CustomMembershipProvider : MembershipProvider
{
#region Unimplemented MembershipProvider Methods
//Other methods here
#endregion
//private IUserRepository _userRepository = new UserRepository();
//Ninject bindings
private IUserRepository _userRepository;
[Inject]
public IUserRepository UserRepository
{
set
{
_userRepository = value;
}
}
private IProfileRepository _profileRepository;
[Inject]
public IProfileRepository ProfileRepository
{
set
{
_profileRepository = value;
}
}
public User User
{
get;
private set;
}
public Profile Profile
{
get;
set;
}
public CustomMembershipProvider()
{
MvcApplication.Container.Inject(this);
}
public override bool ValidateUser(string username, string password)
{
if (string.IsNullOrEmpty(password.Trim())) return false;
User user = _userRepository.GetUserByUsername(username);
user.UserType = UserHelper.GetUserTypeById(user.UserTypeId);
if (user == null) return false;
string hash = PasswordHelper.ComputeHash(password, user.PasswordSalt);
if (user.Password == hash)
{
this.User = user;
Profile profile = _profileRepository.GetProfileByUserId(user.UserId);
this.Profile = profile;
return true;
}
return false;
}
}
Here is the login method of the Account Controller
[HttpPost]
public ActionResult Login(string username, string password)
{
if (!provider.ValidateUser(username, password))
{
TempData["LoginError"] = "Incorrect";
}
else
{
User user = provider.User;
if (!user.Verified)
{
TempData["LoginError"] = "Please verify your account";
return Redirect(Request.UrlReferrer.LocalPath);
}
//FormsAuthentication.SetAuthCookie(user.Username,false);
FormsAuthenticationTicket authTicket = new
FormsAuthenticationTicket(1, //version
username, //user name
DateTime.Now, //creation
DateTime.Now.AddMinutes(30), //Expiration
false, //Persistent
username); //since Classic logins don't have a "Friendly Name"
string encTicket = FormsAuthentication.Encrypt(authTicket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
WebsiteObjects.Profile profile = provider.Profile;
TempData["LoginError"] = String.Empty;
}
return Redirect("/");
}
Suggestions below are not doable because whenever I restart the server here is the case.
Request.IsAuthenticated is FALSE on Application_BeginRequest;
Request.IsAuthenticated is TRUE on my 'View'
why is this happening?
You should perform step 2 on each request or store the user details into the UserData part of the authentication cookie.
In the Application_AuthenticateRequest check if Request.IsAuthenticated=true but User object is null then re-populate it.

Implementing Custom MembershipUser

I am going round in circles and need some help in implementing a Custom MembershipUser so that I can add my own custom Properties to the MembershipUser.
I have been following the example on this site: How to: Implement a Custom Membership User
The problem I am having is in the constructor of CustomMembershipUser, I think.
My CustomMembershipUser has these three additional Properties: firstName, middleName, lastName.
public class CustomMembershipProvider : MembershipProvider
{
public override MembershipUser GetUser(string username, bool userIsOnline)
{
//.... Get data from database
MembershipUser baseUser = new MembershipUser(this.Name,
username,
userId,
email,
"",
comment,
isApproved,
isLockedOut,
dtCreate,
dtLastLogin,
dtLastActivity,
DateTime.Now,
dtLastLockoutDate);
return new CustomMembershipUser(baseUser, firstName, middleName, lastName)
}
}
public class CustomMembershipUser : MembershipUser
{
private string _firstName;
public string FirstName { get { return _firstName; } set { _firstName = value; } }
private string _middleName;
public string MiddleName { get { return _middleName; } set { _middleName = value; } }
private string _lastName;
public string LastName { get { return _lastName; } set { _lastName = value; } }
public CustomMembershipUser(MembershipUser baseuser, string firstname, string middlename, string lastname)
{
_firstName = firstname;
_middleName = middlename;
_lastName = lastname;
new CustomMembershipUser(baseuser); // DO I NEED THIS?? HOW TO IMPLEMENT??
}
}
I am calling it like so:
MembershipUser mu = Membership.GetUser(UserName);
CustomMembershipProvider p = (CustomMembershipProvider)Membership.Provider;
MembershipUser memUser = p.GetUser(UserName, true);
object userId = memUser.ProviderUserKey;
The ProviderUserKey is null and so are the other values.
How can I obtain the addition Properties I added?
Thanks
This is working for me:
public class CustomMembershipUser : MembershipUser
{
public CustomMembershipUser(
string providerName,
string name,
object providerUserKey,
string email,
string passwordQuestion,
string comment,
bool isApproved,
bool isLockedOut,
DateTime creationDate,
DateTime lastLoginDate,
DateTime lastActivityDate,
DateTime lastPasswordChangedDate,
DateTime lastLockoutDate
)
: base(providerName, name, providerUserKey, email, passwordQuestion,
comment, isApproved, isLockedOut, creationDate, lastLoginDate,
lastActivityDate, lastPasswordChangedDate, lastLockoutDate)
{
}
// Add additional properties
public string CustomerNumber { get; set; }
}
public class CustomMembershipProvider : MembershipProvider
{
public override MembershipUser GetUser(string username, bool userIsOnline)
{
if (string.IsNullOrEmpty(username))
{
// No user signed in
return null;
}
// ...get data from db
CustomMembershipUser user = new CustomMembershipUser(
"CustomMembershipProvider",
db.Username,
db.UserId,
db.Email,
"",
"",
true,
false,
db.CreatedAt,
DateTime.MinValue,
DateTime.MinValue,
DateTime.MinValue,
DateTime.MinValue);
// Fill additional properties
user.CustomerNumber = db.CustomerNumber;
return user;
}
}
// Get custom user (if allready logged in)
CustomMembershipUser user = Membership.GetUser(true) as CustomMembershipUser;
// Access custom property
user.CustomerNumber
Based on my own experience trying to do much of the same, trying to use the MembershipProvider to do this will be an ultimately frustrating and counterintuitive experience.
The idea of the membership provider model isn't to change or augment what the definition of a user is, as you're trying to do - it is to allow the Framework an alternate means of accessing the information that has already been defined as belonging to a "MembershipUser".
I think what you're really looking for is a user profile. Using ASP.NET profiles is boatloads easier than implementing your own provider. You can find the overview here.
Just so you know, I've tried to go down the MembershipProvider path before, and it's a long and windy one. You might see if just creating classes that implement IPrincipal and IIdentity will satisfy your needs, since they entail a lot less overhead.

Resources