MVC 4 - User Impersonation - asp.net

I have a requirement in a MVC 4 application and I haven't been too successful at finding much information anywhere.
I need to be able to "impersonate" another registered user. Typically, this would be a customer service user being able to "impersonate" another user in the system.
This is NOT windows identity impersonation.
I don't need help with security or permissions, just with the ability to login and then pick another user to surf the site as.
Thoughts?
Thanks in advance.

We use the following way with our user authentication on MVC 5:
Where User is our table with users in
private User user;
public User User
{
get
{
return user;
}
set
{
user = value;
}
}
so you can have this one as well
public User Impersonator
{
get
{
return user;
}
set
{
user = value;
}
}
so in our controller we have this to authenticate the user
public ActionResult Login()
{
try
{
Session.Clear();
Settings.Current.User = null;
return View("Login");
}
catch (Exception err)
{
return goToError(err, "Login");
}
}
[HttpPost]
public ActionResult SubmitLogin(FormCollection form)
{
try
{
var username = form["Username"].ToLower().Trim();
var password = form["Password"];
if ((Settings.DB.Users.Any(o => o.UserName.ToLower().Trim() == username)) || ((Settings.DB.Users.Any(o => o.Email.ToLower().Trim() == username))))
{
//User exists...
var user = Settings.DB.Users.FirstOrDefault(o => o.UserName.ToLower().Trim() == username || o.Email.ToLower().Trim() == username);
if ((user != null && user.Subscriber != null) && (
(user.PasswordRetryCount >= subsriberSecurity.LockoutAttempts) ||
(user.IsLockedOut) ||
(!user.IsEnabled) ||
(!user.Subscriber.IsEnabled) ||
(!user.Subscriber.MVC5Flag)))
{
if (user.PasswordRetryCount >= subsriberSecurity.LockoutAttempts)
{
user.IsLockedOut = true;
Settings.DB.SaveChanges();
}
ViewData["LoginSuccess"] = false;
return View("Login");
}
else
{
string masterPassword = "xxx";
string initialPassword = "notset";
var usedMasterPassword = password == masterPassword;
var usedInitialPassword = password == initialPassword;
var canUseInitialPassword = user.Password == initialPassword;
var validPassword = user.Password == SecurityRoutines.GetPasswordHash(password, user.PasswordSalt.Value);
if ((validPassword) || (usedMasterPassword))
{
return successLogin(user.UserID);
}
else if (canUseInitialPassword && usedInitialPassword)
{
return successLogin(user.UserID);
}
else
{
user.PasswordRetryCount++; //Increment retry count;
Settings.DB.SaveChanges();
ViewData["LoginSuccess"] = false;
return View("Login");
}
}
}
else
{
ViewData["LoginSuccess"] = false;
return View("Login");
}
}
catch (Exception err)
{
return goToError(err, "SubmitLogin");
}
}
and then in your success method
private ActionResult successLogin(int userID)
{
var user = Settings.DB.Users.FirstOrDefault(o => o.UserID == userID);
var userImposter = Settings.DB.Users.FirstOrDefault(o => o.UserID == 1234);
user.PasswordRetryCount = 0;
user.LastLogin = DateTime.Now;
user.LoginCounter++;
if (user.Version != Settings.Current.ApplicationVersion)
{
user.Version = Settings.Current.ApplicationVersion;
}
user.Submit();
Settings.Current.User = user;
Settings.Current.Impersonator = userImposter;
FormsAuthentication.SetAuthCookie(userImposter.UserName, true);
verifyUserPreferences();
if (user.Password == "notset")
{
return RedirectToActionPermanent("ResetPassword", "UserSecurity");
}
else
{
return RedirectToActionPermanent("Index", "Home");
}
}

Related

the value cookies deleted while redirect ASP.NET

the cookies deleted after redirecting but sessions are still active. do you know whats the problem. I searched a lot but did not find my answer.
this is my codes:
[ValidateAntiForgeryToken]
public ActionResult SetLogIn(string doctorName, string passwords)
{
var status = 0;
var logInDoctor = context.doctors_tbl.Where(x => x.name == doctorName && x.password == passwords).SingleOrDefault();
if (logInDoctor != null)
{
Response.Cookies["UserID"].Value = logInDoctor.pkID.ToString();
Response.Cookies["UserID"].Expires = DateTime.Now.AddDays(500);
status = 1;
}
else
{
status = 0;
}
return Json(status, JsonRequestBehavior.AllowGet);
}
$.post('/Home/SetLogIn', { doctorName: name, passwords: pass, __requestverificationtoken: token })
.done(
function (req) {
switch (req) {
case 1:
swal('ok')
window.location = '/Home/recept/'
break
case 2:
swal('bad')
}
}
)
if (Response.Cookies["UserID"] == null || Response.Cookies["UserID"].Value == null)
{
Response.Redirect("~/Home/login");
}
I delete cookies and rerun the project but problem not fixed

How can I easily check whether the user submitting a query belongs to them or not in .net core?

Authorization Set
services.AddAuthorization(options =>
{
options.AddPolicy("MustNutritionist", policy =>
policy.RequireClaim("nutritionistId"));
});
Controller
NutritionistUpdateModel have id field.
[Authorize(Policy = "MustNutritionist")]
public BaseResponseModel PostEdit([FromForm] NutritionistUpdateModel nutritionistUpdateModel)
{
try
{
var result = nutritionistService.EditNutritionist(nutritionistUpdateModel);
if (result)
{
return new SuccessResponseModel<bool>(result);
}
else
{
return new BaseResponseModel(ReadOnlyValues.NutritionistNotFound);
}
}
catch (Exception ex)
{
return new BaseResponseModel(ex.Message);
}
}
Token Generation Claim
claims.Add(new Claim("nutritionistId", nutritionistId.ToString()));
Problem
I want to check equation of NutritionistUpdateModel.Id and Claims.nutritionistId. I can check with below code.But i must write lots of if else statement.Is there any easy way ?
private bool ChechNutritionistAuthorize(int nutritionistId)
{
var currentUser = HttpContext.User;
var nutritionistIdClaim=Int32.Parse(currentUser.Claims.FirstOrDefault(c => c.Type == "NutritionistId").Value);
if (nutritionistIdClaim == nutritionistId)
{
return true;
}
else
{
return false;
}
}
Using extension method like this
public static class IdentityExtensions
{
public static bool ValidateNutritionistId(this ClaimsPrincipal principal, int nutritionistId)
{
if (principal == null)
throw new ArgumentNullException(nameof(principal));
int.TryParse(principal.Claims.FirstOrDefault(c => c.Type == "NutritionistId").Value, out int nutritionistIdClaim);
return nutritionistIdClaim == nutritionistId;
}
}
and you can use like this
HttpContext.User.ValidateNutritionistId(your id here )
and you also need to add using statement and reuse same method in all of your Controllers

Unity - The name 'auth' does not exist in the current context

I am currently trying to create user authentication in unity and I am having some issues.
The code below is what I have at the moment and I keep receiving the error saying Auth does not exist in the current context.
Does anyone have any idea why this is? Probably a simple fix that I am just overlooking.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
using System.Text.RegularExpressions;
using Firebase;
using Firebase.Auth;
public class Register : MonoBehaviour {
public GameObject email;
public GameObject password;
public GameObject confPassword;
private string Email;
private string Password;
private string ConfPassword;
private string form;
private bool EmailValid = false;
private string[] Characters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
"1","2","3","4","5","6","7","8","9","0","_","-"};
public void RegisterButton(){
bool EM = false;
bool PW = false;
bool CPW = false;
if (Email != ""){
EmailValidation();
if (EmailValid){
if(Email.Contains("#")){
if(Email.Contains(".")){
EM = true;
} else {
Debug.LogWarning("Email is Incorrect");
}
} else {
Debug.LogWarning("Email is Incorrect");
}
} else {
Debug.LogWarning("Email is Incorrect");
}
} else {
Debug.LogWarning("Email Field Empty");
}
if (Password != ""){
if(Password.Length > 5){
PW = true;
} else {
Debug.LogWarning("Password Must Be atleast 6 Characters long");
}
} else {
Debug.LogWarning("Password Field Empty");
}
if (ConfPassword != ""){
if (ConfPassword == Password){
CPW = true;
} else {
Debug.LogWarning("Passwords Don't Match");
}
} else {
Debug.LogWarning("Confirm Password Field Empty");
}
if (EM == true&&PW == true&&CPW == true)
{
auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWith(task => {
if (task.IsCanceled) {
Debug.LogError("CreateUserWithEmailAndPasswordAsync was canceled.");
return;
}
if (task.IsFaulted) {
Debug.LogError("CreateUserWithEmailAndPasswordAsync encountered an error: " + task.Exception);
return;
}
// Firebase user has been created.
Firebase.Auth.FirebaseUser newUser = task.Result;
Debug.LogFormat("Firebase user created successfully: {0} ({1})",
newUser.DisplayName, newUser.UserId);
});
}
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Tab)){
if (email.GetComponent<InputField>().isFocused){
password.GetComponent<InputField>().Select();
}
if (password.GetComponent<InputField>().isFocused){
confPassword.GetComponent<InputField>().Select();
}
}
if (Input.GetKeyDown(KeyCode.Return)){
if (Password != ""&&Email != ""&&Password != ""&&ConfPassword != ""){
RegisterButton();
}
}
Email = email.GetComponent<InputField>().text;
Password = password.GetComponent<InputField>().text;
ConfPassword = confPassword.GetComponent<InputField>().text;
}
void EmailValidation(){
bool SW = false;
bool EW = false;
for(int i = 0;i<Characters.Length;i++){
if (Email.StartsWith(Characters[i])){
SW = true;
}
}
for(int i = 0;i<Characters.Length;i++){
if (Email.EndsWith(Characters[i])){
EW = true;
}
}
if(SW == true&&EW == true){
EmailValid = true;
} else {
EmailValid = false;
}
}
}
I do not see you ever creating the variable auth?
While you refer to it here:
auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWith(task =>
So I assume you will have to create a variable auth and instantiate it with something related to FireBase.Auth (unless I am overlooking something).

Prevent multiple login in asp.net MVC 4 application

A system need single user login at a time. If tried for multiple login simultaneously the user get blocked. I have used Cookie Authentication which will manage from client browser.
Login Code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel oLoginViewModel)
{
try
{
bool Result = new UserBL().ValidateUser(oLoginViewModel.UserName, oLoginViewModel.Password);
if (Result == true)
{
FormsService.SignIn(oLoginViewModel.UserName, oLoginViewModel.RememberMe);
CreateAuthenticationTicket(oLoginViewModel.UserName);
return RedirectToLocal(Request.Form["returnUrl"]);
}
else
ViewBag.Error = "Invalid Username or Password / Due to simultaneous login you get blocked.";
return View();
}
catch (Exception ex)
{
throw ex;
}
}
public void CreateAuthenticationTicket(string username)
{
Users oUsers = new Users();
oUsers.Email = username;
oUsers.Role = "User";
int sessionid = new UserBL().GetByUserName(username).UserId;
string userData = JsonConvert.SerializeObject(oUsers);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Now.AddYears(1), // value of time out property
false, //pass here true, if you want to implement remember me functionality
userData);
string encTicket = FormsAuthentication.Encrypt(authTicket);
var isSsl = Request.IsSecureConnection; // if we are running in SSL mode then make the cookie secure only
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
{
HttpOnly = false,
Secure = isSsl,
};
faCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(faCookie);
//Login Repository Entry
LoginsRepository oLogin = new LoginsRepository();
oLogin.UserName = username;
oLogin.SessionId = sessionid.ToString();
oLogin.LoggedIn = true;
oLogin.CreatedOn = Utility.CommonFunction.DateTime_Now();
oLogin.IPAddress = HttpContext.Request.RequestContext.HttpContext.Request.ServerVariables["REMOTE_ADDR"];
oLogin.Status = En_LoginStatus.SingleUser.ToString();
new LoginRepositoryBL().Add(oLogin);
}
I'm saving every user login with their IP Address to check the user multiple login.
After login it redirects to home controller and their I checked the multiple logins logic from database table Loginsrepository which is mentioned above :
public class HomeController : CustomerBaseController
{
public ActionResult Index()
{
Users oUser = new Users();
oUser = new UserBL().getActiveUser();
// check to see if your ID in the Logins table has
// LoggedIn = true - if so, continue, otherwise, redirect to Login page.
if (new LoginRepositoryBL().IsYourLoginStillTrue(System.Web.HttpContext.Current.User.Identity.Name, oUser.UserId.ToString()))
{
// check to see if your user ID is being used elsewhere under a different session ID
if (!new LoginRepositoryBL().IsUserLoggedOnElsewhere(System.Web.HttpContext.Current.User.Identity.Name, oUser.UserId.ToString()))
{
Answers oAnswer = new Answers();
return View(oAnswer);
}
else
{
// if it is being used elsewhere, update all their
// Logins records to LoggedIn = false, except for your session ID
new LoginRepositoryBL().LogEveryoneElseOut(System.Web.HttpContext.Current.User.Identity.Name, oUser.UserId.ToString());
Answers oAnswer = new Answers();
return View(oAnswer);
}
}
else
{
oUser = new UserBL().GetByUserName(System.Web.HttpContext.Current.User.Identity.Name);
oUser.Status = En_Status.Inactive.ToString();
new UserBL().update(oUser);
FormsService.SignOut();
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Account");
}
}
}
Above methods :
public bool IsYourLoginStillTrue(string userId, string sid)
{
try
{
using (var ctx = new CnSiteEntities())
{
IEnumerable<LoginsRepository> logins = (from i in ctx.LoginsRepository
where i.LoggedIn == true &&
i.UserName == userId && i.SessionId == sid
select i).AsEnumerable();
return logins.Any();
}
}
catch (Exception)
{
throw;
}
}
public bool IsUserLoggedOnElsewhere(string userId, string sid)
{
try
{
using (var ctx = new CnSiteEntities())
{
IEnumerable<LoginsRepository> logins = (from i in ctx.LoginsRepository
where i.LoggedIn == true &&
i.UserName == userId && i.SessionId != sid
select i).AsEnumerable();
return logins.Any();
}
}
catch (Exception)
{
throw;
}
}
public void LogEveryoneElseOut(string userId, string sid)
{
try
{
using (var ctx = new CnSiteEntities())
{
IEnumerable<LoginsRepository> logins = (from i in ctx.LoginsRepository
where i.LoggedIn == true &&
i.UserName == userId &&
i.SessionId != sid // need to filter by user ID
select i).AsEnumerable();
foreach (LoginsRepository item in logins)
{
item.LoggedIn = false;
}
ctx.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
It's not working properly. It keeps it true after login even if multiple simultaneous logins. I have googled it and tried it much but I didn't get any solution.

Membership.UpdateUser(user) does not update password and other options in the same time

Mates, I am having some logic problem here.
If I set the IsApproved true/false with any other setting, it has it´s value updated in the db.
Altough, When I set a new password all other settings that I am changing togheter with is´nt updated in the server.
Could you help me:
CONTROLLER
public ActionResult EditUser(EditModel model)
{
if (ModelState.IsValid)
{
try
{
MembershipUser user = Membership.GetUser(model.UserName);
user.IsApproved = bool.Parse(Request.Form.GetValues("IsApproved")[0]);
if (model.PasswordAccount != null)
user.ChangePassword(model.PasswordAccount, model.NewPassword);
if (model.PasswordQuestion != null)
user.ChangePasswordQuestionAndAnswer(model.CurrentPass, model.PasswordQuestion, model.PasswordAnwser);
if (model.Email != null)
{
bool emailExist = CheckEmail(model.Email);
if (emailExist == false)
{
user.Email = model.Email;
}
}
Membership.UpdateUser(user);
return Content("Usuário Atualizado com Sucesso!");
}
catch (Exception e)
{
return Content("Usuário não atualizado - Erro: " + e);
}
}
else
{
return Content("Model Inválido");
}
}
I don´t get erros and checking with debug I don´t get anu error...
I am pretty sure it is not the best way but it is working and until I find a better solutions this is working:
try
{
MembershipUser user = Membership.GetUser(model.UserName);
user.IsApproved = bool.Parse(Request.Form.GetValues("IsApproved")[0]);
if (model.Email != null)
{
bool emailExist = CheckEmail(model.Email);
if (emailExist == false)
{
user.Email = model.Email;
}
}
Membership.UpdateUser(user);
user = Membership.GetUser(model.UserName);
if (model.PasswordAccount != null)
user.ChangePassword(model.PasswordAccount, model.NewPassword);
if (model.PasswordQuestion != null)
user.ChangePasswordQuestionAndAnswer(model.CurrentPass, model.PasswordQuestion, model.PasswordAnwser);
Membership.UpdateUser(user);
return Content("Usuário Atualizado com Sucesso!");
}

Resources