Search code examples
c#asp.netasp.net-web-apiasp.net-identityaccess-token

How to create multiple tokens for different client type in ASP .NET Web API


I am working on an application with Web API and different clients(Mobile app, browser). I want to have different access token for each client type for same user. The reason is, so that the user can sign-out from one device but stays logged in on other devices (similar to how it happens with Facebook).

I know the ASP .Net Identity framework generates single token for a user disregarding the client type. Is there any other framework? Or should it has to be done by storing some client detail in database?


Solution

  • You can create the token manually and at that time you can add claims to the token and give them back to the client. Once clients makes request to the server, you can extract the claim from the token and decide on the device type.

    Create token like below :

    var identity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);
    
    AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
    var currentUtc = new SystemClock().UtcNow;
    identity.AddClaim(new Claim("device_type", "android/ios/web"));
    
    ticket.Properties.IssuedUtc = currentUtc;
    var expiryInterval = int.Parse("20");
    
    var access_token = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
    

    Access token in the request and the claim from token as mentioned below :

    ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;
    var customClaimValue = principal.Claims.Where(c => c.Type == "device_type").Single().Value;
    

    "customClaimValue" must have your device type.