JWT 如何添加自定义声明和解码声明
JWT How to add custom claims and decode claims
我正在尝试检索我在创建令牌时所做的一些自定义声明。但是,我不确定我应该写什么来检索这些声明。
这是我的代币创建函数
public String createToken(AuthenticationDTO Input)
{
//Set issued at date
DateTime issuedAt = DateTime.UtcNow;
//set the time when it expires
DateTime expires = DateTime.UtcNow.AddDays(7);
//
var tokenHandler = new JwtSecurityTokenHandler();
//create a identity and add claims to the user which we want to log in
ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
{
new Claim("UserName", Input.UserName),
new Claim("Email",Input.Email),
new Claim("PhoneNumber",Input.PhoneNumber),
new Claim("FirstName",Input.FirstName),
new Claim("LastName",Input.LastName),
new Claim("Id",Input.Id)
});
const string sec = HostConfig.SecurityKey;
var now = DateTime.UtcNow;
var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
//create the jwt
var token =(JwtSecurityToken)
tokenHandler.CreateJwtSecurityToken(issuer: HostConfig.Issuer, audience: HostConfig.Audience,
subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
var tokenString = tokenHandler.WriteToken(token);
return tokenString;
}
我决定命名自己的声明,而不是使用提供的标准声明。但是,我不知道如何找回它们。这是我目前拥有的:
public AuthenticationDTO DecodeToken(String Input)
{
var key = Encoding.ASCII.GetBytes(HostConfig.SecurityKey);
var handler = new JwtSecurityTokenHandler();
var tokenSecure = handler.ReadToken(Input) as SecurityToken;
var validations = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
var claims = handler.ValidateToken(Input, validations, out tokenSecure);
return null;
}
编辑:
我注意到我的声明是这样的
如何提取它们?
编辑 2:
添加了 AuthentcationDTO
public class AuthenticationDTO
{
public String Id { get; set; }
public String UserName { get; set; }
public String Email { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String PhoneNumber { get; set; }
}
如果您想获得索赔,即 preferred_username
您可以从 ClaimsPrincipal 获得。
var user = User as ClaimsPrincipal;
string username = user.Claims.Where(c => c.Type == "preferred_username")
.Select(x => x.Value).FirstOrDefault();
User
将来自 Claims
。为此写
using System.Security.Claims;
似乎User
并不是所有版本都可用。另一种获得索赔的方法与此类似。
var prinicpal = (ClaimsPrincipal)Thread.CurrentPrincipal;
var email = prinicpal.Claims.Where(c => c.Type == ClaimTypes.Email)
.Select(c => c.Value).SingleOrDefault();
分配 AuthenticationDTO
的所有值。
public AuthenticationDTO DecodeToken(String Input)
{
var key = Encoding.ASCII.GetBytes(HostConfig.SecurityKey);
var handler = new JwtSecurityTokenHandler();
var tokenSecure = handler.ReadToken(Input) as SecurityToken;
var validations = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
var claims = handler.ValidateToken(Input, validations, out tokenSecure);
var prinicpal = (ClaimsPrincipal)Thread.CurrentPrincipal;
if (principal is ClaimsPrincipal claims)
{
return new ApplicationDTO
{
Id = claims.Claims.FirstOrDefault(x => x.Type == "sub")?.Value ?? "",
UserName = claims.Claims.FirstOrDefault(x => x.Type == "preferred_username")?.Value ?? "",
Email = claims.Claims.FirstOrDefault(x => x.Type == "email")?.Value ?? ""
};
}
return null;
}
我正在尝试检索我在创建令牌时所做的一些自定义声明。但是,我不确定我应该写什么来检索这些声明。
这是我的代币创建函数
public String createToken(AuthenticationDTO Input)
{
//Set issued at date
DateTime issuedAt = DateTime.UtcNow;
//set the time when it expires
DateTime expires = DateTime.UtcNow.AddDays(7);
//
var tokenHandler = new JwtSecurityTokenHandler();
//create a identity and add claims to the user which we want to log in
ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
{
new Claim("UserName", Input.UserName),
new Claim("Email",Input.Email),
new Claim("PhoneNumber",Input.PhoneNumber),
new Claim("FirstName",Input.FirstName),
new Claim("LastName",Input.LastName),
new Claim("Id",Input.Id)
});
const string sec = HostConfig.SecurityKey;
var now = DateTime.UtcNow;
var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
//create the jwt
var token =(JwtSecurityToken)
tokenHandler.CreateJwtSecurityToken(issuer: HostConfig.Issuer, audience: HostConfig.Audience,
subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
var tokenString = tokenHandler.WriteToken(token);
return tokenString;
}
我决定命名自己的声明,而不是使用提供的标准声明。但是,我不知道如何找回它们。这是我目前拥有的:
public AuthenticationDTO DecodeToken(String Input)
{
var key = Encoding.ASCII.GetBytes(HostConfig.SecurityKey);
var handler = new JwtSecurityTokenHandler();
var tokenSecure = handler.ReadToken(Input) as SecurityToken;
var validations = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
var claims = handler.ValidateToken(Input, validations, out tokenSecure);
return null;
}
编辑:
我注意到我的声明是这样的
如何提取它们?
编辑 2:
添加了 AuthentcationDTO
public class AuthenticationDTO
{
public String Id { get; set; }
public String UserName { get; set; }
public String Email { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String PhoneNumber { get; set; }
}
如果您想获得索赔,即 preferred_username
您可以从 ClaimsPrincipal 获得。
var user = User as ClaimsPrincipal;
string username = user.Claims.Where(c => c.Type == "preferred_username")
.Select(x => x.Value).FirstOrDefault();
User
将来自 Claims
。为此写
using System.Security.Claims;
似乎User
并不是所有版本都可用。另一种获得索赔的方法与此类似。
var prinicpal = (ClaimsPrincipal)Thread.CurrentPrincipal;
var email = prinicpal.Claims.Where(c => c.Type == ClaimTypes.Email)
.Select(c => c.Value).SingleOrDefault();
分配 AuthenticationDTO
的所有值。
public AuthenticationDTO DecodeToken(String Input)
{
var key = Encoding.ASCII.GetBytes(HostConfig.SecurityKey);
var handler = new JwtSecurityTokenHandler();
var tokenSecure = handler.ReadToken(Input) as SecurityToken;
var validations = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
var claims = handler.ValidateToken(Input, validations, out tokenSecure);
var prinicpal = (ClaimsPrincipal)Thread.CurrentPrincipal;
if (principal is ClaimsPrincipal claims)
{
return new ApplicationDTO
{
Id = claims.Claims.FirstOrDefault(x => x.Type == "sub")?.Value ?? "",
UserName = claims.Claims.FirstOrDefault(x => x.Type == "preferred_username")?.Value ?? "",
Email = claims.Claims.FirstOrDefault(x => x.Type == "email")?.Value ?? ""
};
}
return null;
}