WebApi中关于base64和jwt的联合验证
用到了如鹏的代码
jwt验证
public class MyAuthoFilterPostOrgInfoAttribute: AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
IEnumerable<string> addToken;
if (actionContext.Request.Headers.TryGetValues("addToken", out addToken))
{
string tokenStr = addToken.First();
var secret = "GQDstcKsmarcccPOuXOYg9MbeJ1XT0uFiwDVvVBrk";//不要泄露
try
{
IJsonSerializer serializer = new JsonNetSerializer();
IDateTimeProvider provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider);
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
var json = decoder.Decode(tokenStr, secret, verify: true);
//Console.WriteLine(json);
//MessageBox.Show("解密成功" + json); }
catch (TokenExpiredException)
{
//MessageBox.Show("token过期");
returnFunc(actionContext, "token过期"); }
catch (SignatureVerificationException)
{
//MessageBox.Show("签名校验失败,数据可能被篡改");
returnFunc(actionContext, "签名校验失败,数据可能被篡改");
}
catch (Exception)
{
returnFunc(actionContext, "身份验证未通过");
}
}
//base.OnAuthorization(actionContext);
} private void returnFunc(HttpActionContext actionContext,string msg)
{
ApiResult<string> result = new ApiResult<string>
{
Code = (int)HttpStatusCode.Unauthorized,
Message = msg };
string resultJson = JsonConvert.SerializeObject(result);
//context.
//actionContext.RequestContext actionContext.Response = new HttpResponseMessage
{
Content = new StringContent(resultJson, Encoding.GetEncoding("UTF-8"), "application/json"),
StatusCode = HttpStatusCode.Unauthorized
};
}
}
base64验证
public class MyAuthoFilterForGetTokenAttribute: AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
//base.OnAuthorization(actionContext);
IEnumerable<string> getToken;
if (actionContext.Request.Headers.TryGetValues("getToken", out getToken))
{
//通过base64解密
string tokenStr = getToken.First();
byte[] bytes;
string result;
try
{
bytes = System.Convert.FromBase64String(tokenStr);
result = System.Text.Encoding.UTF8.GetString(bytes);
JObject jsonModel = (JObject)JsonConvert.DeserializeObject(result);
string userName = jsonModel["userName"].ToString();
string password = jsonModel["password"].ToString();
if (userName == "admin" && password == "qwe321")
{ }
else
{
returnFunc(actionContext);
}
}
catch (Exception)
{
returnFunc(actionContext);
}
}
else
{
returnFunc(actionContext);
} } private void returnFunc(HttpActionContext actionContext)
{
ApiResult<string> result = new ApiResult<string>
{
Code = (int)HttpStatusCode.Unauthorized,
Message = "未授权" };
string resultJson = JsonConvert.SerializeObject(result);
//context.
//actionContext.RequestContext actionContext.Response = new HttpResponseMessage
{
Content = new StringContent(resultJson, Encoding.GetEncoding("UTF-8"), "application/json"),
StatusCode = HttpStatusCode.Unauthorized
};
}
}
controller
public class ValueController: AbpApiController
{
private readonly IOrganizationAppService _orgService; public ValueController(IOrganizationAppService orgService)
{
this._orgService = orgService;
}
[HttpGet] public async Task<string> GetOrgInfo()
{
EntityDto<int> entity = new EntityDto<int>();
entity.Id = ;
OrganizationListDto org = new OrganizationListDto();
try
{
org = await _orgService.GetOrganizationByIdAsync(entity);
}
catch (Exception ex)
{
string ex1 = ex.ToString();
throw;
} return JsonConvert.SerializeObject(org);
}
[HttpGet]
public string Get()
{
return "OK";
} [MyAuthoFilterForGetToken]
public IHttpActionResult GetToken()
{ //返回jwt加密
double exp = (DateTime.UtcNow.AddSeconds() - new DateTime(, , )).TotalSeconds;
var payload = new Dictionary<string, object>
{
{ "userName", "admin" },
{ "password", "qwe321" },
{"exp",exp }
};
var secret = "GQDstcKsx0NHjPOuXOYg9MbeJ1XT0uFiwDVvVBrk";//不要泄露
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
string token = encoder.Encode(payload, secret);
//textBox1.Text = token; ApiResult<string> result = new ApiResult<string>
{
Code = ,
Message ="请求成功",
ReturnValue=token };
//JsonConvert.SerializeObject(result);
return Json(result);
} [HttpPost]
[MyAuthoFilterPostOrgInfo]
public async Task<IHttpActionResult> PostOrgInfo([FromBody]JObject par)
{
//var varlue11 = value;
string data = par["data"].ToString(); string dataDeal = data.Replace("\r\n ", " ").Replace("\\", " ").Trim();
List<OrganizationEditDtoForInterface> orgInfoList = JsonConvert.DeserializeObject<List<OrganizationEditDtoForInterface>>(dataDeal); //验证字段是否完整??? //验证数据重复性
foreach (var orgInfo in orgInfoList)
{ if (_orgService.CheckIsExitOrgName(orgInfo.OrgName,))
{ return Json(returnFunc((int)HttpStatusCode.Forbidden, "已存在服务商"));
} } //验证完重复性,现在开始存数据
bool isSucceed = await _orgService.CreateOrganizationForInterfaceAsync(orgInfoList); if (isSucceed)
{
return Json(returnFunc((int)HttpStatusCode.OK,"数据保存成功"));
}
else
{
return Json(returnFunc((int)HttpStatusCode.Forbidden, "数据保存失败"));
} //return "PostOrgInfo";
} public ApiResult<string> returnFunc(int statueCode,string msg)
{
ApiResult<string> result = new ApiResult<string>
{
Code = statueCode,
Message = msg };
return result;
} public string Post([FromBody] LoginModel2 model)
{
if (model.UserName=="admin"&&model.Password=="")
{
return "Ok,userName=" + model.UserName;
}
else
{
return "Bad";
} } }
WebApi中关于base64和jwt的联合验证的更多相关文章
- 在asp.net WebAPI 中 使用Forms认证和ModelValidata(模型验证)
一.Forms认证 1.在webapi项目中启用Forms认证 Why:为什么要在WebAPI中使用Forms认证?因为其它项目使用的是Forms认证. What:什么是Forms认证?它在WebAP ...
- ASP.NET Core WebAPI中使用JWT Bearer认证和授权
目录 为什么是 JWT Bearer 什么是 JWT JWT 的优缺点 在 WebAPI 中使用 JWT 认证 刷新 Token 使用授权 简单授权 基于固定角色的授权 基于策略的授权 自定义策略授权 ...
- webapi中使用token验证(JWT验证)
本文介绍如何在webapi中使用JWT验证 准备 安装JWT安装包 System.IdentityModel.Tokens.Jwt 你的前端api登录请求的方法,参考 axios.get(" ...
- webapi使用jwt做权限验证
考虑到很多公司目前并没有切换到.netcore,所有本文尝试使用.netframework下的webapi 首先使用Nuget 安装 jwt包 安装完成后,创建 jwt的帮助类 public clas ...
- webapi 中的本地登录
WebApi 身份验证方式 asp.net WebApi 中有三种身份验证方式 个人用户账户.用户可以在网站注册,也可以使用 google, facebook 等外部服务登录. 工作和学校账户.使用活 ...
- Asp.Net Core 3.1 学习3、Web Api 中基于JWT的token验证及Swagger使用
1.初始JWT 1.1.JWT原理 JWT(JSON Web Token)是目前最流行的跨域身份验证解决方案,他的优势就在于服务器不用存token便于分布式开发,给APP提供数据用于前后端分离的项目. ...
- Autofac - MVC/WebApi中的应用
Autofac前面写了那么多篇, 其实就是为了今天这一篇, Autofac在MVC和WebApi中的应用. 一.目录结构 先看一下我的目录结构吧, 搭了个非常简单的架构, IOC(web), IBLL ...
- WebAPI中无法获取Session对象的解决办法
在MVC的WebApi中默认是没有开启Session会话支持的.需要在Global中重写Init方法来指定会话需要支持的类型 public override void Init() { PostAut ...
- webapi 中使用 protobuf
相比json来说,好处是速度更快,带宽占用更小.其效果大致等于json+Gzip. 在webapi中使用protobuf的方法为: 引用nuget包 Install-Package protobuf- ...
随机推荐
- c# 自定义log4net过滤器
有时候为了实现自己想要的多个日志文件记录不同的内容,可能需要自定义log4net过滤器,比如我这里需要记录三个文件,这三个文件的内容又不能重复,多次尝试未果. 为了不更改任何现有日志代码的情况下,于是 ...
- Mybatis一(基础)
mybatis架构 1.mybatis配置 SqlMapConfig.xml,此文件作为mybatis的全局配置文件,配置了mybatis的运行环境等信息. mapper.xml文件即sql映射文件, ...
- Cassandra基础2
========================================================= gossip协议1.点对点(peer to perr)的网络通信协议,节点间地位相同 ...
- 晒一晒Jenkins那些常用插件
Jenkins插件大师 作为CI/CD的调度中心,Jenkins具有十八般武艺,目前已有1700多个插件,功能强大到似乎有点过分了.本文主要列出平时我们常用的插件. 以下这两个网站是Jenkins ...
- .Net培训班课程体系
.Net培训 第一部分:.Net基础 .Net基础:数据类型.变量.运算符.分支结构.循环结构.方法.反编译器.递归.递归算法的非递归优化: 面向对象:异常.封装继承多态.单例模式.装饰者设计模式.t ...
- 21 MRO C3算法
三十九 MRO 多继承的继承顺序 一.python2.2之前用的是 经典类的MRO继承 ①深度递归继承 从左到右 ,一条路走到黑 ②广度继承 一层一层的继承 深度继承时 ...
- Delphi 初始化的顺序
一.存储结构: 初始化单元存储在一个数组InitContext.InitTable^.UnitInfo中,其中UnitInfo是以数组的方式存储的,其中InitTable的定义为: 其中InitTab ...
- [1] 注解(Annotation)-- 深入理解Java:注解(Annotation)基本概念
转载 http://www.cnblogs.com/peida/archive/2013/04/23/3036035.html 深入理解Java:注解(Annotation)基本概念 什么是注解(An ...
- JavaScript 基本数据类型和引用类型的区别详解
js基本数据类型: js基本数据类型包括:undefined,null,number,boolean,string.基本数据类型是按值访问的,就是说我们可以操作保存在变量中的实际的值 1. 基本数据类 ...
- wcf 数值类型赋值不能的问题解决
客户端给对象int类型赋值,服务端收到值为0 网上给出的方案 1.数值型字段+isrequired属性.能解决问题,但没有说明原因.数值型默认不赋值,不科学. 2.emitdefaultvalue.没 ...