ASP.NET MVC FormsAuthentication.SetAuthCookie with custom Roles - c#

I have created this login post method in my login controller, what it does is that it takes the email submitted (no password) and we run the email in the stored procedure to check if the user exists, if they do Set Authentication Cookie. Now I am looking to add on to this. Here is my current code:
WebServiceController service = new WebServiceController();
[HttpPost]
public ActionResult Index(LoginClass model, string returnUrl)
{
if (!ModelState.IsValid)
{
ModelState.AddModelError("", "The email provided is incorrect.");
return View(model);
}
List<UserClass> user = service.loginUser(model.Email);
if(user.Count > 0)
{
FormsAuthentication.SetAuthCookie(model.Email, true);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
Now service.loginUser also returns a int value called divisionID and a user can have multiple divisionID, I would like the divisionID to be the users Role. My question is how would I go about implementing that?

Related

How can I authenticate user and how can I get first name and second name of user according to the login person?

Below is my login function, I want to change the following:
differentiate between admin login and user login to show different page layouts
get the user's first name and second name according to the login user
please how can I do that any suggestion or examples?
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(Customers customer)
{
if (ModelState.IsValid)
{
var user = await _context.Customers.SingleOrDefaultAsync(m => m.Email == customer.Email && m.Password == customer.Password);
if (user != null)
{
return RedirectToAction("Account", "Account");
}
else
{
ViewBag.error = "Login Failed";
return RedirectToAction("Login");
}
}
else
{
return RedirectToAction("Index", "Home");
}
}
You need to maintain Role column values in login table in DB.
Add values to the Role column Ex : Admin Role - 1 , User - 0
Change the login procedure to return the Role,FirstName,LastName instead of count
Select Role,Password,FirstName,LastName from Users where Username=#Username and Password=#Password
After authenticating the user(valid authentication, if password matches), redirect to the View based on the role.
if (Validate_User(Customers customer))
{
if (customer.Role == "1")
{
return View("AdminView");
}
else
{
return View("UserView");
}
ViewBag.FirstName=customer.FirstName;
ViewBag.LastName=customer.LastName;
}
else
{
//handle failed login
ViewBag.error = "Login Failed";
return RedirectToAction("Login");
}
Please refer Role Based Access

Log in in ASP.Net MVC4

I'm having some trouble with my application, because I need 2 ways to log in: form (user + password) or route (passing user unique identifier).
I configured FormsAuthentication and it's working for user + password method, but when I try to log in through unique identifier, I can't redirect to my HomeController.
User + Password:
[HttpPost]
public string Authenticate(string usuario, string senha, string returnUrl)
{
var authenticated = this.UsuarioService.Acessar(usuario, senha, out int codUsuario);
if (authenticated)
{
var user = this.UsuarioService.Buscar(codUsuario);
MontaPermissoes(ref user);
FormsAuthentication.SetAuthCookie(JsonConvert.SerializeObject(user), false);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
return returnUrl;
else
return Url.Action("Index", "Home", new { id = "" });
}
return null;
}
Unique Identifier:
[HttpGet]
private RedirectToRouteResult Autenticacao(Guid uniqId)
{
var usuario = UsuarioService.Buscar(uniqId);
if (usuario != null)
{
MontaPermissoes(ref usuario);
FormsAuthentication.SetAuthCookie(JsonConvert.SerializeObject(usuario), false);
return RedirectToAction("Index", "Home", new { culture = RouteData.Values["culture"] });
}
return RedirectToAction("Index", "Login", new { culture = RouteData.Values["culture"] });
}
Using user + password, I just return next URL to redirect via Javascript, but unique identifier log in will be used by another application, using the same database.
This problem could be IIS related, your application has to have two authentication options enabled.
FormsAuthentication
Anonymous Authentication
With anonymous authentication enabled the application can allow Anonymous calls.
You can add an AllowAnonymous attribute to your controller or specific controller methods to make sure that FormsAuthentication won't be triggered.
[AllowAnonymous]
public class MyController: Controller {}

redirect to different pages based on user role in ASP.NET MVC 4 Internet Application Login

I'm creating ASP.NET MVC 4 Internet Application. In that Application
I created Login Page that any user can log, then I'm Trying to redirect user to different pages based on their role.
ASP.NET Identity is the membership system here.
In my AspNetRoles Table I have two roles:
Id| Name
1 | HEI_Admin
2 | HEI_User
This is my Login Controller method:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
if (user.ConfirmedEmail == true)
{
await SignInAsync(user, model.RememberMe);
if (String.IsNullOrEmpty(returnUrl))
{
if (UserManager.IsInRole(user.Id, "HEC_Admin"))
{
return RedirectToAction("Index", "HEC");
}
//role Admin go to Admin page
if (UserManager.IsInRole(user.Id, "HEI_User"))
{
return RedirectToAction("Index", "HEI");
}
}
else
{
return RedirectToLocal(returnUrl);
}
}
else
{
ModelState.AddModelError("", "Confirm Email Address.");
}
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
but when I try to log using correct credentials I'm getting following error:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
All the connection are double checked, how can achieve this problem.
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
if (UserManager.IsInRole(user.Id, "Admin"))
{
return RedirectToAction("Index", "Admin");
}
else if (UserManager.IsInRole(user.Id, "Clerk"))
{
return RedirectToAction("Index","Employee");
}
else if (UserManager.IsInRole(user.Id, "Customer"))
{
return RedirectToAction("Index", "Customer");
}
//return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("","Invalid username or password");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
This is the code i used for redirect. also see if the userID and RoleID are inserted into the ASPNETUserRoles table
if you are using any centralized database then Make sure your database engine is configured to accept remote connections.
Go through this link i will solve the same issue with the help of this link

ASP.NET MVC forms authentication equivalent

when I was writing ASP.NET applications I used the Forms Authentication with my custom login page, like so:
Once login is a success I checked him as authenticated:
FormsAuthentication.RedirectFromLoginPage(userId.ToString(), true);
In order to check if a user is logged in, I had a class that inherited from a base page and all pages inherited from it, which contained a method that returned a bool after checking if the user is authenticated, with the following command:
return HttpContext.Current.User.Identity.IsAuthenticated;
Now, I'm doing an ASP.NET MVC application, and was wondering what is the best was to do that on MVC?
Thanks
ok MVC is very simple and similar
for your question you can use like .......
in your controller
public ActionResult LogOn()
{
return View();
}
//
// POST: /Account/LogOn
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var userInfo = new UserInfo()
{
UserName = model.UserName,
Password = model.Password,
};
var service = new CSVService();
if(service.ValidateUser(userInfo))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return Redirect("~/");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
The best way to authenticate website / web-application is using the Membership which is provided by Microsoft built in for Easy-ness .
From this you can do following things(features)
it maintains Log-in status (you don't have to bother about Authentication).
It allows to provide Roles & Users and Assigning permission who can see which page
(Page Restriction)
It provides built-in Stored Procedures and UI tools like Log-in, Log-out,user,Password Recovery, Etc elements. & Highly secure (Hack-Proof)
for more info:
Walk through Membership (MSDN)

ASP.NET MVC Membership, Get new UserID

I am trying to register a new user and also understand how to get the new userID so i can start creating my own user tables with a userID mapping to the asp.net membership user table.
Below is my code:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(string userName, string email, string position, string password, string confirmPassword)
{
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
ViewData["position"] = new SelectList(GetDeveloperPositionList());
if (ValidateRegistration(userName, email, position, password, confirmPassword))
{
// Attempt to register the user
MembershipCreateStatus createStatus = MembershipService.CreateUser(userName, password, email);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuth.SignIn(userName, false /* createPersistentCookie */);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View();
}
I've done some research and many sites inform me to use Membership.GetUser().ProviderUserKey; but this throws an error as Membership is NULL.
I placed this line of code just above "return RedirectToAction("Index", "Home");" within the if statement.
Please can someone advise me on this...
Thanks in advance
Create the user using the MembershipProvider, this will return a MembershipUser instance. Where you can access the ProviderKey to access the Id.
MembershipCreateStatus status;
MembershipUser user = Membership.Provider.CreateUser(userName, password, email, null, null, true, null, out status);
if (status == MembershipCreateStatus.Success)
{
object key = user.ProviderUserKey;
}
This will retrieve the ProviderKey:
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuth.SignIn(userName, false /* createPersistentCookie */);
MembershipUser newUser = Membership.GetUser(model.UserName);
string key = newUser.ProviderUserKey.ToString();
return RedirectToAction("Index", "Home");
}

Categories

Resources