I am using asp.net membership. I have login successfully but when I have access user than user.Identity.GetUserId() always null.
this is my login code.
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
SignInStatus result = signinManager.PasswordSignIn(txtEmail.Text, txtPassword.Text, RememberMe.Checked, false);
switch (result)
{
case SignInStatus.Success:
string strReturnUrl = Request.QueryString["ReturnUrl"] ?? "";
if (string.IsNullOrWhiteSpace(strReturnUrl))
{
if (GenericMethods.CheckUserInRole(user, UserRoles.SystemAdmin.ToString()))
strReturnUrl = "~/Admin/SettingsMaster.aspx";
else if (GenericMethods.CheckUserInRole(user, UserRoles.Admin.ToString()))
strReturnUrl = "~/Admin/SettingsMaster.aspx";
else if (GenericMethods.CheckUserInRole(user, UserRoles.CorporateSponsor.ToString()))
strReturnUrl = "~/";
else if (GenericMethods.CheckUserInRole(user, UserRoles.Advertiser.ToString()))
{
int productcount = ProductBL.GetInactiveProductCount(user.Id);
if (String.IsNullOrEmpty(user.FirstName) || String.IsNullOrEmpty(user.LastName) ||
String.IsNullOrEmpty(user.Address1) || String.IsNullOrEmpty(user.PhoneNumber) ||
String.IsNullOrEmpty(user.Email) || String.IsNullOrWhiteSpace(user.Birthdate.ToString()))
{
strReturnUrl = "~/MyAccount/ProfileSetting.aspx";
}
else if (productcount > 0)
{
strReturnUrl = "~/MyAccount/ViewFeatureProduct.aspx";
}
else
strReturnUrl = "~/MyAccount/AdvertiserTutorial.aspx";
}
else if (GenericMethods.CheckUserInRole(user, UserRoles.Subscriber.ToString()))
{
int productcount = ProductBL.GetInactiveProductCount(user.Id);
if (String.IsNullOrEmpty(user.FirstName) || String.IsNullOrEmpty(user.LastName) ||
String.IsNullOrEmpty(user.Address1) || String.IsNullOrEmpty(user.PhoneNumber) ||
String.IsNullOrEmpty(user.Email) || string.IsNullOrWhiteSpace(user.Birthdate.ToString()))
{
strReturnUrl = "~/MyAccount/ProfileSetting.aspx";
}
else if (productcount == 0)
{
strReturnUrl = "~/MyAccount/TradeMyStuff.aspx";
}
else
strReturnUrl = "~/";
}
}
var userLoginInfo = new UserLoginInfo("ClosetAuctions.com", "CA");
userManager.AddLogin(user.Id, userLoginInfo);
user.LastLoginDate = DateTime.Now;
userManager.Update(user);
IdentityHelper.RedirectToReturnUrl(strReturnUrl, Response);
break;
case SignInStatus.LockedOut:
Response.Redirect("/Account/Lockout");
break;
case SignInStatus.RequiresVerification:
Response.Redirect(
String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
Request.QueryString["ReturnUrl"],
RememberMe.Checked),
true);
break;
// ReSharper disable once RedundantCaseLabel
case SignInStatus.Failure:
default:
FailureText.Text = "Invalid login attempt";
ErrorMessage.Visible = true;
break;
}
I am getting userId here.
public static ApplicationUser GetCurrentUser()
{
var user = HttpContext.Current.User;
if (user == null) return null;
if (user.Identity.GetUserId() == null) return null;
var db = new MyDbContext();
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
return manager.FindById(user.Identity.GetUserId());
// manager.AddClaim(CurrentUser.Id, new Claim(ClaimTypes.Role, "systemAdmin"));
// manager.AddClaim(CurrentUser.Id, new Claim(ClaimTypes.Role, "admin"));
}
I am not sure, where I am wrong.
If any one know then Can you please help me.
Maybe you check authentication first.
if (User.Identity.IsAuthenticated)
{
string userId = HttpContext.Current.User.Identity.Name;
}
Related
I have an ASP.Net web form application that users can register to. In the registration process, some user details are stored as claims, the MemberApproved variable is used to check the approval status of a user, it is set to "No" when the user is created, and can be changed later by admin:
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text, FirstName = FirstName.Text, LastName = LastName.Text,MemberApproved="No" };
THis is working fine and I can see the user details above added correctly in the AspNetUsers
Then I am trying to check if the user has been approved by an admin when they login, in this process, I am trying to retrieve MemberApproved value using the following code:
protected void Page_Load(object sender, EventArgs e)
{
RegisterHyperLink.NavigateUrl = "Register";
OpenAuthLogin.ReturnUrl = Request.QueryString["ReturnUrl"];
var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
if (!String.IsNullOrEmpty(returnUrl))
{
RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl;
}
}
protected void LogIn(object sender, EventArgs e)
{
if (IsValid)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
var claims = ClaimsPrincipal.Current.Identities.First().Claims.ToList();
string MemberApproved = claims?.FirstOrDefault(x => x.Type.Equals("MemberApproved", StringComparison.OrdinalIgnoreCase))?.Value;
if (MemberApproved == "No")
{
FailureText.Text = "User not approved yet";
ErrorMessage.Visible = true;
break;
}
else
{ IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
break;
}
case SignInStatus.LockedOut:
Response.Redirect("/Account/Lockout");
break;
case SignInStatus.RequiresVerification:
Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
Request.QueryString["ReturnUrl"],
RememberMe.Checked),
true);
break;
case SignInStatus.Failure:
default:
FailureText.Text = "Invalid login attempt";
ErrorMessage.Visible = true;
break;
}
}
}
}
I am however running into problems and the code above does not seem to be able to retrieve the value of "MemberApproved"
Any suggestions would be very much appreciated.
I'm using the new Microsoft identity to manage my website login and register.
I've configured the website to start using external login (Facebook).
How i can get the Access Token in the (RegisterExternalLogin) page?
``
protected void Page_Load(){
// Process the result from an auth provider in the request
ProviderName = IdentityHelper.GetProviderNameFromRequest(Request);
if (String.IsNullOrEmpty(ProviderName))
{
RedirectOnFail();
return;
}
if (!IsPostBack)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
if (loginInfo == null)
{
RedirectOnFail();
return;
}
var user = manager.Find(loginInfo.Login);
if (user != null)
{
IdentityHelper.SignIn(manager, user, isPersistent: false);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else if (User.Identity.IsAuthenticated)
{
Response.Write("ok.2");
// Apply Xsrf check when linking
var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId());
if (verifiedloginInfo == null)
{
RedirectOnFail();
return;
}
var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login);
if (result.Succeeded)
{
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else
{
AddErrors(result);
return;
}
}
else
{
try
{
var accessToken = "What can i get the access token";
Response.Write(accessToken + "<br>");
var client = new FacebookClient(accessToken);
//var client = new FacebookClient();
dynamic me = client.Get("me");
string firstName = me.first_name;
string lastName = me.last_name;
Response.Write(firstName + " " + lastName);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
email.Text = loginInfo.Email;
}
}
}
Regards,
Moayyad
public ViewResult Index(string currentFilter, string searchString, int? page)
{
if (Request.HttpMethod == "GET")
{
searchString = currentFilter;
}
else
{
page = 1;
}
ViewBag.CurrentFilter = searchString;
var connString = ConfigurationManager.ConnectionStrings["ApplicantDB"].ConnectionString;
List<Applicant> instructors = new List<Applicant>();
using (var conn = new SqlConnection(connString))
{
conn.Open();
var query = new SqlCommand("SELECT TOP 50 APPLICANT_ID, APPLICANT_Lastname, APPLICANT_FirstName, APPLICANT_MiddleName, APPLICANT_Address, APPLICANT_City"+
" FROM APPLICANT", conn);
var reader = query.ExecuteReader();
int currentPersonID = 0;
Applicant currentInstructor = null;
while (reader.Read())
{
var personID = Convert.ToInt32(reader["APPLICANT_ID"]);
if (personID != currentPersonID)
{
currentPersonID = personID;
if (currentInstructor != null)
{
instructors.Add(currentInstructor);
}
currentInstructor = new Applicant();
currentInstructor.APPLICANT_ID = Convert.ToInt32(reader["APPLICANT_ID"].ToString());
currentInstructor.APPLICANT_Lastname = reader["APPLICANT_Lastname"].ToString();
currentInstructor.APPLICANT_FirstName = reader["APPLICANT_FirstName"].ToString();
currentInstructor.APPLICANT_MiddleName = reader["APPLICANT_MiddleName"].ToString();
currentInstructor.APPLICANT_Address = reader["APPLICANT_Address"].ToString();
currentInstructor.APPLICANT_City = reader["APPLICANT_City"].ToString();
}
if (!String.IsNullOrEmpty(searchString))
{
currentInstructor = instructors.AsQueryable().Where(s => s.APPLICANT_Lastname.ToUpper().Contains(searchString.ToUpper())
|| s.APPLICANT_FirstName.ToUpper().Contains(searchString.ToUpper()));
}
}
if (currentInstructor != null)
{
instructors.Add(currentInstructor);
}
reader.Close();
conn.Close();
}
int pageSize = 10;
int pageNumber = (page ?? 0);
return View(instructors.ToPagedList(pageNumber, pageSize));
}
Error in this Line
if (!String.IsNullOrEmpty(searchString))
{
currentInstructor = instructors.AsQueryable().Where(s => s.APPLICANT_Lastname.ToUpper().Contains(searchString.ToUpper())
|| s.APPLICANT_FirstName.ToUpper().Contains(searchString.ToUpper()));
}
This is the first time i encountered this type of error . .
I wasted almost 2 hours in this kind of error
I hope someone can help me in this situation. . advance thank you for those who are willing to help. . So much appreciated :) KUDOS !!
As the error says, you are trying to assign single object to list.
currentInstructor = instructors.AsQueryable().Where(s => s.APPLICANT_Lastname.ToUpper().Contains(searchString.ToUpper())
|| s.APPLICANT_FirstName.ToUpper().Contains(searchString.ToUpper()));
If there can be only one result you need to use SingleOrDefault() and if there are multiple records, use FirstOrDefault() which extracts first record from result set.
instructors.AsQueryable().Where(s => s.APPLICANT_Lastname.ToUpper().Contains(searchString.ToUpper())
|| s.APPLICANT_FirstName.ToUpper().Contains(searchString.ToUpper())).FirstOrDefault();
You probably want the first applicant in the list.
currentInstructor = instructors
.AsQueryable()
.Where(s => s.APPLICANT_Lastname.ToUpper().Contains(searchString.ToUpper()) || s.APPLICANT_FirstName.ToUpper().Contains(searchString.ToUpper()))
.FirstOrDefault();
Following is the code that i am using. It work in IE but the button click event is not generated properly in firefox:
function trapEnter(btn,hdn, event) {
var key;
var isIE = true;
debugger;
if (window.event) {
key = window.event.keyCode; //IE
isIE = true;
}
else {
key = event.which; //firefox
isIE = false;
}
if (key == 13) {
var btn = document.getElementById(btn);
if (btn != null) { //If we find the button click it
document.getElementById(hdn).value = '1'
btn.click();
key = 0;
}
}
}
I think your function has the wrong parameters. Try this:
function trapEnter(e) {
e = e || window.event || event;
var code = e.charCode || e.keyCode || e.which;
if (code == 13) {
var btn = document.getElementById('<%= YourButtonID.ClientID %>');
if (btn != null) { //If we find the button click it
document.getElementById(hdn).value = '1';
btn.click();
key = 0;
}
}
}
I have a problem with my ASP.NET website, it got hacked. One hacker found a bug in my login system and he can login with every account he wants, even if the account is normal user, moderator or administrator. He can delete everything he wants.
Please can anyone help me, tell me if there is any vulnerable function or something
P.S. I'm not myself an ASP.NET programmer, I know only PHP, so please tell me exactly what I need to edit in the code, because I don't know ASP.NET at all.
ThanksAS
public void loginButton_Click(object sender, EventArgs e)
{
string username = nicknameTextBox.Text;
string password = passwordTextBox.Text;
string returnUrl = Request.QueryString["returnUrl"];
if (returnUrl == null) returnUrl = Convert.ToBase64String(Encoding.ASCII.GetBytes(Request.Url.ToString()));
string message = CurrentPlayer.LoginRequest(username, password, returnUrl);
if(message != null)
Response.Redirect("AccountLogin.aspx?returnUrl=" + returnUrl);
}
LoginRequest:
public static string LoginRequest(string username, string password, string returnUrl)
{
Player player = null;
string message = InputValidator.CheckLoginRequest(username, password, out player);
if (message != null) return message;
message = LoginCookie.CheckLoginRequest(player);
if (message != null) return message;
SessionPlayer sessionPlayer = new SessionPlayer(
player.ID, player.ActivationGuid, (PlayerRole)player.IdRole,
player.Nickname, player.CreationDate);
SessionMessages sessionMessages = new SessionMessages(player.ID);
SessionOwnedCounts ownedCounts = new SessionOwnedCounts(player.ID);
SessionGuestCounts guestCounts = new SessionGuestCounts(player.ID);
SessionMatchCounts matchCounts = new SessionMatchCounts(player.ID);
CurrentPlayer.Login(sessionPlayer, sessionMessages, ownedCounts, guestCounts, matchCounts);
Player.UpdateLastLogin(player.ID);
returnUrl = Encoding.ASCII.GetString(Convert.FromBase64String(returnUrl));
HttpContext.Current.Response.Redirect(returnUrl);
return null;
}[/code]
Login:
private static void Login(SessionPlayer player, SessionMessages messages, SessionOwnedCounts ownedCounts, SessionGuestCounts guestCounts, SessionMatchCounts matchCounts)
{
HttpContext.Current.Session["player"] = player;
HttpContext.Current.Session["messages"] = messages;
HttpContext.Current.Session["ownedCounts"] = ownedCounts;
HttpContext.Current.Session["guestCounts"] = guestCounts;
HttpContext.Current.Session["matchCounts"] = matchCounts;
if (LoginCookie.Exists() == false)
LoginCookie.AddForFirstTime(player.Nickname, player.Guid);
else
LoginCookie.SetToLoginAction();
}
And checkloginrequest:
public static string CheckLoginRequest(string username, string password, out Player player)
{
player = null;
object lastLoginTryDateObj = HttpContext.Current.Session["lastLoginTryDate"];
if (lastLoginTryDateObj == null)
{
HttpContext.Current.Session["lastLoginTryDate"] = DateTime.Now;
HttpContext.Current.Session["lastLoginTryCount"] = 1;
}
else
{
DateTime lastLoginTryDate = (DateTime)HttpContext.Current.Session["lastLoginTryDate"];
int lastLoginTryCount = (int)HttpContext.Current.Session["lastLoginTryCount"];
TimeSpan ts = DateTime.Now - lastLoginTryDate;
if (ts.TotalSeconds < 60)
{
if (lastLoginTryCount >= Settings.AllowedLoginTriesPerMinute)
{
return "Ai depasit numarul maxim de incercari pe minut .<br/>Vino inapoi dupa " + (60 - (int)ts.TotalSeconds).ToString() + " secunde.";
}
else
{
HttpContext.Current.Session["lastLoginTryCount"] = lastLoginTryCount + 1;
}
}
else
{
HttpContext.Current.Session["lastLoginTryDate"] = DateTime.Now;
HttpContext.Current.Session["lastLoginTryCount"] = 1;
}
}
player = Player.GetPlayer(username, password);
if (player == null)
{
return "Usernameul si parola nu se potrivesc.";
}
if (player != null && player.IsActive == false)
{
return "Contul a fost creat dar nu e activat.<br/> Verifica mailul " + player.Email + " si activeaza-ti contul.";
}
PlayerSuspended ps = BLL.PlayerSuspended.SuspendedGet(player.ID);
if (ps != null)
{
return "Contul tau e suspendat pana in data de " + ps.SuspendedEndDate.ToString("dd-MM-yyyy") + ".<br/>Motivul: " + ps.SuspendedReason;
}
return null;
}
GetPlayer:
public static Player GetPlayer(string nickname, string password)
{
Player player = null;
object[] values = DAL.Player.GetPlayer(nickname, password);
if (values != null)
{
player = new Player();
player.SetFromValues(values);
}
return player;
}
DAL.Player.GetPlayer:
public static object[] GetPlayer(string nickname, string password)
{
password = Convert.ToBase64String(Encoding.ASCII.GetBytes(password));
List<SqlParameter> sqlParams = new List<SqlParameter>();
sqlParams.Add(new SqlParameter("#Nickname", nickname));
sqlParams.Add(new SqlParameter("#Password", password));
return DataBase.GetFirstRow("[spPlayer.Get]", sqlParams);
}
Your site is vulnerable to session fixation
Why are you not using asp.net forms authentication and membership?