Page.Profile not saving after user created in a CreateUserWizard - asp.net

I Have the following code which fires OnCreatedUser and doesn't throw any errors. Profile.Title is getting set to the correct value when inspected after the assignment.
public void CreateUserForm_CreatedUser(object sender, EventArgs e)
{
var ddlTitle = (DropDownList)CreateUserWizardStep1.ContentTemplateContainer.FindControl("Title");
Profile.Title = ddlTitle.SelectedValue;
Profile.Save();
}
However, when I test Profile.Title on subsequent pages (the user is definitely logged in) it is == "";
I'm guessing that this is the users old anonymous profile, not the new profile associated with their newly registered user account.
I've tried adding a Profile_MigrateAnonymous method (as suggested here) to my Global.asax but this code doesn't get hit.
How do I save title to the new users account profile?
UPDATE
Here's the code
public void CreateUserForm_CreatedUser(object sender, EventArgs e)
{
var ddlTitle = (DropDownList)CreateUserWizardStep1.ContentTemplateContainer.FindControl("Title");
var emailTextBox = (TextBox)CreateUserWizardStep1.ContentTemplateContainer.FindControl("UserName");
UserProfile profile = (UserProfile)ProfileBase.Create(emailTextBox.Text.Trim());
profile.Title = ddlTitle.SelectedValue;
profile.Save();
}

I think you're correct that the user is still anonymous while that method is called. I'm not familiar with Profile, but I think you need to look the profile up by username instead of relying on the current profile.

Related

ASP.NET membership - Redirect users with unpaid invoice

I'm working on a custom implementation of ASP.NET membership, which uses my own database tables. Everything works as it should, but I need to redirect customers, which have not paid their invoice, to a payment page. This should not only happen on login, but also for users which already are logged in, so if an invoice is registered as "not paid" while the user is logged in, then the user must be redirected to the payment page, the next time they load a page.
Can this be done?
I did something similar to this using a HttpModule. What you want to do is handle the PreRequest event and if they are authenticated and if so make your unpaid invoice check and redirect as necessary.
e.g.
protected void OnPreRequestHandlerExecute(object sender, EventArgs e)
{
if (HttpContext.Current.Request.Path != "/UnPaid.aspx" && HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
// You don't want to make this check for every resource type
bool isPage = HttpContext.Current.Request.Path.EndsWith(".aspx") || HttpContext.Current.Request.Path == "/";
if (isPage)
{
bool isPaid = false; // Make isPaid check here
if (!isPaid)
{
// Optional pass ina return url for after the invoice is paid
string returnUrl = HttpUtility.UrlEncode(HttpContext.Current.Request.RawUrl, HttpContext.Current.Request.ContentEncoding);
HttpContext.Current.Response.Redirect(string.Concat("/UnPaid.aspx?ReturnUrl=", returnUrl), true);
}
}
}
}
}
I wouldn't let the membership provider know this information. It is job of your application to know this, not your security model. It may be as simple as adding/removing a role, but that's not ideal either.
You can do that on global.asax using the Application_AuthenticateRequest
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
string cTheFile = HttpContext.Current.Request.Path;
if(!cTheFile.EndsWith("ThePaymentPage.aspx"))
{
if(HttpContext.Current.User != null
&& HttpContext.Current.User.Identity != null
&& HttpContext.Current.User.Identity.IsAuthenticated)
{
// check here if need to redirect or not.
if(NeedPayment())
{
HttpContext.Current.Responce.Redirect("ThePaymentPage.aspx");
}
}
}
}
This is called on every page, so maybe you can add some more checks and make it real fast. Other checks can be if the page ends on .aspx
How about having inheritance.
You can "inject" a BasePage between Page class and your ASPX code behind class.
This way, you will have access to your business logic classes and then you can decide, on each request, where the user should be re-directed.
Me too agree on the point that this logic should be handled by your applications business logic instead of the security model.
Hope this helps.

how to prevent the user repeat-login

In my application,I do not want two user login with the same login name.
For example, user1 login with name "test1",then user2 try to login with "test1" too,but at this moment the user1's formauthentication does not expire,so the login of user2 should be denied.
I created a cache class to record all the active session:
public class SessionDb {
private static Dictionary<string, HttpSessionState> sessionDB=new Dictionary<string, HttpSessionState>();
public SessionDb() {
}
public static void addUserAndSession(string name, HttpSessionState session) {
sessionDB.Add(name, session);
}
public static bool containUser(string name) {
//in fact,here I also want to check if this session is active or not ,but I do not find the method like session.isActive() or session.HasExpire() or something else.
return sessionDB.ContainsKey(name);
}
public static void removeUser(string name) {
if(sessionDB.ContainsKey(name)) {
sessionDB.Remove(name);
}
}
}
In the login.aspx.cs:
//check the name and password
if(checkNameAndPass(sUserName, sUserPwd)) {
if(!SessionDb.containUser(sUserName)) {
//let the user login
Session["current_user_name"] = sUserName;
SessionDb.addUserAndSession(sUserName, Session);
FormsAuthentication.RedirectFromLoginPage(UserName.Text, false);
}
else {
//
this.error.Text=string.Format("user {0} have logined!", sUserName);
}
}
Global.asax:
void Session_End(object sender, EventArgs e)
{
SessionDb.removeUser(Session["current_user_name"].ToString());
}
But it seems that it the Session_End() method is called at some time according the timeout setting in the sessionState.
Obviously I need the the SessionDb remove the related session when the authentication timeout.
Any idea to improve my code? or any other idea to implement my requirement?
I just do not want the user repeat-login(with the same name).
UPDATE:
BTW,I think my code also have some problems: I store the log in token using the Session,but how about if the formauthentication have timeout but the session does not?
If you are using a Membership provider:
A user is considered online if the current date and time minus the UserIsOnlineTimeWindow property value is earlier than the LastActivityDate for the user.
from MSDN Article
so you can simple use the check
Membership.IsOnline();
before you login the user.
In asp.net site how to prevent multiple logins of same user id?
Another approach (Disclaimer: I have not tested this.):
In the web.config add userIsOnlineTimeWindow to 1 and in the loggingIn event handler:
protected void Login1_LoggingIn(object sender, LoginCancelEventArgs e)
{
MembershipUser u = Membership.GetUser(Login1.UserName);
Response.Write(u.IsOnline);
if (u.IsOnline)
{
Login1.FailureText = "A user with this username is already logged in.";
e.Cancel = true;
}

Custom authentication module inheriting IHttpModule issue

LoginPage.aspx:-
protected void Button1_Click(object sender, EventArgs e)
{
Context.Items["Username"] = txtUserId.Text;
Context.Items["Password"] = txtPassword.Text;
//
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, Context.Items["Username"].ToString(), DateTime.Now, DateTime.Now.AddMinutes(10), true, "users", FormsAuthentication.FormsCookiePath);
// Encrypt the cookie using the machine key for secure transport
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
hash); // Hashed ticket
// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
Response.Cookies.Add(cookie);
Response.Redirect("Default.aspx");
}
Global.asax file:-
void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id =
(FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
// Get the stored user-data, in this case, our roles
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
Response.Write(HttpContext.Current.User.Identity.Name);
Response.Redirect("Default.aspx");
}
}
}
}
I get the following error after signing in
This webpage has a redirect loop.
The webpage at http://localhost:1067/Default.aspx has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer.
This is the rough idea of what your module should look like. Your module will run on every request. You don't invoke it or pass anything to it, it just automatically fires whenever a request is made that ASP.Net is set to process.
Your module will do two things, 1) authenticate a user in the login page, 2) authenticate a user on subsequent pages. The first step is to subscribe to the BeginRequest method which will be given the current HttpApplication as the first parameter. From there you need to determine if the user is on your login page or not. If they're not on your login page, check your session or cookie or querystring token, or whatever you're using to make sure that they're still valid. If they're invalid, bounce them back to the login page.
If they're on your login page and have made a POST, look at the raw form fields and validate them. TextBoxes, checkboxes, etc don't exist here, only raw form fields. If they're valid, set your authentication token however you want (session, cookies, etc). If they're invalid, either redirect to the login page or inject a "try again" message or something.
Also, if you double-post a message please reference it so that we can follow the chain of what was already said.
class MyModule : IHttpModule
{
void IHttpModule.Init(HttpApplication context)
{
//Subscribe to the BeginRequest event
context.BeginRequest += new EventHandler(this.Application_BeginRequest);
}
private void Application_BeginRequest(Object source, EventArgs e)
{
//Initialize our variables, null checks should be put here, too
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
System.Web.SessionState.HttpSessionState s = context.Session;
//Normally our module needs to validate every request to make sure our request is still authenticated.
//The exception to that rule is on our logon page where they obviously don't have credentials yet.
if(!context.Request.FilePath.ToLowerInvariant().StartsWith("/login.aspx")){
//If we're here then we're not on the logon page, validate our current session according to whatever logic we want
if (s != null && s["isvalid"] == "true"){
return;
}else{
context.Response.Redirect("/login.aspx");
}
}else{
//If we're here then we're on the login page itself. If there's a post, assume that they've hit the login button
if (context.Request.HttpMethod == "POST")
{
//Whatever your form variables are called
string username = context.Request.Form["username"];
string password = context.Request.Form["password"];
//Your own validation logic would go here
if (MyCustomLogin.IsUserValid(username, password))
{
s["isvalid"] = "true";
context.Response.Redirect("/Home.aspx");
}else{
s["isvalid"] = "false";
context.Response.Redirect("/login.aspx?error=invalid_login");
}
}else{
//If we're here then the request is probably a GET or HEAD which would be from a person
//initially browsing to our page so just do nothing and pass it through normally
}
}
}
}
There is no direct way to have access to this information in the module (for authenticated user, you can access the username via the context, but not the password). The module checks if a request is carrying required authentication information and serve or deny the request based on that. Unless you deliberately from the login page collect this information and store somewhere where you can access it in the module, e.g session. But ideally, storing password is not widely recommended, collect it use it for authentication and destroy.
You might ideally throw more light on the reason why you want to have access to this information in the module and guys can then suggest methods to accomplish it.
Edited, after Chandan comment:
#Chandan, your comment here suggest to me what you want to do is use httpmodule for your authentication as against using standard form authentication. If I am on track, then you can check this project on codeproject at http://www.codeproject.com/KB/web-security/AspNetCustomAuth.aspx. Goodluck

Is there any way to get the requesting user's ID in an ASP.NET web service method?

I know this probably isn't possible, but I would like to be able to get the Request user ID from within an ASP.NET web service method. So far, I've tried User.Identity.Name, Context.Request.LogonUserIdentity.Name, Request.ServerVariables["AUTH_USER"] and Request.ServerVariables["LOGON_USER"]. Am I tilting at windmills here, or is there something super simple that I'm missing?
Well, what do you mean by User ID?
If they've authenticated via Windows Authentication, User.Identity gives you the WindowsIdentity object that corresponds to that user.
If you want the User ID which corresponds to an authenticated user to "magically" show up in your pages, you can do that too! In your Global.asax, there is a function called Application_AuthenticateRequest which you implement to take whatever identity is passed to your application and turn it into a IPrincipal-based object which can be accessed from your pages.
So when you implement AuthenticateRequest(), you can take the HttpContext.Current.User.Identity.Name, and use that to look up your User ID from your database. From there, you construct your own IPrincipal-derived object and set the HttpContext.Currrent.User reference to that object you create. You can then cast "User" in your pages over to the object you create and read the User ID. We do this all the time. Here's some sample code (which actually caches the Principal object so that you don't have to go to the DB on every request):
protected void Application_AuthenticateRequest(object sender, EventArgs e) {
try {
IIdentity myIdentity = HttpContext.Current.User.Identity;
MyPrincipal myPrincipal = (MyPrincipal)HttpContext.Current.Cache[myIdentity.Name];
if (myPrincipal == null) {
myPrincipal = (MyPrincipal)GetPrincipalFromDatabase(HttpContext.Current.User.Identity);
HttpContext.Current.Cache.Insert(myIdentity.Name, myPrincipal, null, DateTime.Now.AddMinutes(1), TimeSpan.Zero);
}
HttpContext.Current.User = myPrincipal;
}
catch (SecurityException) {
HttpContext.Current.User = null;
}
catch (Exception ex) {
Trace.WriteLine("Could not validate your user.");
}
}

How to set Thread.CurrentPrincipal for use throughout the application?

In an ASP.net application I'm using a Login control with a custom membership provider that I wrote. What I want to do is to set Thread.CurrentPrincipal to my custom Principal object, just after the user is authenticated.
I'm using the setter: Thread.CurrentPrincipal and it sets the Principal object for me but, on all the consequent threads this CurrentPrincipal is overridden with the default one.
Here is my code for the Authenticate event of the Login control:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string username = Login1.UserName;
string password = Login1.Password;
if (Membership.ValidateUser(username, password))
{
var login = sender as Login;
var phoenixIdentity = new PhoenixIdentity("B", "Forms" , true);
var principal = new PhoenixPrincipal(phoenixIdentity);
Thread.CurrentPrincipal = principal;
AppDomain.CurrentDomain.SetThreadPrincipal(principal);
HttpContext.Current.User = principal;
e.Authenticated = true;
}
}
For example, imagine that I login with the username A, everything goes well... Validation passes, but I hardcode the user with the username B in the Identity object which is set to the Principal object I set as the CurrentPrincipal object.
When I check which user is set to the CurrentPrincipal Identity at the end of this method it says it's user B. But when I load another page and then check what the Identity of the CurrentPrincipal is, it says it's user A.
So, how can I make my CurrentPrincipal object to be persistent across all other threads, and where/when does this Login control set the CurrentPrincipal object of the Thread?
Tadas is not wrong, FormsAuthentication correctly implemented will not cause this problem.
Your page is accessible even without login, only in the login page, your thread's principle is set manually by you, but when you hit the other URL, it sure doesnt call your login page and remember each page runs on its own different thread. If you request first page and set thread principle and you request second page in same browser instance, it may or may not be the exact same thread.
This is how FormsAuthentication works,
It checks if Auth Cookie is set or not, it then directs user to login page
Login page must validate and set auth cookie, like FormsAuthentication.SetAuthCookie
Before every page access, Step 1 is executed.
After successful validation of Auth Cookie, ASP.NET internally sets the current user and all differnet parameters according to your membership component.
ASP.NET Global.asax file can give you some events where in you can plugin your code to check just after authentication is successful you can change your current user, remember setting your current principle on login page will not help
We had similar issue when we were using session to store certain important information, after auth sessions were not rebuilt, so we wrote a HTTP Module, and in it's init method, we attached AfterRequestAcquired event and in this event you can write your code to instantiate all your important user related variables.
You can handle FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs e) (in Global.asax) and set CurrentPrincipal here.
void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs e)
{
var phoenixIdentity = new PhoenixIdentity("B", "Forms" , true);
var principal = new PhoenixPrincipal(phoenixIdentity);
e.User = principal;
}
This is what I did in FormsAuthentication_OnAuthenticate method:
if (FormsAuthentication.CookiesSupported)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
FormsAuthenticationTicket ticket =
FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value);
var myIdentity = new GenericIdentity("B");
var principal = new GenericPrincipal(myIdentity, new string[]{"rola1"});
e.User = principal;
}
catch (Exception ex)
{
// Decrypt method failed.
}
}
}
else
{
throw new HttpException("Cookieless Forms Authentication is not " +
"supported for this application.");
}
it seems that it's working what it should do... It's just that if I put my custom principal/identity pair as e.User, then I have serialization problem which I need to fix next... Thank you guys...

Resources