内容简介:此项目作者IKende ,github开源地址:此人博客园地址:我基于他的github项目的 samples学习的。反正我崇拜他
此项目作者IKende ,github开源地址: https://github.com/IKende
此人博客园地址: https://www.cnblogs.com/smark/
我基于他的github项目的 samples学习的。反正我崇拜他
全局异常
增加一个过滤器
public class CatehException : FilterAttribute { public override void Executed(ActionContext context) { base.Executed(context); if (context.Exception != null) { context.Result = new TextResult(context.Exception.Message); context.Exception = null; } } }
然后在Program中注册上
测试异常 http://127.0.0.1:5555/student/SelfIntroduce?name=1
public object SelfIntroduce(string name) { if (name == "1") throw new Exception("差不多"); return new { Hello = "我叫 " + name, InSchoolTime = new DateTime(1997, 9, 1, 10, 0, 0) }; }
抛出异常都进入这里了,其实是 每次都会执行这里,只是判断Exception是否为空
也算解决这个问题了。
JWT全称JSON Web Tokens,是现有webapi服务一种普遍的验证方式,下面简单讲解一下如何在BeetleX中集成它。 .Net Core已经提供这个功能库,所以基础功能并不需要自己编写,但为了方便使用还是需要扩展一个简单的操作类,首先引用System.IdentityModel.Tokens.Jwt,然后实现一个简单的JWTHelper
通过Nuget引用和安装
下面是Smark提供的一个JWTHelper
using Microsoft.IdentityModel.Tokens; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Text; namespace HttpApiServer.JWT { public class JWTHelper { private string mIssuer = null; private string mAudience = null; private SecurityKey mSecurityKey; private SigningCredentials mSigningCredentials; private TokenValidationParameters mTokenValidation = new TokenValidationParameters(); private JwtSecurityTokenHandler mJwtSecurityTokenHandler = new JwtSecurityTokenHandler(); public JWTHelper() : this(null, null) { } public JWTHelper(string issuer, string audience, string key = "2qyg4coej88uqrono0xdmx4y0il5dn5y7b72tlb3imba677ht1p1xlfcnh36mk5u3xzjktfara29axvzk85apfplun7oslbe1m20c148p5d519kja5wvg7lmn5v4a5ou") { mIssuer = issuer; mAudience = audience; mSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)); if (string.IsNullOrEmpty(mIssuer)) { mTokenValidation.ValidateIssuer = false; } else { mTokenValidation.ValidIssuer = mIssuer; } if (string.IsNullOrEmpty(mAudience)) { mTokenValidation.ValidateAudience = false; } else { mTokenValidation.ValidAudience = mAudience; } mTokenValidation.IssuerSigningKey = mSecurityKey; mSigningCredentials = new SigningCredentials(mSecurityKey, SecurityAlgorithms.HmacSha256); Expires = 60 * 24; } public int Expires { get; set; } public string CreateToken(string name, string role) { ClaimsIdentity claimsIdentity = new ClaimsIdentity(); claimsIdentity.AddClaim(new Claim("Name", name)); claimsIdentity.AddClaim(new Claim("Role", role)); var item = mJwtSecurityTokenHandler.CreateEncodedJwt(mIssuer, mAudience, claimsIdentity, DateTime.Now.AddMinutes(-5), DateTime.Now.AddMinutes(100), DateTime.Now, mSigningCredentials); return item; } public ClaimsPrincipal ValidateToken(string token) { return mJwtSecurityTokenHandler.ValidateToken(token, mTokenValidation, out var securityToken); } public UserInfo GetUserInfo(string token) { UserInfo userInfo = new UserInfo(); if (!string.IsNullOrEmpty(token)) { var info = ValidateToken(token); ClaimsIdentity identity = info?.Identity as ClaimsIdentity; userInfo.Name = identity?.Claims?.FirstOrDefault(c => c.Type == "Name")?.Value; userInfo.Role = identity?.Claims?.FirstOrDefault(c => c.Type == "Role")?.Value; } return userInfo; } public struct UserInfo { public string Name; public string Role; } } }
基础功能完成后接下来需要做两个工作,一个是通过JWTHelper为用户生成Token,然后编写一个Filter来验证请求头部这个Token的有效性。
(个人理解,给客户端一个JWT的信息,让他存在浏览器)
增加一个全局的 Filter
public class JWTFilter : FilterAttribute { public override bool Executing(ActionContext context) { string token = context.HttpContext.Request.Header[HeaderTypeFactory.AUTHORIZATION]; var user = JWTHelper.Instance.GetUserInfo(token); if (!string.IsNullOrEmpty(user.Name)) { return true; } else { context.Result = new TextResult("token not found"); return false; } } }
然后在入口加进去,作为全局了
然后找个不需要的验证的地方,加上
我加了1个新的Controller
[BeetleX.FastHttpApi.Controller(BaseUrl = "g/", SingleInstance = true)] public class GController { [SkipFilter(typeof(JWTFilter))] public object GetToken(string name, string role) { return new TextResult(JWTHelper.Instance.CreateToken(name, role)); } }
然后访问
http://127.0.0.1:5555/g/gettoken?name=ay&role=admin
返回
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJOYW1lIjoiYXkiLCJSb2xlIjoiYWRtaW4iLCJuYmYiOjE1NDU5OTAzMDcsImV4cCI6MTU0NTk5NjYwNywiaWF0IjoxNTQ1OTkwNjA3fQ.G8RqQXDwkrMqsEaJsyxUrRhz_sJE14CWgVHx1gTR13I
然后拷贝到 jwt.io 验证下
访问没有跳过jwt验证的地方
我自己修改下GetToken的代码,登录成功在Respone的Header加上jwt
[SkipFilter(typeof(JWTFilter))] public object GetToken(string name, string role, IHttpContext context) { string _1 = JWTHelper.Instance.CreateToken(name, role); context.Response.Header.Add(HeaderTypeFactory.AUTHORIZATION, _1); return 1; }
感觉登录方法对外不验证,然后写入jwt
访问http://127.0.0.1:5555/g/gettoken?name=ay&role=admin
然后就可以postman,设置header中的 Authorization,然后就可以访问了。
当然实际中,用户注册完了,给一个key,用来生成jwt
====================www.ayjs.net 杨洋 wpfui.com ayui ay aaronyang=======请不要转载谢谢了。=========
推荐您阅读更多有关于“FastHttpApi,”的文章
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Never Lost Again
[美] Bill Kilday / HarperBusiness / 2018-5-29 / USD 8.00
As enlightening as The Facebook Effect, Elon Musk, and Chaos Monkeys—the compelling, behind-the-scenes story of the creation of one of the most essential applications ever devised, and the rag-tag tea......一起来看看 《Never Lost Again》 这本书的介绍吧!