c# - MVC FormsAuthentication IsInRole in View not working -
i authenticating user:
[route("login"), httppost, allowanonymous] public loginviewmodelresponse login(loginviewmodelrequest data) { if(!membership.validateuser(data.username, data.password)) { return new loginviewmodelresponse { displaymessage = "invalid username/password!", issuccess = false, redirecturl = "/home/" }; } formsauthentication.setauthcookie(data.username, false); claimsidentity identity = new genericidentity(data.username); var roles = "administrator,user".split(','); // var client = authorisationservice.instance.getauthenticateduser();// new clientservice().getclientbyid(1); var principle = new genericprincipal(identity, roles); httpcontext.current.user = principle; system.threading.thread.currentprincipal = principle; if (user.isinrole("administrator")) { var b = 1; } return new loginviewmodelresponse { issuccess = true, displaymessage = "ok", redirecturl = "/home/" }; }
and test 'isinrole' working.
however, have following in view (_layout), , check administrator fails.
if (viewcontext.httpcontext.user.isinrole("administrator")) { <li class="dropdown"> ...
is there need allow view understand "isinrole"?
this works:
@if (viewcontext.httpcontext.user.identity.isauthenticated == false)
but 'isinrole' evaluated false.
since set formsauthentication cookie yourself, you'll need create principle object , assign current thread on every request inside authenticaterequest event.
global.asax.cs
public class global : httpapplication { protected void application_authenticaterequest(object sender, eventargs e) { httpcookie decryptedcookie = context.request.cookies[formsauthentication.formscookiename]; if (decryptedcookie != null) { formsauthenticationticket ticket = formsauthentication.decrypt(decryptedcookie.value); var identity = new genericidentity(ticket.name); var roles = ticket.userdata.split(','); var principal = new genericprincipal(identity, roles); httpcontext.current.user = principal; thread.currentprincipal = httpcontext.current.user; } } }
sign-in method
public void signin(string username, bool createpersistentcookie) { var = datetime.utcnow.tolocaltime(); timespan expirationtimespan = formsauthentication.timeout; var ticket = new formsauthenticationticket( 1 /*version*/, username, now, now.add(expirationtimespan), createpersistentcookie, "" /*userdata*/, formsauthentication.formscookiepath); var encryptedticket = formsauthentication.encrypt(ticket); var cookie = new httpcookie(formsauthentication.formscookiename, encryptedticket) { httponly = true, secure = formsauthentication.requiressl, path = formsauthentication.formscookiepath }; if (ticket.ispersistent) { cookie.expires = ticket.expiration; } if (formsauthentication.cookiedomain != null) { cookie.domain = formsauthentication.cookiedomain; } response.cookies.add(cookie); }
Comments
Post a Comment