im using mvc3 using asp.net membership database. have created table called business contains userid(from aspnet_users table),businessid , businessname fields.
i know using context.currentuser.....i can username etc.
i need able store businessid somewhere of controllers can access, best way this? dont want make call database everytime businessid based on current user
do create context.session somewhere?
any pointers helpful!
one possibility use session variable. 1 persist information in userdata
part of authentication ticket stored in cookie. write custom principal , authorize attribute read authentication cookie, decrypt ticket , retrieve information.
update:
as requested in comments section here's example of how second approach implemented.
we start defining custom principal:
public class customprincipal : genericprincipal { public customprincipal(iidentity identity, string[] roles, string businessid) : base(identity, roles) { businessid = businessid; } public string businessid { get; private set; } }
then custom authorize attribute:
public class customauthorize : authorizeattribute { protected override bool authorizecore(httpcontextbase httpcontext) { var isauthorized = base.authorizecore(httpcontext); if (isauthorized) { var cookie = httpcontext.request.cookies[formsauthentication.formscookiename]; var ticket = formsauthentication.decrypt(cookie.value); var identity = new genericidentity(ticket.name); var principal = new customprincipal(identity, null, ticket.userdata); httpcontext.user = principal; } return isauthorized; } }
next need modify login action business id included in userdata part of authentication cookie:
[httppost] public actionresult logon(string username, string password) { someusermodel user = fetchuserfromsomewhere(username, password); if (user == null) { // wrong username/password => redisplay login form return view(); } var ticket = new formsauthenticationticket( 1, username, datetime.now, datetime.now.addminutes(formsauthentication.timeout.totalminutes), false, user.businessid // that's store business id ); var encryptedticket = formsauthentication.encrypt(ticket); var cookie = new httpcookie(formsauthentication.formscookiename, encryptedticket) { httponly = true, secure = formsauthentication.requiressl }; response.appendcookie(cookie); return redirecttoaction("index", "somecontroller"); } }
and last part use custom authorize attribute on action:
[customauthorize] public actionresult foo() { var businessid = ((customprincipal)user).businessid; ... }
you write base controller , expose custom principal property avoid casting everytime need access business id.
Comments
Post a Comment