Friday, December 14, 2018

Authentication in MVC

First thing that we need to do is to create CustomMembership class that should inherits from MembershipProvider.

ValidateUser which takes username and password as parameters and test simply if user exists or not.
GetUser is responsible to return user data based on username parameter.
GetUserNameByEmail accepts email as parameter, and return username as result. 

CustomMembership.cs 
using CustomAuthenticationMVC.DataAccess;  
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Security;  
  
namespace CustomAuthenticationMVC.CustomAuthentication  
{  
    public class CustomMembership : MembershipProvider  
    {  
  
  
        ///
  
        ///   
        ///
          ///   
        ///   
        ///   
        public override bool ValidateUser(string username, string password)  
        {  
            if(string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))  
            {  
                return false;  
            }  
  
            using (AuthenticationDB dbContext = new AuthenticationDB())  
            {  
                var user = (from us in dbContext.Users  
                            where string.Compare(username, us.Username, StringComparison.OrdinalIgnoreCase) == 0  
                            && string.Compare(password, us.Password, StringComparison.OrdinalIgnoreCase) == 0  
                            && us.IsActive == true  
                            select us).FirstOrDefault();  
  
                return (user != null) ? true : false;  
            }  
        }  
  
        ///
  
        ///   
        ///
          ///   
        ///   
        ///   
        ///   
        ///   
        ///   
        ///   
        ///   
        ///   
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)  
        {  
            throw new NotImplementedException();  
        }  
  
        ///
  
        ///   
        ///
          ///   
        ///   
        ///   
        public override MembershipUser GetUser(string username, bool userIsOnline)  
        {  
            using (AuthenticationDB dbContext = new AuthenticationDB())  
            {  
                var user = (from us in dbContext.Users  
                            where string.Compare(username, us.Username, StringComparison.OrdinalIgnoreCase) == 0  
                            select us).FirstOrDefault();  
  
                if(user == null)  
                {  
                    return null;  
                }  
                var selectedUser = new CustomMembershipUser(user);  
  
                return selectedUser;  
            }  
        }  
  
        public override string GetUserNameByEmail(string email)  
        {  
            using (AuthenticationDB dbContext = new DataAccess.AuthenticationDB())  
            {  
                string username = (from u in dbContext.Users  
                                   where string.Compare(email, u.Email) == 0  
                                   select u.Username).FirstOrDefault();  
  
                return !string.IsNullOrEmpty(username) ? username : string.Empty;  
            }  
        }  

        #region Overrides of Membership Provider  
  
        public override string ApplicationName  
        {  
            get  
            {  
                throw new NotImplementedException();  
            }  
  
            set  
            {  
                throw new NotImplementedException();  
            }  
        }  
  
        public override bool EnablePasswordReset  
        {  
            get  
            {  
                throw new NotImplementedException();  
            }  
        }  
  
        public override bool EnablePasswordRetrieval  
        {  
            get  
            {  
                throw new NotImplementedException();  
            }  
        }  
  
        public override int MaxInvalidPasswordAttempts  
        {  
            get  
            {  
                throw new NotImplementedException();  
            }  
        }  
  
        public override int MinRequiredNonAlphanumericCharacters  
        {  
            get  
            {  
                throw new NotImplementedException();  
            }  
        }  
  
        public override int MinRequiredPasswordLength  
        {  
            get  
            {  
                throw new NotImplementedException();  
            }  
        }  
  
        public override int PasswordAttemptWindow  
        {  
            get  
            {  
                throw new NotImplementedException();  
            }  
        }  
  
        public override MembershipPasswordFormat PasswordFormat  
        {  
            get  
            {  
                throw new NotImplementedException();  
            }  
        }  
  
        public override string PasswordStrengthRegularExpression  
        {  
            get  
            {  
                throw new NotImplementedException();  
            }  
        }  
  
        public override bool RequiresQuestionAndAnswer  
        {  
            get  
            {  
                throw new NotImplementedException();  
            }  
        }  
  
        public override bool RequiresUniqueEmail  
        {  
            get  
            {  
                throw new NotImplementedException();  
            }  
        }  
  
        public override bool ChangePassword(string username, string oldPassword, string newPassword)  
        {  
            throw new NotImplementedException();  
        }  
  
        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)  
        {  
            throw new NotImplementedException();  
        }  
  
        public override bool DeleteUser(string username, bool deleteAllRelatedData)  
        {  
            throw new NotImplementedException();  
        }  
  
        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)  
        {  
            throw new NotImplementedException();  
        }  
  
        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)  
        {  
            throw new NotImplementedException();  
        }  
  
        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)  
        {  
            throw new NotImplementedException();  
        }  
  
        public override int GetNumberOfUsersOnline()  
        {  
            throw new NotImplementedException();  
        }  
  
        public override string GetPassword(string username, string answer)  
        {  
            throw new NotImplementedException();  
        }  
  
        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)  
        {  
            throw new NotImplementedException();  
        }  
  
        public override string ResetPassword(string username, string answer)  
        {  
            throw new NotImplementedException();  
        }  
  
        public override bool UnlockUser(string userName)  
        {  
            throw new NotImplementedException();  
        }  
  
        public override void UpdateUser(MembershipUser user)  
        {  
            throw new NotImplementedException();  
        }  

        #endregion  
    }  



Now, we need to create CustomRole class that should inherits from RoleProvider then we will override GetRolesForUser & IsUserInRole methods respectively.

CustomRole.cs 

using CustomAuthenticationMVC.DataAccess;  
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Security;  
  
namespace CustomAuthenticationMVC.CustomAuthentication  
{  
    public class CustomRole : RoleProvider  
    {  
        ///   
        ///   
        ///
          ///   
        ///   
        ///   
        public override bool IsUserInRole(string username, string roleName)  
        {  
            var userRoles = GetRolesForUser(username);  
            return userRoles.Contains(roleName);  
        }  
  
        ///   
        ///   
        ///
          ///   
        ///   
        public override string[] GetRolesForUser(string username)  
        {  
            if (!HttpContext.Current.User.Identity.IsAuthenticated)  
            {  
                return null;  
            }  
  
            var userRoles = new string[] { };  
  
            using (AuthenticationDB dbContext = new AuthenticationDB())  
            {  
                var selectedUser = (from us in dbContext.Users.Include("Roles")  
                                    where string.Compare(us.Username, username, StringComparison.OrdinalIgnoreCase) == 0  
                                    select us).FirstOrDefault();  
  
                  
                if(selectedUser != null)  
                {  
                    userRoles = new[] { selectedUser.Roles.Select(r=>r.RoleName).ToString() };  
                }  
  
                return userRoles.ToArray();  
            }  
  
  
        }  



        #region Overrides of Role Provider  
  
        public override string ApplicationName  
        {  
            get  
            {  
                throw new NotImplementedException();  
            }  
  
            set  
            {  
                throw new NotImplementedException();  
            }  
        }  
  
        public override void AddUsersToRoles(string[] usernames, string[] roleNames)  
        {  
            throw new NotImplementedException();  
        }  
  
        public override void CreateRole(string roleName)  
        {  
            throw new NotImplementedException();  
        }  
  
        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)  
        {  
            throw new NotImplementedException();  
        }  
  
        public override string[] FindUsersInRole(string roleName, string usernameToMatch)  
        {  
            throw new NotImplementedException();  
        }  
  
        public override string[] GetAllRoles()  
        {  
            throw new NotImplementedException();  
        }  
  
        public override string[] GetUsersInRole(string roleName)  
        {  
            throw new NotImplementedException();  
        }  
  
  
        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)  
        {  
            throw new NotImplementedException();  
        }  
  
        public override bool RoleExists(string roleName)  
        {  
            throw new NotImplementedException();  
        }  

        #endregion  
    }  

}  

Now inherit IPrinciple.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Security.Principal;  
using System.Web;  
  
namespace CustomAuthenticationMVC.CustomAuthentication  
{  
    public class CustomPrincipal : IPrincipal  
    {  
        #region Identity Properties  
  
        public int UserId { get; set; }  
        public string FirstName { get; set; }  
        public string LastName { get; set; }  
        public string Email { get; set; }  
        public string[] Roles { get; set; }  
        #endregion  
  
        public IIdentity Identity  
        {  
            get; private set;  
        }  
  
        public bool IsInRole(string role)  
        {  
            if (Roles.Any(r => role.Contains(r)))  
            {  
                return true;  
            }  
            else  
            {  
                return false;  
            }  
        }  
  
        public CustomPrincipal(string username)  
        {  
            Identity = new GenericIdentity(username);  
        }  
    }  
}  

https://www.c-sharpcorner.com/article/custom-authentication-with-asp-net-mvc/

No comments:

Followers

Link