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

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.

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

If user is not authenticated go to login page

task: If user is not authenticated go to login page!
I want this behavior in every action of every controller.
But offcourse I do not want to have logic in every action for this
if (User == null || User.Identity == null || !User.Identity.IsAuthenticated)
{
return RedirectToAction("Index","Authentication");
}
What is good practive for this?
I added to web config:
<authentication mode="Forms">
<forms loginUrl="~/Authentication" timeout="2880"/>
</authentication>
Controllers have attribute [authorize], except AuthenticationController where I have[AllowAnonymous]
But still not redirect to login page (just show error: HTTP Error 401.0 - Unauthorized)
Edit2:
Solved!
I had
<remove name="FormsAuthentication" />
in web.cofig
When I remove this line everything was fine
you should define membership provider or something provides Identity for your system. Then you should use Authorize attribute for your controller.
Authorize attiribute redirects action to login view if user is not authenticated.

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".

ASP.NET MVC custom role provider not working

I have setup a custom role provider implemented using the code below except it seems it's never being used, and the default provider is being used instead. When decorating the HomeController with the [Authorize(Roles = "Administrator")] attribute the CustomRoleProvider constructor is being called (I only included the constructor in to see whether the breakpoint would be hit) but none of the methods are being called. And then I am left with a HTTP Error 401.0 - Unauthorized page.
Aside from adding the necessary bits to the web.config I haven't done anything else to get Windows authentication to work. I assume it's working though because if I don't include <allow users="*"></allow> (obviously without the inclusion of the Authorize attribute) I get a 401.2.: Unauthorized: Logon failed due to server configuration error, so I assume I'm being authenticated.
I've cleared my browser cookies as per this SO post but that had no effect.
CustomerRoleProvider
public class CustomRoleProvider : RoleProvider
{
public CustomRoleProvider()
{
}
public override bool IsUserInRole(string username, string roleName)
{
bool isUserInRole = false;
// omitted for brevity
return isUserInRole;
}
public override string[] GetRolesForUser(string username)
{
string[] roles = null;
// omitted for brevity
return roles;
}
// omitted for brevity
}
web.config
<authentication mode="Windows">
</authentication>
<authorization>
<allow users="*"></allow>
<deny users="?"/>
</authorization>
<roleManager defaultProvider="CustomRoleProvider" enabled="true">
<providers>
<clear />
<add name="CustomRoleProvider" type="ProjectName.UI.Mvc.Code.Providers.CustomRoleProvider" />
</providers>
</roleManager>
Home Controller
[Authorize(Roles = "Administrator")]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
This was caused from not having IIS Express set to use Windows Authentication. To fix I selected the project in Solution Explorer, opened the Properties window set Windows Authentication = Enabled and Anonymous Authentication = Disabled. Custom role provider now works.

Forms authentication problems when migrating asp.net from WebForms to MVC

I am upgrading my project from asp.net web forms to MVC4, step by step. In the first step I changed the login page and few other pages. I am using forms authentication, with my own logic (no membership) - I check the username/password against a database table. If it is OK the user is redirected to its destination.
My login code is:
Web.config:
<authentication mode="Forms">
<forms loginUrl="~/LogIn" name=".ASPXFORMSAUTH" timeout="150" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
Login Controller:
[AllowAnonymous]
[HttpPost]
public ActionResult AjaxLogin(FormCollection postedFormData)
{
try
{
string userName = postedFormData["Login_UserName"];
string password = postedFormData["Login_Password"];
UserEntity userEntity = new UserEntity(Utilities.AuthenticateUser(userName, password, 1));
Session["UserEntity"] = userEntity;
FormsAuthentication.SetAuthCookie(userEntity.Key.Id.ToString(), false);
return Json(new { redirectToUrl = "./AccountSelection", error = "false", lan = Thread.CurrentThread.CurrentUICulture.ToString() });
}
catch (Exception ex)
{
return Json(new { redirectToUrl = "", error = ExceptionHandler.HandleException(ex), lan = Thread.CurrentThread.CurrentUICulture.ToString() });
}
}
When I try to login I get http 302 and redirected back to login.
If I remove the "authorization" section on web.config it will work fine, but now I have two problems:
I have to put [authorize] attribute on every controller
My webforms will not be inside forms authentication (can be accessed directly with no login!!)
What am I doing wrong?
If you're defining your authorization in web.config, you don't need an AllowAnonymousAttribute.
Having said that, you don't appear to be adding AjaxLogin to your authorization list. This is necessary, because the Ajax request will otherwise be blocked. You need both ~/Login and ~/Account/AjaxLogin paths. You may also need a ~/Account/Login path, but i'm not certain of that.

Categories

Resources