任務36:應用Jwtbearer Authenticationweb
D:\MyDemos\jesseapi
新建項目:dotnet new webapi --name JwtAuthSampleasp.net
VS2017運行項目:http://localhost:5429/api/values加密
using Microsoft.AspNetCore.Authorization;
由於我本機安裝的是asp.net core 2.2的項目,因此用VScode去dotnet run的方式運行不行,默認建立的api項目是https的spa
因而我改用VS2017去打開建立的項目:項目的屬性 取消SSL.net
而後用VS運行項目:3d
加上authorize之後返回 500:code
引入orm
Startup.cs內加上這個middlewarejwt
新建文件夾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);
上面是認證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);
}