ASP.NET MVC Custom User Fields on Each Page

Background: I am creating more and more web applications where developers / template developers decide that adding a “profile picture” and some other user-related data, of course, only when someone logs in.

Like most ASP.NET MVC developers, I use viewmodels to provide razor layouts with the information I need to show, obtained from repositories, etc.

Easily show username with

HttpContext.Current.User.Identity.Name

What if I want to show the information stored in my data warehouse on these pages? Custom fields in the ApplicationUser class, such as the name of the business unit or the URL of the CDN profile.

(for simplicity, suppose I'm using the Identity Framework with an Entity Framework database (SQL database) containing my ApplicationUsers)

Question

How do you solve this:

  • Without assuming a viewmodel / controller tree (e.g. creating a BaseViewModel or BaseController populating / providing this information?
  • Without the need to round off the database every page request for these details?
  • Without querying the database if the user is not logged in?
  • If you can't use SESSION data (since my applications often scale across multiple Azure instances - read why this is not possible here - I'm not interested in SQL caching or Redis caching.

, , SQL pageload. , . , ?

TL;DR;

(ApplicationUser) , (anon access = allowed). ? Session? ?

+4
4

Identity - . , . .

ApplicationUser GenerateUserIdentityAsync, ClaimsIdentity :

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, string> manager)
{
    // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
    var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

   // Add custom user claims here
   userIdentity.AddClaims(new[]
   {
       new Claim("MyApp:FirstName",this.FirstName), //presuming FirstName is part of ApplicationUser class
       new Claim("MyApp:LastName",this.LastName),
   });

   return userIdentity;
}

- , cookie - .

HttpContext.Current.User.Identity - ClaimsIdentity , cookie. , , , , .

, IPrincipal

public static String GetFirstName(this IPrincipal principal)
{
    var claimsPrincipal = principal as ClaimsPrincipal;
    if (claimsPrincipal == null)
    {
        throw new DomainException("User is not authenticated");
    }

    var personNameClaim = claimsPrincipal.Claims.FirstOrDefault(c => c.Type == "MyApp:FirstName");
    if (personNameClaim != null)
    {
        return personNameClaim.Value;
    }

    return String.Empty;
}

Razor: User.GetFirstName()

, - DI .

, , cookie cookie , - . IAuehtenticationManager.Signout() .

+4

. . , Identity, ApplicationUser.GenerateUserIdentityAsync():

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, string> manager)
{
    // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
    var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

   // Add custom user claims here
   userIdentity.AddClaims(new[]
   {
       new Claim("MyValueName1","value1"),
       new Claim("MyValueName2","value2"),
       new Claim("MyValueName2","value3"),
       // and so on
   });

   return userIdentity;
}

, . HttpContext.Current.User.Identity.Name .

public ActionResult MyAction()
{
     // you have access the authenticated user claims 
     // simply by casting User.Identity to ClaimsIdentity
     var claims = ((ClaimsIdentity)User.Identity).Claims;
     // or 
     var claims2 = ((ClaimsIdentity)HttpContext.Current.User.Identity).Claims;
} 
+2

, "" , , , , , , HttpContext. ApplicationContext , DI. ( , , - DI.)

public interface IApplicationContext
{
    //Interface
    string GetUsername();
}

public class ApplicationContext : IApplicationContext
{
    public static IApplicationContext Current
    {
        get
        {
            return DependencyResolver.Current.GetService<IApplicationContext>();
        }
    }


    //appropriate functions to get required data
    public string GetUsername() {
        if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
            return HttpContext.Current.User.Identity.Name;
        }
        return null;
    }
}

"" .

@ApplicationContext.Current.GetUsername()

, # 2. , , , , .

+1

ChildAction loggedin

0

All Articles