Aziz
Aziz

Reputation: 1614

Generate Identity from bearer token

Is there a way to take a Bearer Token string and convert it to the Identity object manually in asp.net?

Cheers, Aziz

Upvotes: 3

Views: 7561

Answers (3)

Riaz Raza
Riaz Raza

Reputation: 382

This is a pretty old question, but I think answer was still missing. I was able to regenerate Principal by using the following line

var ticket = Startup.OAuthOptions.AccessTokenFormat.Unprotect(accessToken);
var identity = ticket.Identity;

Upvotes: 2

Stephen Brickner
Stephen Brickner

Reputation: 2602

The token just holds claims and it's just used for authentication into the resource. If one of those claims held user information you could create an identity and assign the claims to it.

public void ValidateBearerToken(OwinContext context)
{
    try
    {
       var tokenHandler = new JwtSecurityTokenHandler();
       byte[] securityKey = GetBytes("some key"); //this should come from a config file

       SecurityToken securityToken;

       var validationParameters = new TokenValidationParameters()
       {
          ValidAudience = "http://localhost:2000", 
          IssuerSigningToken = new BinarySecretSecurityToken(securityKey),
          ValidIssuer = "Self"
       };

       var auth = context.Request.Headers["Authorization"];

       if (!string.IsNullOrWhiteSpace(auth) && auth.Contains("Bearer"))
       {
          var token = auth.Split(' ')[1];

          var principal = tokenHandler.ValidateToken(token, validationParameters, out securityToken);

          context.Request.User = principal;
       }
   }
   catch (Exception ex)
   {
       var message = ex.Message;
   }
}

Upvotes: 1

Sam FarajpourGhamari
Sam FarajpourGhamari

Reputation: 14741

First you need to crate some claims based on token then create ClaimsIdentity and use it to authorize the user.

public ActionResoult Login(string token)
{
    if(_tokenManager.IsValid(token))         
    {
        // optionally you have own user manager which returns roles and user name from token
        // no matter how you store users and roles
        var user=_myUserManager.GetUserRoles(token);

        // user is valid, going to authenticate user for my App
        var ident = new ClaimsIdentity(
            new[] 
            {  
                // adding following 2 claim just for supporting default antiforgery provider
                new Claim(ClaimTypes.NameIdentifier, token),
                new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),

                // an optional claim you could omit this 
                new Claim(ClaimTypes.Name, user.Username),

                // populate assigned user's role form your DB 
                // and add each one as a claim  
                new Claim(ClaimTypes.Role, user.Roles[0]),
                new Claim(ClaimTypes.Role, user.Roles[1]),
                // and so on
            },
            DefaultAuthenticationTypes.ApplicationCookie);

        // Identity is sign in user based on claim don't matter 
        // how you generated it             
        HttpContext.GetOwinContext().Authentication.SignIn(
            new AuthenticationProperties { IsPersistent = false }, ident);

        // auth is succeed, just from a token
        return RedirectToAction("MyAction"); 
    }
    // invalid user        
    ModelState.AddModelError("", "We could not authorize you :(");
    return View();
}

Now you could use Authorize filter as well:

[Authorize]
public ActionResult Foo()
{
}

// since we injected user roles to Identity we could do this as well
[Authorize(Roles="admin")]
public ActionResult Foo()
{
    // since we injected our authentication mechanism to Identity pipeline 
    // we have access current user principal by calling also
    // HttpContext.User
}

Also I encourage you to have look Token Based Authentication Sample from my github repo as a very simple working example.

Upvotes: 1

Related Questions