声明身份 .NET CORE 3.0 API JWT
Claims Identity .NET CORE 3.0 API JWT
我正在尝试在 .NET CORE 3.0 上开发 Web API,但我无法从控制器获取 userId
这是我的创业公司
RSAParameters keyParams = RsaKeyUtils.GetKeyParameters("jwt_key.conf");
var key = new RsaSecurityKey(keyParams);
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
IssuerSigningKey = key,
ValidAudience = GappedAuthSettings.TokenAudience,
ValidIssuer = GappedAuthSettings.TokenIssuer,
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
RequireSignedTokens = true,
ClockSkew = TimeSpan.FromMinutes(0)
};
});
这是发布 JWT 令牌的方式:
private string GetToken(string userEmail, DateTime? expires, IEnumerable<Claim> claims)
{
var handler = new JwtSecurityTokenHandler();
var identity = new ClaimsIdentity(new GenericIdentity(userEmail, "Auth"), claims);
var securityToken = handler.CreateToken(new SecurityTokenDescriptor
{
Issuer = this.tokenOptions.Issuer,
Audience = this.tokenOptions.Audience,
SigningCredentials = this.tokenOptions.SigningCredentials,
Subject = identity,
Expires = expires,
IssuedAt = DateTime.UtcNow
});
return handler.WriteToken(securityToken);
}
当我尝试读取它时 claimsIdentity returns 一个具有空属性的对象
protected string GetUserId()
{
var claimsIdentity = this.User.Identity as ClaimsIdentity;
var userId = claimsIdentity.FindFirst("userId")?.Value;
if (userId != null)
{
return userId;
}
return null;
}
IMG
这是一个像下面这样的工作演示:
1.appsettings.json:
"Jwt": {
"Key": "ThisismySecretKey",
"Issuer": "Test.com"
}
2.Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])),
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
RequireSignedTokens = true,
ClockSkew = TimeSpan.FromMinutes(0)
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication(); //be sure to add this line
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
3.Controller:
[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
private IConfiguration _config;
public ValuesController(IConfiguration config)
{
_config = config;
}
[HttpGet]
public string Get()
{
var claim = new[]
{
new Claim("userId", "1")
};
var data = GetToken("np@hotmail.com", null, claim);
return data;
}
[HttpGet]
private string GetToken(string userEmail, DateTime? expires, IEnumerable<Claim> claims)
{
var handler = new JwtSecurityTokenHandler();
var identity = new ClaimsIdentity(new GenericIdentity(userEmail, "Auth"), claims);
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var securityToken = handler.CreateToken(new SecurityTokenDescriptor
{
Issuer = _config["Jwt:Issuer"],
Audience = _config["Jwt:Issuer"],
SigningCredentials = credentials,
Subject = identity,
Expires = DateTime.Now.AddMinutes(120),
IssuedAt = DateTime.UtcNow
});
return handler.WriteToken(securityToken);
}
}
4.The 测试方法(一定要加[Authorize]
):
[Route("api/[controller]")]
public class TestController : Controller
{
[Authorize]
[HttpGet]
public string Get()
{
var claimsIdentity = this.User.Identity as ClaimsIdentity;
var claim = claimsIdentity.Claims;
// or
var data = claimsIdentity.FindFirst("userId").Value;
return data;
}
}
5.Test 程序:
首先,您需要通过GetToken
方法获取令牌。
然后,调用授权类型为Bearer Token
的测试方法。
终于可以理赔了。
我正在尝试在 .NET CORE 3.0 上开发 Web API,但我无法从控制器获取 userId
这是我的创业公司
RSAParameters keyParams = RsaKeyUtils.GetKeyParameters("jwt_key.conf");
var key = new RsaSecurityKey(keyParams);
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
IssuerSigningKey = key,
ValidAudience = GappedAuthSettings.TokenAudience,
ValidIssuer = GappedAuthSettings.TokenIssuer,
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
RequireSignedTokens = true,
ClockSkew = TimeSpan.FromMinutes(0)
};
});
这是发布 JWT 令牌的方式:
private string GetToken(string userEmail, DateTime? expires, IEnumerable<Claim> claims)
{
var handler = new JwtSecurityTokenHandler();
var identity = new ClaimsIdentity(new GenericIdentity(userEmail, "Auth"), claims);
var securityToken = handler.CreateToken(new SecurityTokenDescriptor
{
Issuer = this.tokenOptions.Issuer,
Audience = this.tokenOptions.Audience,
SigningCredentials = this.tokenOptions.SigningCredentials,
Subject = identity,
Expires = expires,
IssuedAt = DateTime.UtcNow
});
return handler.WriteToken(securityToken);
}
当我尝试读取它时 claimsIdentity returns 一个具有空属性的对象
protected string GetUserId()
{
var claimsIdentity = this.User.Identity as ClaimsIdentity;
var userId = claimsIdentity.FindFirst("userId")?.Value;
if (userId != null)
{
return userId;
}
return null;
}
IMG
这是一个像下面这样的工作演示:
1.appsettings.json:
"Jwt": {
"Key": "ThisismySecretKey",
"Issuer": "Test.com"
}
2.Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])),
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
RequireSignedTokens = true,
ClockSkew = TimeSpan.FromMinutes(0)
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication(); //be sure to add this line
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
3.Controller:
[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
private IConfiguration _config;
public ValuesController(IConfiguration config)
{
_config = config;
}
[HttpGet]
public string Get()
{
var claim = new[]
{
new Claim("userId", "1")
};
var data = GetToken("np@hotmail.com", null, claim);
return data;
}
[HttpGet]
private string GetToken(string userEmail, DateTime? expires, IEnumerable<Claim> claims)
{
var handler = new JwtSecurityTokenHandler();
var identity = new ClaimsIdentity(new GenericIdentity(userEmail, "Auth"), claims);
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var securityToken = handler.CreateToken(new SecurityTokenDescriptor
{
Issuer = _config["Jwt:Issuer"],
Audience = _config["Jwt:Issuer"],
SigningCredentials = credentials,
Subject = identity,
Expires = DateTime.Now.AddMinutes(120),
IssuedAt = DateTime.UtcNow
});
return handler.WriteToken(securityToken);
}
}
4.The 测试方法(一定要加[Authorize]
):
[Route("api/[controller]")]
public class TestController : Controller
{
[Authorize]
[HttpGet]
public string Get()
{
var claimsIdentity = this.User.Identity as ClaimsIdentity;
var claim = claimsIdentity.Claims;
// or
var data = claimsIdentity.FindFirst("userId").Value;
return data;
}
}
5.Test 程序:
首先,您需要通过GetToken
方法获取令牌。
然后,调用授权类型为Bearer Token
的测试方法。
终于可以理赔了。