最近实现的Asp.net core 2.0 WEB Api。在我本地的开发环境上工作异常顺利。但是...当我部署到AZURE时,我发现我的JWT访问令牌不包含颁发者和受众声明,因此我得到401 Unauthorized with:Bearer error =“ invalid_token”,error_description =“受众无效”。在我的本地计算机上生成的JWT具有:(由jwt.io提供)
{
"http://schemas.xmlsoap.org/...": "Rory@gspin.com",
"sub": "Rory@gspin.com",
"given_name": "Rory",
"family_name": "McGilroy",
"email": "Rory@gspin.com",
"jti": "3875f83d-eb93-4d45-8507-795a0cb7e3e4",
"iat": 1533506381,
"rol": "api_access",
"id": "420990b2-4747-4c3c-ae0f-ccbbc4dfe521",
"nbf": 1533506381,
"exp": 1533513581,
"iss": "gspin.com",
"aud": "https://www.gspin.com"
}
但是在将相同的应用程序部署到AZURE APP Service之后,我的访问令牌包含以下内容:
{
"http://schemas.xmlsoap.org/...": "billyttom@fido.com",
"sub": "billyttom@fido.com",
"given_name": "billy mark tom",
"family_name": "last",
"email": "billyttom@fido.com",
"jti": "0d34a03f-31ae-45aa-9ace-004d5916b430",
"iat": 1533498384,
"rol": "api_access",
"id": "5485d641-974b-4f60-ade6-35c048503701",
"nbf": 1533498383,
"exp": 1533505583
}
缺少 iss 和 aud ???
您知道为什么在定义它们并将它们存在于本地计算机/ Visual Studio env上生成的令牌中时,为什么将它们部署到天蓝色时会丢弃?
My Code is : public async Task<string> GenerateEncodedToken(string
userName, ClaimsIdentity identity, UserManager<GSIdentityUser> _userManager)
{
var user = await _userManager.FindByNameAsync(userName);
var userClaims = await _userManager.GetClaimsAsync(user);
var claims = new[]
{
new Claim(ClaimTypes.Name, userName),
new Claim(JwtRegisteredClaimNames.Sub, userName),
new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName),
new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName),
new Claim(JwtRegisteredClaimNames.Email, user.Email), /// same as username
new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), // the uniqueness claim is a GUID
new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Rol),
identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Id)
};
// Create the JWT security token and encode it.
var jwt = new JwtSecurityToken(
issuer: _jwtOptions.Issuer,
audience: _jwtOptions.Audience,
claims: claims,
notBefore: _jwtOptions.NotBefore,
expires: _jwtOptions.Expiration,
signingCredentials: _jwtOptions.SigningCredentials);
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
return encodedJwt;
}
public ClaimsIdentity GenerateClaimsIdentity(string userName, string id)
{
return new ClaimsIdentity(new GenericIdentity(userName, "Token"), new[]
{
new Claim(Helpers.Constants.Strings.JwtClaimIdentifiers.Id, id),
new Claim(Helpers.Constants.Strings.JwtClaimIdentifiers.Rol, Helpers.Constants.Strings.JwtClaims.ApiAccess)
});
}
Also in ConfigureServices i have :
services.Configure<JwtIssuerOptions>(options =>
{
options.Issuer = Configuration["JwtIssuerOptions:Issuer"];
options.Audience=Configuration["JwtIssuerOptions:Audience"];
options.SigningCredentials = new SigningCredentials(_signingKey,
SecurityAlgorithms.HmacSha256);
});