C# 从承载令牌生成标识
是否有方法在asp.net中获取承载令牌字符串并将其手动转换为C# 从承载令牌生成标识,c#,asp.net,asp.net-web-api,asp.net-identity,asp.net-web-api2,C#,Asp.net,Asp.net Web Api,Asp.net Identity,Asp.net Web Api2,是否有方法在asp.net中获取承载令牌字符串并将其手动转换为Identity对象 干杯, Aziz令牌只保存声明,它只用于对资源进行身份验证。如果其中一个声明包含用户信息,您可以创建一个标识并将声明分配给它 public void ValidateBearerToken(OwinContext context) { try { var tokenHandler = new JwtSecurityTokenHandler(); byte[] secur
Identity
对象
干杯,
Aziz令牌只保存声明,它只用于对资源进行身份验证。如果其中一个声明包含用户信息,您可以创建一个标识并将声明分配给它
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回购协议作为一个非常简单的工作示例。这是一个非常古老的问题,但我认为仍然缺少答案。我可以使用下面的行重新生成Principal
var ticket = Startup.OAuthOptions.AccessTokenFormat.Unprotect(accessToken);
var identity = ticket.Identity;
你能再解释一下吗?你怎么拿不记名代币?通过简单的post或get方法?您想通过该令牌授权调用方吗?@SamFarajpourGhamari我有一个标记,因此它将是一个GET端点,我想授权该用户是他们所声称的用户。您可以对此进行扩展吗?如何从字符串(原始令牌)提取信息。这将验证您的令牌并设置声明原则。然后您只需将声明添加到pricinple.claims列表中。我使用的是SimpleAuthorizationServerProvider:OAuthAuthorizationServerProvider,而不是Jwt安全令牌没有_myUserManager.GetUserRoles(令牌);。。。方法。我正在使用公共类SimpleAuthorizationServerProvider:OAuthAuthorizationServerProvider-这有帮助吗?
\u myUserManager
就是一个例子。演示如何使用自己的类生成声明并基于用户登录。在本例中,我使用\u myUserManager
提取当前用户角色,您可以实现自己的类。用户名和角色只是简单的字符串。如果没有用户名或角色,则为可选。如果你看看我的github repo,你会发现我是如何只用一个字符串来授权用户的。我没有当前的用户上下文。我需要从字符串标记转到用户。我需要知道locic如何在_myUserManager.GetUserRoles(令牌)中运行;那么,如何存储用户数据呢?以分贝为单位?您的用户有角色吗?我使用默认的aspnet_用户表。但是,令牌生成由Microsoft.Owin.Security.OAuth处理;努吉。令牌不存储在db中,因此我不能将引用拉到用户。