36-应用Jwtbearer Authentication
新建.net core webapi项目
E:\coding\netcore>dotnet new webapi --name JwtAuthSample
创建需要用到的实体对象类
namespace JwtAuthSample.Models { public class JwtSettings{ //发现者 public string Issure{get;set;} //使用者 public string Audience{get;set;} //jwt使用的密码 public string SecretKey {get;set;} } }
在appsettings.json 中增加映射到实体类JwtSettings的配置文件
"JwtSettings":{ "Issure":"http://localhost:5000", "Audience":"http://localhost:5000", "SecretKey":"123456789@byd@33311fasdfsad" }
在StartUp.cs方法ConfigureServices中配置如下代码,用于Jwt验证
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings")); var jwtSetting = new JwtSettings(); Configuration.Bind("JwtSettings",jwtSetting); services.AddAuthentication(options=>{ options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(jwtOption=>{ jwtOption.TokenValidationParameters=new Microsoft.IdentityModel.Tokens.TokenValidationParameters{ ValidIssuer = jwtSetting.Issure, ValidAudience = jwtSetting.Audience, IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey( System.Text.Encoding.UTF8.GetBytes(jwtSetting.SecretKey) ) }; }); }
为了让受权生效,需要在Configure启用授权
接下来测试授权有没有生效
需要在要授权的类或方法上加下[Authorize]特性
通过测试器访问 http://localhost:5000/api/values/ ,会出出现401未授权错误