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".
Related
I am working with ASP.NET MVC 4 (NET Framework 4.0)
For a reason I do not understand, my user remains logged-in even after the browser or/and application restart. To take this further, even after a total computer restart, which means the authentification cookie/ticket is persisting.
I do not want to use cookieless attribute in my Web.config as I do not want to have the cookie stored in the URL for security and SEO issues.
I don't understand why is this happening, I have set the authentification cookie not to persist in the FormsAuthentication.SetAuthCookie() method.
This is my login action, isValid(username, password) is a custom method that checks if the username and password match in the model.
db is my database context.
[AllowAnonymous]
[HttpPost]
public ActionResult LogIn(Employe user)
{
if (ModelState.IsValid)
{
if (IsValid(user.username, user.password))
{
FormsAuthentication.SetAuthCookie(user.username, false);
Employe currentEmp = db.Employes.SingleOrDefault(emp => emp.username == user.username);
Session["currentUser"] = currentEmp;
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Login Data Incorrect!");
}
}
return View();
}
This is my Web.config
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" protection="All" timeout="2880" />
</authentication>
If you are using Form Authentication mode, there is a situation to control both Form Authentication expiration and Custom Session expiration. That would probably make your application happen the issue.
Hope you would find the solution here How can I handle forms authentication timeout exceptions in ASP.NET?
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
I am getting this error all the time. Can't figure out what the problem is. I tried clearing my cookies / the entire browsing history still no luck.
In my index.aspx i have the code below on page_load
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated == true)
{
Response.Redirect(FormsAuthentication.DefaultUrl, true);
}
}
In the web config I have this :
<authentication mode="Forms">
<forms cookieless="UseCookies" defaultUrl="app_files/home.aspx" loginUrl="index.aspx" name="osivms" path="/" protection="All" requireSSL="true" slidingExpiration="true" timeout="525600" />
</authentication>
Sometimes It does work though.. but its really random and I dont know what changed when it works.. then after I hit refresh or something I get the same error message again...
This issue was fixed. I followed the instructions on this page and my localhost is back working now.
I had to delete the old certificate and create a self signed new certificate and bind it to the site.
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.
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.