I have written a custom AuthorizeAttribute which has the following condition in asp.net mvc3 application:
public override void OnAuthorization(AuthorizationContext filterContext)
{
//auth failed, redirect to Sign In
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
And in my web.config, i have:
<authentication mode="Forms">
<forms loginUrl="~/User/SignIn" timeout="2880" />
</authentication>
On authentication fail, it redirects to "/Account/Login" page by default.
How do i change this default redirect url and redirect it to "/User/SignIn"?
The screenshot shows the clear view of what i am trying to say..
Though i have set '/User/SignIn', it redirects to '/Account/Login'
I am not sure whether i can add this as an answer. But this may help others who were having this related issue.
I got the solution after a struggle. I have added WebMatrix.WebData reference recently, which seems to be the real culprit of this issue. This can be handled by adding the key to your config file:
<add key="loginUrl" value="~/User/SignIn" />
You should be modifying the root one for loginUrl.
i have created AuthorizationAttribute... it's redirecting properly
e.g.
<authentication mode="Forms">
<forms loginUrl="~/Authenticate/SignIn" timeout="2880"/>
</authentication>
and my attribute is:
public class AuthorizationAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
}
and apply attribute to any method of your controller as necessary...
[AuthorizationAttribute()]
public ActionResult Index()
{
return View();
}
I recently had this problem and found it was because I had the WebMatrix.dll referenced in my project.
Removing this DLL fixed the issue
see here
What is the PreserveLoginUrl appSetting key/value in an ASP.NET MVC application?
Related
I have already read many topics about it but i can't find a solution.
I'm working on asp.net mvc 5 application with an admin area.
I have created a filter inherits from ActionFilterAttribute and i have added it as attribute on my controller.
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var errorResult = new RedirectToRouteResult(new RouteValueDictionary
{
{ "controller", "Login" },
{ "action", "Index" },
});
if (!filterContext.HttpContext.Request.IsAuthenticated)
{
filterContext.Result = errorResult;
}
base.OnActionExecuting(filterContext);
}
LoginController uses AllowAnonymous attribute.
I tried to login but then the request is not authenticated (i see it in debug mode). I need to edit web.config.
If i add the following code in root web.config:
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Admin/Login" timeout="2880" />
</authentication>
</system.web>
it works but my application has not any login, only admin area has.
What is the solution?
I can't write this code in web.config area.
Thanks in advance.
When user open my site, he sees login page (mentioned in routeConfig). But if he tries to access register page (or any other but it's normal), he still be redirected to login page. Both actions are [AllowAnonimus]. In my web config i have such a paragraph
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<authorization>
<deny users="?"/>
</authorization>
I wish I could transfer to register page but not to others and I don't want to put [Authorize] to all actions.
[AllowAnonymous]
public class LoginController : Controller {}
Also you dont really need authentication mode = forms.
Add to webconfig:
<authentication mode="None">
</authentication>
And use your RouteConfig.cs
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional }
);
Also use the global authentication filters:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizeAttribute());
}
}
This will allow [AllowAnonymous] to work all your controllers will need authorization or you can add authorization to just methods if needed.
[AllowAnonymous]
public ActionResult Test() {}
Should mention if you dont want to add [AllowAnonymous] just leave the controller or method be.
I'm having an issue with my ASP.NET MVC 5 simple membership provider login code. The code is as follows:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
bool active = true;
if (ModelState.IsValid && WebSecurity.Login(model.Email, model.Password, persistCookie: model.RememberMe))
{
UserDetail userModel = UserDetail.Initialize(model.Email);
FormsAuthentication.SetAuthCookie(model.Email, true);
active = userModel.ActiveBit;
if (active)
{
return Redirect("~/");
}
else
{
WebSecurity.Logout();
ModelState.AddModelError("", "Account is inactive.");
}
}
else
{
ModelState.AddModelError("", "*Either the Username or Password provided is incorrect.");
}
return View(model);
}
The login processes successfully and I can see the authentication cookie (.ASPXAUTH) in the browser. The problem arises on the next page request. The authentication cookie is passed back to the server, but the server seems to have no record of the login any more. When I set a breakpoint and check after processing the login and requesting a new page (after completing the post-login redirect), User.Identity.IsAuthenticated is false as is WebSecurity.IsAuthenticated and WebSecurity.HasUserID. WebSecurity.CurrentUserId is -1 and WebSecurity.CurrentUserName is an empty string.
It's not a database connectivity issue since I do authenticate successfully. I do a roundtrip to the server and back and I am still not authenticated so the common answers I've seen for CurrentUser == -1 don't seem to apply.
I'm a relative newbie on MVC but I had a coworker who's got a decent amount experience on this look at my code and he couldn't find anything either. Thanks for your help.
By default asp.net MVC5 web.config not supporting FormsAuthentication, check below section of your web config file and remove "<remove name="FormsAuthentication" />" if you want to use FormsAuthentication.
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
Authentication timeout configuration
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
</system.web>
Hope this helps.
I'm very new to .NET and security. I've chosen to implement Forms authentication (correct me if I should use something else). From what I gathered on the internet, I did the following, but it's not working:
Web.config
<authentication mode="Forms">
<forms loginUrl="~/Home/Index" timeout="30" />
</authentication>
HTTPPost ajax Login method:
[HttpPost]
public ActionResult Login(LoginInputModel loginModel)
{
if (ModelState.IsValid)
{
var success = UserService.Login(loginModel.Password, loginModel.Email);
if (success)
{
return Json(new { Url = Url.Action("Index","Home") });
}
loginModel.ErrorMessages = "Failed to log in with these credentials. Please try again.";
return PartialView("Widgets/Login/_LoginInput", loginModel);
}
return PartialView("Widgets/Login/_LoginInput", loginModel);
}
With actual login code in UserService class:
public static bool Login(string password, string email)
{
var user = Connector.GetUserByCredentials(password, email);
if (user == null) return false;
FormsAuthentication.SetAuthCookie(email, false); // this line
SessionService.Delete(UserSessionKey);
SessionService.Store(UserSessionKey, UserMapper.DbUserToUser(user));
return SessionService.HasKey(UserSessionKey);
}
Whenever I hit login, it works okay (it refreshes the page and I see different content), but if I then navigate to another page, I get redirected to the login page again. What am I (not) doing wrong?
If you need more code, I'll be happy to post it.
When you say you're using MVC5, what version of Visual Studio are you using? Are you using an application that was originally created by a default wizard?
If the application was created by the default wizard, then by default it enables ASP.NET Identity, and it removes the FormsAuthentication module from processing. If you want to keep using FormsAuth then you have to remove the "remove" key from the web.config for the FormsAuthentication module.
You need to remove this line
<system.webServer>
<modules>
<remove name="FormsAuthentication" /> <----****
</modules>
</system.webServer>
I've implmented an service using MVC WEB API and i implemented a custom way to authenticate the requests. this is how it looks like:
public HttpResponseMessage GetTest()
{
try
{
IDBModel DAO = new DBModelDAO();
if (DAO.IsApiKeyValid(Request.Headers.Authorization.Parameter))
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
catch (Exception e)
{
System.Diagnostics.Trace.WriteLine(e.Message);
}
return new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
However if the authentication fails i get redirected to this uri:
/Account/Login?ReturnUrl=%2ftest
And i don't want that because i don't use the webbrowser for authenticating.
How can i disable this feature?
Your help is very much appreciated!
Zoli
The part:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
has to be commented and it won't redirect