概述

认证授权是很多系统的基本功能 , 在以前pc的时代 , 通常是基于cookies-session这样的方式实现认证授权 , 在那个时候通常系统的用户量都不会很大, 所以这种方式也一直很好运行, 随着现在都软件用户量越来越大, 系统架构也从以前垂直扩展(增加服务器性能) -> 水平扩展(增加服务器数量)

cookies-session 工作方式

客户端提交用户信息 -> 服务器识别用户 -> 服务端保存用户信息 -> 返回session-id客户端 -> 客户端保存session-id -> 每次请求cookies带上session-id

这种方式也不是不能水平扩展 , 例如 , session复制/第三方保存session(数据库 , redis)

名词解析

认证 : 识别用户是否合法

授权: 赋予用户权限 (能访问哪些资源)

鉴权: 鉴定权限是否合法

jwt优势与劣势

优势

无状态

token 存储身份验证所有信息 , 服务端不需要保存用户身份验证信息, 减少服务端压力 , 服务端更容易水平扩展, 由于无状态, 又会导致它最大缺点 , 很难注销

2、支持跨域访问

cookie是不允许垮域访问的,token支持

3、跨语言

基于标准化的 json web token (jwt) , 不依赖特定某一个语言 , 例如生成对token可以对多个语言使用(net , java , php …)

劣势

1、token有效性问题

后台很难注销已经发布的token , 通常需要借助第三方储存(数据库/缓存) 实现注销, 这样就会失去jwt最大的优势

2、占带宽

token长度(取决存放内容) 比session_id大 , 每次请求多消耗带宽 , token只存必要信息 , 避免token过长

3、需要实现续签

cookies – session 通常是框架已经实现续签功能, 每次访问把过期时间更新, jwt需要自己实现, 参考oauth2刷新token机制实现刷新token

4、消耗更多cpu

每次请求需要对内容解密和验证签名这两步操作,典型用时间换空间

只能根据自身使用场景决定使用哪一种身份验证方案 , 没有一种方案是通用的,完美的

aspnetcore集成jwt认证

1、添加包

dotnet add package microsoft.aspnetcore.authentication.jwtbearer

2、添加配置

"jwtoptions": {
 "issuer": "https://localhost:5001",
 "audience": "https://localhost:5001",
 "securitykey": "1g3l0yygboinid3a*ioei4iyxr7$spzm"
}

3、jwt bearer 扩展(选项)

public static authenticationbuilder addjwtbearer(this iservicecollection services, action<jwtoptions> configureoptions)
{
 if (configureoptions == null) throw new argumentnullexception(nameof(configureoptions));

 var jwtoptions = new jwtoptions()
 {
  issuer = "jwt authentication",
  audience = "wilson pan web api",
 };
 // set customs optoins
 configureoptions(jwtoptions);

 // update options 
 services.postconfigure<jwtoptions>(options =>
 {
  options.issuer = jwtoptions.issuer;
  options.audience = jwtoptions.audience;
  options.securitykey = jwtoptions.securitykey;
 });

 return services.addauthentication(jwtbearerdefaults.authenticationscheme)
     .addjwtbearer(options =>
     {
      options.tokenvalidationparameters = new tokenvalidationparameters()
      {
       validissuer = jwtoptions.issuer,
       validaudience = jwtoptions.audience,
       validateissuer = true,
       validatelifetime = true,
       validateissuersigningkey = true,
       issuersigningkey = jwtoptions.symmetricsecuritykey
      };
     });

}

4、configureservices

services.addjwtbearer(options =>
{
 options.issuer = configuration.getvalue<string>("jwtoptions:issuer");
 options.audience = configuration.getvalue<string>("jwtoptions:audience");
 options.securitykey = configuration.getvalue<string>("jwtoptions:securitykey");
});

5、configure

app.useauthentication();
app.useauthorization();

6、add authorizecontroller

//define claim 
var claims = new claim[]
{
  new claim(claimtypes.name, username),
  new claim(claimtypes.email, $"{username}@github.com"),
  new claim(claimtypes.role, username == "wilsonpan" ? "admin" : "reader"),
  new claim(claimtypes.hash, jwthashhelper.gethashstring($"{username}:{password}:{system.datetime.now.ticks}")),
};

//define jwtsecuritytoken
var token = new jwtsecuritytoken(
  issuer: _jwtoptions.issuer,
  audience: _jwtoptions.audience,
  claims: claims,
  expires: system.datetime.now.addminutes(5),
  signingcredentials: _jwtoptions.signingcredentials
);

// generate token
var result = new jwtsecuritytokenhandler().writetoken(token);

7、contrller/action 添加认证授权

[apicontroller]
[authorize]
[route("[controller]")]
public class apicontroller : controllerbase
{
  ...
}

[httppost]
[authorize(roles = "admin")]
public iactionresult post()
{
  return ok();
}

rest client

dotnet run

1、认证接口

@host = https://localhost:5001

# @name token
post {{host}}/authorize http/1.1
content-type: application/x-www-form-urlencoded

#username=wilson&password=123456
# admin 
username=wilsonpan&password=123456

2、需要授权接口

### required authorize
get {{host}}/api http/1.1
authorization: bearer {{token.response.body.*}}

3、需要管理员角色接口

### required authorize
post {{host}}/api http/1.1
authorization: bearer {{token.response.body.*}}

示例代码

总结

到此这篇关于asp.net core学习之使用jwt认证授权的文章就介绍到这了,更多相关asp.net core用jwt认证授权内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!