Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you extend HttpContext.Current.User.Identity properties

Is there a way to override HttpContext.Current.User.Identity to add another property (screen name)?

My application uses Identity and I've left the unique identity as email. I store user data such as first / last name in a separate "Profile" table. Is there a way to store this information somewhere within HttpContext.Current?

It doesn't necessarily need to be within User. I have had a search and noticed there's a HttpContext.Current.ProfileBase. Not sure how to use it though - and I really don't want all the excess stuff that base comes with.

like image 512
Fred Johnson Avatar asked Aug 12 '15 19:08

Fred Johnson


People also ask

What is HttpContext current user identity?

It just holds the username of the user that is currently logged in. After login successful authentication, the username is automatically stored by login authentication system to "HttpContext.Current.User.Identity.Name" property.

How do you set HttpContext user identity for an application manually?

You can achieve this by manually settings HttpContext. User: var identity = new ClaimsIdentity("Custom"); HttpContext. User = new ClaimsPrincipal(identity);

How does HttpContext current work?

The HttpContext encapsulates all the HTTP-specific information about a single HTTP request. When an HTTP request arrives at the server, the server processes the request and builds an HttpContext object. This object represents the request which your application code can use to create the response.

Why is user identity IsAuthenticated false?

identity. isauthenticated is False when a user is already logged in.


1 Answers

You can put value in HttpContext.Current.Items. It is dictionary which lifetime is single request.

You can use it like this:

public static string CurrentScreenName
{
    get
    {
        string screenName = (string)HttpContext.Current.Items["CurrentScreenName"];

        if (string.NullOrEmpty(screenName))
        {
             screenName = ResolveScreenName();
             HttpContext.Current.Items["CurrentScreenName"] = screenName;
        }
        return screenName;
    }
}

It will execute ResolveScreenName() only once for single request.

Also you can make extension method to access screen name from IIdentity

public static class Extensions
{
    public static string GetScreenName(this IIdentity identity)
    {
        return CurrentScreenName;
    }
}

And then use it like this:

string screenName = HttpContext.Current.User.Identity.GetScreenName();
like image 107
Piotr Dory Avatar answered Sep 21 '22 05:09

Piotr Dory