内容简介:此项目作者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,”的文章
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
企业IT架构转型之道:阿里巴巴中台战略思想与架构实战
钟华 / 机械工业出版社 / 2017-4-1 / 79
在当今整个中国社会都处于互联网转型的浪潮中,不管是政府职能单位、业务规模庞大的央企,还是面临最激烈竞争的零售行业都处于一个重要的转折点,这个转折对企业业务模式带来了冲击,当然也给企业的信息中心部门带来了挑战:如何构建IT系统架构更好地满足互联网时代下企业业务发展的需要。阿里巴巴的共享服务理念以及企业级互联网架构建设的思路,给这些企业带来了不少新的思路,这也是我最终决定写这本书的最主要原因。本书从阿......一起来看看 《企业IT架构转型之道:阿里巴巴中台战略思想与架构实战》 这本书的介绍吧!