繁体   English   中英

从承载令牌生成身份

[英]Generate Identity from bearer token

有没有办法获取承载令牌字符串并将其手动转换为asp.net中的Identity对象?

干杯,阿齐兹

这是一个相当老的问题,但我认为答案仍然缺失。 我能够通过使用以下行来重新生成主体

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

令牌仅保留声明,并且仅用于对资源进行身份验证。 如果这些声明之一包含用户信息,则可以创建一个身份并将其分配给它。

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;
   }
}

首先,您需要根据令牌创建一些声明,然后创建ClaimsIdentity并使用它来授权用户。

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();
}

现在,您还可以使用“ Authorize过滤器:

[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
}

我也鼓励您从我的github存储库中查看基于令牌的身份验证示例 ,这是一个非常简单的工作示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM