Getting "null" in Membership.GetUser() and Page.Identity.User - c#

I have implemented the ASPNET membership provider and at the Login1_LoggedIn event, I tried to get Membership.GetUser() or Page.Identity.User but both of them returned null.
I tried different solutions suggested by others including changing form path="/" but have no luck. However the LoginName control works and showing the username correctly.
Does anyone has an idea why?

Try to disable non-authenticated users in web.config:
<authorization>
<deny users="?" />
</authorization>
the HttpContext.Current.User will not pupulated until you call :
FormsAuthentication.SetAuthCookie(UserName, False)
or
FormsAuthentication.RedirectFromLoginPage(UserName, False)

I have found out why, ScottGu has explained it well in his blog post.
http://forums.asp.net/t/982749.aspx

Related

User.Identity.Name = "" (anonymous) but Windows auth is enabled?

I created an ASP.NET MVC app with the following override via a custom AuthorizeAttribute implementation:
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return base.AuthorizeCore(httpContext);
}
However, within this method, httpContext.User.Identity.Name is "". I need to get a handle to the current Identity.Name so I can retrieve some data based on that value. I have the following entries in web.config:
<authentication mode="Windows" />
<authorization>
<deny users="?"/>
</authorization>
At minimum, I think that the MVC site should prompt me for credentials with the configuration above, right?
I was able to get the network user ID with the following alternate code:
Request.LogonUserIdentity.Name
Are there any implications or impacts of using this code as opposed to:
httpContext.User.Identity.Name

Response is not Available in this context Global.asax

I'm checking user is authorized already or not in global.asax if true then redirect to some route
if (false)
{
HttpContext.Current.Response.RedirectToRoute("Login");
}
It throws exeption :
Response is not available in this context
I think it would be a better solution to make use of the authentication tag in the web.config.
// or loginUrl="~/Account/LogOn" for example in an MVC application
<authentication mode="Windows">
<forms
name=".ASPXAUTH"
loginUrl="login.aspx"
defaultUrl="default.aspx"
protection="All"
timeout="30"
path="/"
requireSSL="false"
slidingExpiration="true"
cookieless="UseDeviceProfile" domain=""
enableCrossAppRedirects="false">
<credentials passwordFormat="SHA1" />
</forms>
<passport redirectUrl="internal" />
</authentication>
You can define a loginUrl where the user will be redirected in case the user tries to access a ressource which requires authentication.
Update
According to your given comment I think you may be looking for an authorization based routing. There is already an answer for that in this SO Question MVC role-based routing.
As far as I know, ASP.NET creates HttpContext object together with HttpRequest and HttpResponse objects. It happens before creation of the HttpApplication instance.
So it seems that HttpContext.Current just doesn't work at this stage.
Inside application event's handlers you can get the context throw the sender:
private void OnAuthorizeRequest(object sender, EventArgs e)
{
var application = (HttpApplication)sender;
var context = (HttpContext)application.Context;
}
(AuthorizeRequest is a right place to redirect anonymous users, cause previous AuthenticateRequest has authenticated or hasn't authenticated the user already.)
See details here.
It's important: the neighbor answer is absolutely correct, and you should use web.config to make this thing. My answer about "how it works", and "how it could be done".

User roles from custom database in ASP.NET

I'm creating an app with ASP.NET WebForms. I have custom database with users table. It contains name and role. How can I add roles from DB to website? I want to use something like this:
<location path="path">
<system.web>
<authorization>
<allow roles="role"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
where role should be imported.
Thank you!
You can implement a custom RoleProvider.
As a minimum you need to implement Intialize (of course) and the methods GetRolesForUser and IsUserInRole. The other methods are only needed if you want to be able to administer roles through the RoleProvider.
IsUserInRole can often be implemented as something close to:
public bool IsUserInRole(string username, string roleName)
{
return GetRolesForUser(username).Contains(roleName);
}
so apart from initialization, which in your case will probably only be storing a database connection string, you only have one simple method to implement.

mvc WebSecurity.CurrentUserName empty and CurrentUserID -1 after user logged in

Below is the code used to login
WebSecurity.Login("abc", "123", true);//return true
return RedirectToAction("afterLogin", #"afterLogin");
After loggin in, I checked the user's id to see if it's -1 by running the below line:
WebSecurity.CurrentUserId
But why whenever I called this, the return value always -1 and CurrentUserName is empty?
edited:
An additional question:
Does the WebSecurity have something like timeout so that the user idle for a specific period and will logged out automatically?
Check your webconfig, you have to enable forms authentication:
Add following snippet inside
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="3600" />
</authentication>
Comment out if it is in your webconfig:
<!--<modules>
<remove name="FormsAuthentication" />
</modules>-->
Now you can check
WebSecurity.CurrentUserName, WebSecurity.CurrentUserId and , WebSecurity.IsAuthenticated flags;
Also add this class in app_start
public static class AuthConfig
{
public static void RegisterAuth()
{
}
}
and call this in AppStart in Global.asax.cs
AuthConfig.RegisterAuth();
I think the default expiration is when the browser session ends. It might be that cookies are not enabled and that's why it is returning -1 cookies need to be enabled.

how to redirect to root file in asp.net?

My loging page in root/Account/Login.aspx page when I click on contact us i need to redirect to root/contactus.aspx page.
I used Response.Redirect("~/contactus.aspx") in Master page (Site.Master)
Protected Sub lbContactUs_Click(sender As Object, e As EventArgs) Handles lbContactUs.Click
Response.Redirect("~/contactus.aspx")
End Sub
Still it is not redirecting to page.
You are not redirecting properly.
Response.Redirect("/contactus.aspx", False);
Context.ApplicationInstance.CompleteRequest();
Do not use Response.Redirect(url). It calls Response.End which is very taxing on the server.
Response.Redirect(url, false) is much faster and more efficient.
Response.End will raise a ThreadAbortException which costs a lot for the server to do.
http://blogs.msdn.com/b/tmarq/archive/2009/06/25/correct-use-of-system-web-httpresponse-redirect.aspx
#Jason Kulatunga's answer looks like it will solve your problem. The above information is just for good practice.
Add the following to your web.config
<configuration>
...
<location path="ContactUs.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
...
</configuration>
It seems that you have a deny all anonymous users rule set in your web.config. If you need to allow anonymous users access to specific pages, while still leaving the rest of your site protected by forms authentication, you can use the location tag to override the security for specific pages.
#James123: Use
Protected Sub lbContactUs_Click(sender As Object, e As EventArgs) Handles lbContactUs.Click
Response.Redirect("/contactus.aspx")
End Sub
this will redirect to root directory

Categories

Resources