Lars Holdgaard Lars Holdgaard - 1 year ago 70
reST (reStructuredText) Question

How to set a global variable after authentication in a Web API?

I have my web API which uses OAUTH authentication. This means that all calls to the API includes a token which is a user of some sort.

Now, what I want to do - is to set a global variable depending on the token. In practice, I have a range of users and depending on the user, I want to apply different "profiles". That means in my service layer, I want to be able to access a call such as:


And when I receive the API call with the token, I want to set this global value.

The flow I had in mind was:

  1. API receives a call

  2. In some filter (I guess?) we find out which user it is, and then depending on the user, we find the correct profile

  3. We set some global variable depending on the result

  4. Services can use this

My question is:

Is this the correct approach? And how would you set some "global setting" depending on the token/user you receive a call from?

Answer Source

As the token is used to authorize the user you can add the profile details as claims to the user principle which should be associated with the request once successfully authenticated/authorized anyway.

const string SendEmails = "ProfileSettings.Notification.SendEmails"

// IPrincipal being set

if (identity != null && identity.IsAuthenticated) {
    ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
    if (claimsIdentity != null) {
        var claim = new Claim(SendEmails, "{set value based on user}");

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download