c# - MVC 4 Forms Authentication not working with [Authorize] -
i'm learning mvc4 right now, , following pro asp net mvc4 4th edition book create sports store project.
i have developed in webforms, , trying figure out how forms authentication working in mvc4.
here have achieved:
web.config
<authentication mode="forms"> <forms loginurl="~/account/login" timeout="2880"/> </authentication>
accountcontroller login action:
[httppost] public actionresult login(loginviewmodel model, string returnurl) { if (modelstate.isvalid) { if (authprovider.authenticate(model.username, model.password)) { return redirect(returnurl ?? url.action("index", "admin")); } else { modelstate.addmodelerror("", "incorrect username or password"); return view(); } } else { return view(); } }
auth provider:
public bool authenticate(string username, string password) { bool result = formsauthentication.authenticate(username, password); if (result) { formsauthentication.setauthcookie(username, false); } return result; }
i setting authcookie , know, how protect other controllers , actions out of accountcontroller
the application has controller called admincontroller, can edit products , the
product list in under following {controller/action}
admin/index
so, if not missunderstanding theory, if user not logging in accountcontroller should not able call actions [authorize] tag on declaration:
public class admincontroller : controller { private iproductrepository repository; public admincontroller(iproductrepository repo) { repository = repo; } [authorize] public actionresult index() { return view(repository.products); } }
the thing can call index action of admin controller without problem , without introducing login.
i need guidance understand how works. have done research , not find anything, , book not covering topic.
thanks in advance.
edit: closed chrome browser , worked without changing anything. working tabs , guess cookie active stopping , starting debugging.
if controller action decorated [authorize]
attribute (as admin/index
action) cannot invoke action if not have valid forms authentication cookie in request.
also in login
action, upon successful authentication should not return view should redirect away, cookie set , available on subsequent requests.
here's should happen when non-authenticated user attempts access protected admin/index
action. [authorize]
attribute throw 401 exception, know classic webforms intercepted forms authentication module , redirected loginurl
configured in web.config passing returnurl query string parameter requested protected resource.
so must have login
action on account controller not decorated [httppost]
attribute , should serve view containing sign-in view. request this:
/account/login?returnurl=%2fadmin%2findex
Comments
Post a Comment