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
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
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).
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.
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!");
}