用到了如鹏的代码

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的联合验证的更多相关文章

  1. 在asp.net WebAPI 中 使用Forms认证和ModelValidata(模型验证)

    一.Forms认证 1.在webapi项目中启用Forms认证 Why:为什么要在WebAPI中使用Forms认证?因为其它项目使用的是Forms认证. What:什么是Forms认证?它在WebAP ...

  2. ASP.NET Core WebAPI中使用JWT Bearer认证和授权

    目录 为什么是 JWT Bearer 什么是 JWT JWT 的优缺点 在 WebAPI 中使用 JWT 认证 刷新 Token 使用授权 简单授权 基于固定角色的授权 基于策略的授权 自定义策略授权 ...

  3. webapi中使用token验证(JWT验证)

    本文介绍如何在webapi中使用JWT验证 准备 安装JWT安装包 System.IdentityModel.Tokens.Jwt 你的前端api登录请求的方法,参考 axios.get(" ...

  4. webapi使用jwt做权限验证

    考虑到很多公司目前并没有切换到.netcore,所有本文尝试使用.netframework下的webapi 首先使用Nuget 安装 jwt包 安装完成后,创建 jwt的帮助类 public clas ...

  5. webapi 中的本地登录

    WebApi 身份验证方式 asp.net WebApi 中有三种身份验证方式 个人用户账户.用户可以在网站注册,也可以使用 google, facebook 等外部服务登录. 工作和学校账户.使用活 ...

  6. Asp.Net Core 3.1 学习3、Web Api 中基于JWT的token验证及Swagger使用

    1.初始JWT 1.1.JWT原理 JWT(JSON Web Token)是目前最流行的跨域身份验证解决方案,他的优势就在于服务器不用存token便于分布式开发,给APP提供数据用于前后端分离的项目. ...

  7. Autofac - MVC/WebApi中的应用

    Autofac前面写了那么多篇, 其实就是为了今天这一篇, Autofac在MVC和WebApi中的应用. 一.目录结构 先看一下我的目录结构吧, 搭了个非常简单的架构, IOC(web), IBLL ...

  8. WebAPI中无法获取Session对象的解决办法

    在MVC的WebApi中默认是没有开启Session会话支持的.需要在Global中重写Init方法来指定会话需要支持的类型 public override void Init() { PostAut ...

  9. webapi 中使用 protobuf

    相比json来说,好处是速度更快,带宽占用更小.其效果大致等于json+Gzip. 在webapi中使用protobuf的方法为: 引用nuget包 Install-Package protobuf- ...

随机推荐

  1. 浅析 阿里 OceanBase 双十一 淘宝天猫 天量交易 承载能力 原理

    我们先看看 这 2 篇文章: <秘诀!支付宝支撑双十一4200万次/秒的数据库请求峰值的技术实现>  https://mp.weixin.qq.com/s?__biz=MzI3MzEzMD ...

  2. ML(4)——逻辑回归

    Logistic Regression虽然名字里带“回归”,但是它实际上是一种分类方法,“逻辑”是Logistic的音译,和真正的逻辑没有任何关系. 模型 线性模型 由于逻辑回归是一种分类方法,所以我 ...

  3. create-react-app 搭建的项目中,让 antd 通过侧边栏导航 Menu 的 Menu.Item 控制 Content 部分的变化

    第一种:BrowserRouter把Menu和Route组给一起包起来 <Router></Router> 标签要把Menu和Route组给一起包起来 修改src/index. ...

  4. Qt中的主窗口之菜单栏

    1.Qt中的主窗口 主窗口为建立应用程序用户界面提供了一个框架 Qt开发平台中直接支持主窗口的概念 QMainWindow是Qt中主窗口的基类 QMainWindow继承于QWidget是一种容器类型 ...

  5. 【java】对象赋值给另一个对象

    对基本数据类型的赋值很简单的.基本类型存储了实际的数值,而并非指向一个对象的引用,所以在赋值的时候,是直接将一个地方的内容复制到另一个地方.对于a=b,修改b后并不会影响到a,这正是我们大多数情况下所 ...

  6. SPI 核的寄存器空间

    SPI 核的寄存器空间 寄存器的地址与定义: 寄存器描述与配置: 复位寄存器: 控制寄存器: 状态寄存器: 数据发送寄存器: 在使用DTR之前,一定要经过复位处理. 对于DTR的操作中,首先写入com ...

  7. Vivado HLS初识---阅读《vivado design suite tutorial-high-level synthesis》(2)

    Vivado HLS初识---阅读<vivado design suite tutorial-high-level synthesis>(2) 1.实验目的 2.启动命令行  将命令行切换 ...

  8. mac系统 Xcode打包ionic项目(iOS)

    一.环境搭建 1. 安装Node.js,使用node -v 查询版本号: 2. 安装ionic: $ sudo npm install -g cordova(可以指定版本,如cordova@7.0.1 ...

  9. msp430学习笔记-TA

    定时器,CCR2,CCR1三者共用一个中断向量 定时器A是一个16位的定时/计数器.它有3个捕获/比较寄存器:能支持多个时序控制.多个捕获/比较功能和多个PWM输出:有广泛的中断功能,中断可由计数器溢 ...

  10. ubuntu-docker入门到放弃(五)docker网络管理

    查看docker宿主机的网卡信息我们会发现,有一个docker0的网卡,这个网卡就是用于跟docker容器进行通讯的,这个网段跟我们docker容器的网段是一样的: #ifconfig docker容 ...