如何获取令牌的claimsidentity或从令牌oauth2获取



我需要一个驱动程序来访问存储在ClaimsIdentity中的某些信息。下面是我的方法GrantResourceOwnerCredentials((。

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
string rol = null;
if (context.Request.Headers.ContainsKey("X-Role"))
{
rol = context.Request.Headers.Get("X-Role");
switch (rol)
{
case "user":
bool isValidCredentials = await //Logica que verifica credenciales.
if (isValidCredentials)
{
//Crea y prepara el objeto ClaimsIdentity
var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
var data = new Dictionary<string, string>
{
{"email", context.UserName}
};
var properties = new AuthenticationProperties(data);
var ticket = new AuthenticationTicket(identity, properties);
context.Validated(ticket);
return;
}
else
{
context.SetError("Invalid user or password.");
return;
}
case "things":
//Logica para autenticar things.
return;
default:
context.SetError("The role is not valid.");
return;
}
}
else
{
context.SetError("The role header is required.");
return;
}
}

控制器dodne的部分代码我需要访问下面的声明

[Route("{email}")]
[Authorize(Roles="user")]
public async Task<Customer> Get([FromUri]  string email)
{
//here I need to obtain the value of the claim that refers to userName associated with this identity.

}

这种行为是如何实现的?我知道至少Role的值正在获得,因为这使得[Authorize(Roles="user"(]工作。

我希望您的控制器类继承自System.Web.Http.ApiController。在这种情况下,您可以通过以下方式访问用户声明。

首先获得ClaimsIdentity:

ClaimsIdentity claimsIdentity = (this.User as ClaimsPrincipal)?.Identities.FirstOrDefault();

var claimsIdentity = this.User?.Identity as ClaimsIdentity;

然后访问声明:

if (claimsIdentity != null)
{
string userName = claimsIdentity.Name;
//or
userName = claimsIdentity.FindFirst(ClaimTypes.Name).Value;
}

最新更新