欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Asp.Net Core基于JWT认证的数据接口网关实例代码

程序员文章站 2022-03-21 13:59:21
前言 近日,应一位朋友的邀请写了个asp.net core基于jwt认证的数据接口网关demo。朋友自己开了个公司,接到的一个升级项目,客户要求用aps.net core...

前言

近日,应一位朋友的邀请写了个asp.net core基于jwt认证的数据接口网关demo。朋友自己开了个公司,接到的一个升级项目,客户要求用aps.net core做数据网关服务且基于jwt认证实现对前后端分离的数据服务支持,于是想到我一直做.net开发,问我是否对.net core有所了解?能不能做个简单demo出来看看?我说,分道扬镳之后我不是调用别人的接口就是提供接口给别人调用,于是便有了以下示例代码。

示例要求能演示获取token及如何使用该token访问数据资源,在demo中实现了jwt的颁发及验证以及重写一个actionauthorizeattribute实现对具体数据接口的调用权限控制,先看一下项目截图:

Asp.Net Core基于JWT认证的数据接口网关实例代码[项目截图]

项目文件介绍

解决方案下只有一个项目,项目名称就叫jwt.gateway,包含主要文件有:

  1. controllers目录下的apiactionfilterattribute.cs文件,继承microsoft.aspnetcore.mvc.filters.actionfilterattribute,用于校验接口调用者对具体接口的访问权限。
  2. controllers目录下的apibase.cs文件,继承microsoft.aspnetcore.mvc.controller,具有microsoft.aspnetcore.authorization.authorize特性引用,用于让所有数据接口用途的控制器继承,定义有currentappkey属性(来访应用程序的身份标识)并在onactionexecuting事件中统一分析claims并赋值。
  3. controllers目录下的tokencontroller.cs控制器文件,用于对调用方应用程序获取及注销token。
  4. controllers目录下的userscontroller.cs控制器文件,继承apibase.cs,作为数据调用示例。
  5. middlewares目录下的apicustomexception.cs文件,是一个数据接口的统一异常处理中间件。
  6. models目录下的apiresponse.cs文件,用于做数据接口的统一数据及错误信息输出实体模型。
  7. models目录下的user.cs文件,示例数据实体模型。
  8. program.cs及startup.cs文件就不介绍了,随便建个空项目都有。

项目文件代码

apiactionfilterattribute.cs

controllers目录下的apiactionfilterattribute.cs文件,继承microsoft.aspnetcore.mvc.filters.actionfilterattribute,用于校验接口调用者对具体接口的访问权限。

设想每一个到访的请求都是一个应用程序,每一个应用程序都分配有基本的key和password,每一个应用程序具有不同的接口访问权限,所以在具体的数据接口上应该声明该接口所要求的权限值,比如修改用户信息的接口应该在接口方法上声明需要具有“修改用户”的权限,用例: [apiactionfilter("用户修改")]

大部分情况下一个接口(方法)对应一个操作,这样基本上就能应付了,但是不排除有时候可能需要多个权限组合进行验证,所以该文件中有一个对多个权限值进行校验的“与”和“和”枚举,用例: [apiactionfilter(new string[] { "用户修改", "用户录入", "用户删除" },apiactionfilterattributeoption.and)] ,这样好像就差不多了。

由于在一个接口调用之后可能需要将该接口所声明需要的权限值记入日志等需求,因此权限值集合将被写入到httpcontext.items["permissions"]中以方便可能的后续操作访问,看代码:

using system;
using system.collections.generic;
using system.linq;
using system.threading.tasks;
using microsoft.aspnetcore.mvc.filters;

namespace jwt.gateway.controllers
{
 public enum apiactionfilterattributeoption
 {
 or,and
 }
 public class apiactionfilterattribute : microsoft.aspnetcore.mvc.filters.actionfilterattribute
 {
 list<string> permissions = new list<string>();
 apiactionfilterattributeoption option = apiactionfilterattributeoption.and;
 public apiactionfilterattribute(string permission)
 {
 permissions.add(permission);
 }
 public apiactionfilterattribute(string[] permissions, apiactionfilterattributeoption option)
 {
 foreach(var permission in permissions) {
 if (permissions.contains(permission))
 {
  continue;
 }
 permissions.add(permission);
 }
 option = option;
 }

 public override void onactionexecuting(actionexecutingcontext context)
 {
 var key = getappkey(context);
 list<string> keypermissions = getappkeypermissions(key);
 var isand = option == apiactionfilterattributeoption.and;
 var permissionscount = permissions.count;
 var keypermissionscount = keypermissions.count;
 for (var i = 0; i < permissionscount; i++)
 {
 bool flag = false;
 for (var j = 0; j < keypermissions.count; j++)
 {
  if (flag = string.equals(permissions[i], keypermissions[j], stringcomparison.ordinalignorecase))
  {
  break;
  }
 }
 if (flag)
 {
  continue;
 }
 if (isand)
 {
  throw new exception("应用“" + key + "”缺少“" + permissions[i] + "”的权限");
 }
 }

 context.httpcontext.items.add("permissions", permissions);

 base.onactionexecuting(context);
 }

 private string getappkey(actionexecutingcontext context)
 {
 var claims = context.httpcontext.user.claims;
 if (claims == null)
 {
 throw new exception("未能获取到应用标识");
 }
 var claimkey = claims.tolist().find(o => string.equals(o.type, "appkey", stringcomparison.ordinalignorecase));
 if (claimkey == null)
 {
 throw new exception("未能获取到应用标识");
 }

 return claimkey.value;
 }
 private list<string> getappkeypermissions(string appkey)
 {
 list<string> li = new list<string>
 {
 "用户明细","用户列表","用户录入","用户修改","用户删除"
 };
 return li;
 }

 }
}

apiactionauthorizeattribute.cs

apibase.cs

controllers目录下的apibase.cs文件,继承microsoft.aspnetcore.mvc.controller,具有microsoft.aspnetcore.authorization.authorize特性引用,用于让所有数据接口用途的控制器继承,定义有currentappkey属性(来访应用程序的身份标识)并在onactionexecuting事件中统一分析claims并赋值。

通过验证之后,aps.net core会在httpcontext.user.claims中将将来访者的身份信息记录下来,我们可以通过该集合得到来访者的身份信息。

using system;
using system.collections.generic;
using system.linq;
using system.threading.tasks;
using microsoft.aspnetcore.http;
using microsoft.aspnetcore.mvc;
using microsoft.aspnetcore.mvc.filters;

namespace jwt.gateway.controllers
{
 [microsoft.aspnetcore.authorization.authorize]
 public class apibase : microsoft.aspnetcore.mvc.controller
 {
 private string _currentappkey = "";
 public string currentappkey { get { return _currentappkey; } }
 public override void onactionexecuting(actionexecutingcontext context)
 {
  var claims = context.httpcontext.user.claims.tolist();
  var claim = claims.find(o => o.type == "appkey");
  if (claim == null)
  {
  throw new exception("未通过认证");
  }
  var appkey = claim.value;
  if (string.isnullorempty(appkey))
  {
  throw new exception("appkey不合法");
  }

  _currentappkey = appkey;

  base.onactionexecuting(context);
 }
 }
}

apibase.cs

tokencontroller.cs

controllers目录下的tokencontroller.cs控制器文件,用于对调用方应用程序获取及注销token。

using system;
using system.collections.generic;
using system.linq;
using system.threading.tasks;
using microsoft.aspnetcore.http;
using microsoft.aspnetcore.mvc;

namespace jwt.gateway.controllers
{
 [route("api/[controller]/[action]")]
 public class tokencontroller : controller
 {
 private readonly microsoft.extensions.configuration.iconfiguration _configuration;

 public tokencontroller(microsoft.extensions.configuration.iconfiguration configuration)
 {
  _configuration = configuration;
 }

 // /api/token/get
 public iactionresult get(string appkey, string apppassword)
 {
  try
  {
  if (string.isnullorempty(appkey))
  {
   throw new exception("缺少appkey");
  }
  if (string.isnullorempty(appkey))
  {
   throw new exception("缺少apppassword");
  }
  if (appkey != "mykey" && apppassword != "mypassword")//固定的appkey及apppassword,实际项目中应该来自数据库或配置文件
  {
   throw new exception("配置不存在");
  }

  var key = new microsoft.identitymodel.tokens.symmetricsecuritykey(system.text.encoding.utf8.getbytes(_configuration["jwtsecuritykey"]));
  var creds = new microsoft.identitymodel.tokens.signingcredentials(key, microsoft.identitymodel.tokens.securityalgorithms.hmacsha256);
  var claims = new list<system.security.claims.claim>();
  claims.add(new system.security.claims.claim("appkey", appkey));//仅在token中记录appkey
  var token = new system.identitymodel.tokens.jwt.jwtsecuritytoken(
   issuer: _configuration["jwttokenissuer"],
   audience: _configuration["jwttokenaudience"],
   claims: claims,
   expires: datetime.now.addminutes(30),
   signingcredentials: creds);

  return ok(new models.apiresponse { status = 1, message = "ok", data = new system.identitymodel.tokens.jwt.jwtsecuritytokenhandler().writetoken(token) });

  }
  catch(exception ex)
  {
  return ok(new models.apiresponse { status = 0, message = ex.message, data = "" });
  }
 }
 
 // /api/token/delete
 public iactionresult delete(string token)
 {
  //code: 加入黑名单,使其无效

  return ok(new models.apiresponse { status = 1, message = "ok", data = "" });
 }


 }
}

tokencontroller.cs

userscontroller.cs

controllers目录下的userscontroller.cs控制器文件,继承apibase.cs,作为数据调用示例。

该控制器定义了对user对象常规的明细、列表、录入、修改、删除等操作。

using system;
using system.collections.generic;
using system.linq;
using system.threading.tasks;
using microsoft.aspnetcore.mvc;

namespace jwt.gateway.controllers
{
 [produces("application/json")]
 [route("api/[controller]/[action]")]
 public class userscontroller : apibase
 {
 /* 
  * 1.要访问访问该控制器提供的接口请先通过"/api/token/get"获取token
  * 2.访问该控制器提供的接口http请求头必须具有值为"bearer+空格+token"的authorization键,格式参考:
  * "authorization"="bearer eyjhbgcioijiuzi1niisinr5cci6ikpxvcj9.eyjyb2xlijoiqxbwiiwiyxbws2v5ijoibxllzxkilcjlehaioje1nte3odc2mdmsimlzcyi6ikdhdgv3yxkilcjhdwqioijhdwrpzw5jzsj9.gq9_q7hut31ofyfl533t-bno5iwd2drl0nmd1jwqkmi"
 */

 /// <summary>
 /// 临时用户测试数据,实际项目中应该来自数据库等媒介
 /// </summary>
 static list<models.user> _users = null;
 static object _lock = new object();
 public userscontroller()
 {
  if (_users == null)
  {
  lock (_lock)
  {
   if (_users == null)
   {
   _users = new list<models.user>();
   var now = datetime.now;
   for(var i = 0; i < 10; i++)
   {
    var num = i + 1;
    _users.add(new models.user { userid = num, username = "name"+num, userpassword = "pwd"+num, userjointime = now });
   }
   }
  }
  }
 }

 // /api/users/detail
 [apiactionfilter("用户明细")]
 public iactionresult detail(long userid)
 {
  /*
  //获取appkey(在apibase中写入)
  var appkey = currentappkey;
  //获取使用的权限(在apiactionauthorizeattribute中写入)
  var permissions = httpcontext.items["permissions"];
  */

  var user = _users.find(o => o.userid == userid);
  if (user == null)
  {
  throw new exception("用户不存在");
  }

  return ok(new models.apiresponse { data = user, status = 1, message = "ok" });
 }

 // /api/users/list
 [apiactionfilter("用户列表")]
 public iactionresult list(int page, int size)
 {
  page = page < 1 ? 1 : page;
  size = size < 1 ? 1 : size;
  var total = _users.count();
  var pages = total % size == 0 ? total / size : ((long)math.floor((double)total / size + 1));
  if (page > pages)
  {
  return ok(new models.apiresponse { data = new list<models.user>(), status = 1, message = "ok", total = total });
  }
  var li = new list<models.user>();
  var startindex = page * size - size;
  var endindex = startindex + size - 1;
  if (endindex > total - 1)
  {
  endindex = total - 1;
  }
  for(; startindex <= endindex; startindex++)
  {
  li.add(_users[startindex]);
  }
  return ok(new models.apiresponse { data = li, status = 1, message = "ok", total = total });
 }

 // /api/users/add
 [apiactionfilter("用户录入")]
 public iactionresult add()
 {
  return ok(new models.apiresponse { status = 1, message = "ok" });
 }

 // /api/users/update
 [apiactionfilter(new string[] { "用户修改", "用户录入", "用户删除" },apiactionfilterattributeoption.and)]
 public iactionresult update()
 {
  return ok(new models.apiresponse { status = 1, message = "ok" });
 }

 // /api/users/delete
 [apiactionfilter("用户删除")]
 public iactionresult delete()
 {
  return ok(new models.apiresponse { status = 1, message = "ok" });
 }
 }
}

userscontroller.cs

apicustomexception.cs

middlewares目录下的apicustomexception.cs文件,是一个数据接口的统一异常处理中间件。

该文件整理并抄袭自:https://www.cnblogs.com/shennan/p/10197231.html

在此特别感谢一下作者的先行贡献,并请原谅我无耻的抄袭。

using system;
using system.collections.generic;
using system.linq;
using system.threading.tasks;
using microsoft.aspnetcore.http;
using microsoft.aspnetcore.builder;
using microsoft.extensions.dependencyinjection;

namespace jwt.gateway.middlewares
{
 //参考: https://www.cnblogs.com/shennan/p/10197231.html

 public enum apicustomexceptionhandletype
 {
 jsonhandle = 0,
 pagehandle = 1,
 both = 2
 }
 public class apicustomexceptionmiddlewareoption
 {
 public apicustomexceptionmiddlewareoption(
  apicustomexceptionhandletype handletype = apicustomexceptionhandletype.jsonhandle,
  ilist<pathstring> jsonhandleurlkeys = null,
  string errorhandingpath = "")
 {
  handletype = handletype;
  jsonhandleurlkeys = jsonhandleurlkeys;
  errorhandingpath = errorhandingpath;
 }
 public apicustomexceptionhandletype handletype { get; set; }
 public ilist<pathstring> jsonhandleurlkeys { get; set; }
 public pathstring errorhandingpath { get; set; }
 }
 public class apicustomexceptionmiddleware
 {
 private requestdelegate _next;
 private apicustomexceptionmiddlewareoption _option;
 private idictionary<int, string> _exceptionstatuscodedic;

 public apicustomexceptionmiddleware(requestdelegate next, apicustomexceptionmiddlewareoption option)
 {
  _next = next;
  _option = option;
  _exceptionstatuscodedic = new dictionary<int, string>
  {
  { 401, "未授权的请求" },
  { 404, "找不到该页面" },
  { 403, "访问被拒绝" },
  { 500, "服务器发生意外的错误" }
  //其余状态自行扩展
  };
 }

 public async task invoke(httpcontext context)
 {
  exception exception = null;
  try
  {
  await _next(context);
  }
  catch (exception ex)
  {
  context.response.clear();
  context.response.statuscode = 200;//手动设置状态码(总是成功)
  exception = ex;
  }
  finally
  {
  if (_exceptionstatuscodedic.containskey(context.response.statuscode) &&
   !context.items.containskey("exceptionhandled"))
  {
   var errormsg = string.empty;
   if (context.response.statuscode == 500 && exception != null)
   {
   errormsg = $"{_exceptionstatuscodedic[context.response.statuscode]}\r\n{(exception.innerexception != null ? exception.innerexception.message : exception.message)}";
   }
   else
   {
   errormsg = _exceptionstatuscodedic[context.response.statuscode];
   }
   exception = new exception(errormsg);
  }
  if (exception != null)
  {
   var handletype = _option.handletype;
   if (handletype == apicustomexceptionhandletype.both)
   {
   var requestpath = context.request.path;
   handletype = _option.jsonhandleurlkeys != null && _option.jsonhandleurlkeys.count(
    k => requestpath.startswithsegments(k, stringcomparison.currentcultureignorecase)) > 0 ?
    apicustomexceptionhandletype.jsonhandle :
    apicustomexceptionhandletype.pagehandle;
   }

   if (handletype == apicustomexceptionhandletype.jsonhandle)
   await jsonhandle(context, exception);
   else
   await pagehandle(context, exception, _option.errorhandingpath);
  }
  }
 }
 private jwt.gateway.models.apiresponse getapiresponse(exception ex)
 {
  return new jwt.gateway.models.apiresponse() { status = 0, message = ex.message };
 }
 private async task jsonhandle(httpcontext context, exception ex)
 {
  var apiresponse = getapiresponse(ex);
  var serialzestr = newtonsoft.json.jsonconvert.serializeobject(apiresponse);
  context.response.contenttype = "application/json";
  await context.response.writeasync(serialzestr, system.text.encoding.utf8);
 }
 private async task pagehandle(httpcontext context, exception ex, pathstring path)
 {
  context.items.add("exception", ex);
  var originpath = context.request.path;
  context.request.path = path;
  try
  {
  await _next(context);
  }
  catch { }
  finally
  {
  context.request.path = originpath;
  }
 }
 }
 public static class apicustomexceptionmiddlewareextensions
 {
 public static iapplicationbuilder useapicustomexception(this iapplicationbuilder app, apicustomexceptionmiddlewareoption option)
 {
  return app.usemiddleware<apicustomexceptionmiddleware>(option);
 }
 }
}

apicustomexception.cs

配置相关

appsettings.json

算法'hs256'要求securitykey.keysize大于'128'位,所以jwtsecuritykey可不要太短了哦。

{
 "urls": "http://localhost:60000",
 "allowedhosts": "*",
 "jwtsecuritykey": "areyouokhhhhhhhhhhhhhhhhhhhhhhhhhhh",
 "jwttokenissuer": "jwt.gateway",
 "jwttokenaudience": "app"
}

appsettings.json

startup.cs

关于jwt的配置可以在通过jwtbeareroptions加入一些自己的事件处理逻辑,共有4个事件可供调用:

onauthenticationfailed,onmessagereceived,ontokenvalidated,onchallenge, 本示例中是在ontokenvalidated中插入token黑名单的校验逻辑。黑名单应该是jwt应用场景中主动使token过期的主流做法了。

using system;
using system.collections.generic;
using system.linq;
using system.threading.tasks;
using microsoft.aspnetcore.builder;
using microsoft.aspnetcore.hosting;
using microsoft.aspnetcore.http;
using jwt.gateway.middlewares;
using microsoft.extensions.dependencyinjection;

namespace jwt.gateway
{
 public class startup
 {
  private readonly microsoft.extensions.configuration.iconfiguration _configuration;

  public startup(microsoft.extensions.configuration.iconfiguration configuration)
  {
   _configuration = configuration;
  }
  
  public void configureservices(iservicecollection services)
  {
   services.addauthentication(microsoft.aspnetcore.authentication.jwtbearer.jwtbearerdefaults.authenticationscheme)
    .addjwtbearer(options => {
     options.events = new microsoft.aspnetcore.authentication.jwtbearer.jwtbearerevents
     {
      /*onmessagereceived = context =>
      {
       context.token = context.request.query["access_token"];
       return task.completedtask;
      },*/
      ontokenvalidated = context =>
      {
       var token = ((system.identitymodel.tokens.jwt.jwtsecuritytoken)context.securitytoken).rawdata;
       if (inblacklist(token))
       {
        context.fail("token in blacklist");
       }
       return task.completedtask;
      }
     };
     options.tokenvalidationparameters = new microsoft.identitymodel.tokens.tokenvalidationparameters
     {
      validateissuer = true,
      validateaudience = true,
      validatelifetime = true,
      validateissuersigningkey = true,
      validaudience = _configuration["jwttokenaudience"],
      validissuer = _configuration["jwttokenissuer"],
      issuersigningkey = new microsoft.identitymodel.tokens.symmetricsecuritykey(system.text.encoding.utf8.getbytes(_configuration["jwtsecuritykey"]))
     };
    });
   services.addmvc().addjsonoptions(option=> {
    option.serializersettings.dateformatstring = "yyyy-mm-dd hh:mm:ss.fff";
   });
  }

  public void configure(iapplicationbuilder app, ihostingenvironment env)
  {
   if (env.isdevelopment())
   {
    app.usedeveloperexceptionpage();
   }

   app.useapicustomexception(new apicustomexceptionmiddlewareoption(
      handletype: apicustomexceptionhandletype.both,
      jsonhandleurlkeys: new pathstring[] { "/api" },
      errorhandingpath: "/home/error"));

   app.useauthentication();

   app.usemvc();
  }



  bool inblacklist(string token)
  {
   //code: 实际项目中应该查询数据库或配置文件进行比对

   return false;
  }


 }
}

startup.cs

program.cs

using system;
using system.collections.generic;
using system.io;
using system.linq;
using system.threading.tasks;
using microsoft.aspnetcore;
using microsoft.aspnetcore.hosting;
using microsoft.extensions.configuration;
using microsoft.extensions.logging;

namespace jwt.gateway
{
 public class program
 {
  public static void main(string[] args)
  {
   buildwebhost(args).run();
  }

  public static iwebhost buildwebhost(string[] args)
  {
   var config = new configurationbuilder()
    .setbasepath(directory.getcurrentdirectory())
    .addjsonfile("appsettings.json", optional: true)
    .build();

   return webhost.createdefaultbuilder(args)
    .usekestrel()
    .useconfiguration(config)
    .usestartup<startup>()
    .build();
  }
 }
}

program.cs

运行截图

Asp.Net Core基于JWT认证的数据接口网关实例代码[运行截图-获取token]

Asp.Net Core基于JWT认证的数据接口网关实例代码[运行截图-配置fiddler调用接口获取数据]

Asp.Net Core基于JWT认证的数据接口网关实例代码[运行截图-获取到数据]

如果token校验失败将会返回401错误!

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。