任务36:应用Jwtbearer Authentication
任务36:应用Jwtbearer Authentication
D:\MyDemos\jesse
新建项目:dotnet new webapi --name JwtAuthSample
VS2017运行项目:http://localhost:5429/api/values
using Microsoft.AspNetCore.Authorization;
[Authorize]
因为我本机安装的是asp.net core 2.2的项目,所以用VScode去dotnet run的方式运行不行,默认创建的api项目是https的
于是我改用VS2017去打开创建的项目:项目的属性 取消SSL
然后用VS运行项目:
加上authorize以后返回 500:
引入
using Microsoft.AspNetCore.Authentication.JwtBearer;
Startup.cs内加上这个middleware
新建文件夹Models并在里面创建类:
JwtSettings.cs
namespace JwtAuthSample{ public class JwtSettings { //token是谁颁发的 public string Issuer{get;set;} //token可以给哪些客户端使用 public string Audience{get;set;} //加密的密钥 public string SecretKey{get;set;} } }
需要给jwt设置一些配置信息:
"JwtSettings": { "Audience": "http://localhost:5000", "Issuer": "http://localhost:5000", "SecretKey": "Hello-Key" }
services.Configure<JwtSettings>(Configuration); var jwtSettings=new JwtSettings(); Configuration.Bind("JwtSettings",jwtSettings);
Challenge是验证的时候
上面是认证middleware的配置
下面是认证jwt middleware的配置
在这个命名空间内:using Microsoft.IdentityModel.Tokens; 有对称加密的一种方式:SymmetricSecurityKey
IssuerSigningKey=new SymmetricSecurityKey(这里的参数要用utf-8),所以要引入命名空间system.Text;
这样就完成了jwt的配置
public void ConfigureServices(IServiceCollection services)
{
services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
var jwtSettings = new JwtSettings();
Configuration.Bind("JwtSettings", jwtSettings);
services.AddAuthentication(Options =>
{
Options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
Options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidIssuer = jwtSettings.Issuer,
ValidAudience = jwtSettings.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey))
};
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}