用到了如鹏的代码

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. Scala中的Map使用例子

    Map结构是一种非常常见的结构,在各种程序语言都有对应的api,由于Spark的底层语言是Scala,所以有必要来了解下Scala中的Map使用方法. (1)不可变Map特点: api不太丰富 如果是 ...

  2. The difference among ioctl, unlocked_ioctl and compat_ioctl (RT)

    Meta-answer: All the raw stuff happening to the Linux kernel goes through lkml (the Linux kernel mai ...

  3. Be Careful When Using Bit Field

    Below illustration is based on MSP430, IAR. See the implementation below. typedef struct { uint8_t g ...

  4. 04C++const增强、枚举的增强

    #include <iostream> int main(void) { //const定义常量--->const意味着只读 const int a; int const b; // ...

  5. AspNetCore+Swagger 生成Model描述

    AspNetCore+Swagger 生成Model 描述 前言: 本篇文章实现是基于上一篇文章,进下补充:多余的就不多说了,只是为了实现Model的描述生成:有兴趣的可以结合上一篇的进行实现:如有更 ...

  6. html+css常用总结

    一,HTML结构: 1,DOCTYPE 2,head: title:网站的标题 meta charset 3,body: 二,HTML标签: 块状元素和内联元素: 常见的块级元素有:div.p.add ...

  7. node api 之:stream - 流

    stream 模块可以通过以下方式使用: const stream = require('stream'); 流可以是可读的.可写的.或者可读可写的. 所有的流都是 EventEmitter 的实例. ...

  8. base64 base64urlsafe

    1. base64 不算是加密算法,只能说是一种转码.使用64 个可见的字符来代替 ASCII码 中的256 个字符. 2. ASCII码占用一个字节,可以有0-255共256个取值.前128个为常用 ...

  9. Fixed-point multiplication (C166 A*B/B)

    I want to multiply two fixed point numbers. After the multiplication I have to shift the result so t ...

  10. Centos6 rpm 安装mysql5.5(转)

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/macfac/article/details/51868712 0. 到官网下载好,想要安装的rpm包 ...