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- ...
随机推荐
- log4net 自定义日志级别记录多个日志
程序中原来只记录一个日志,现在我要写一个用户操作日志,需要与原来的日志分开,在config文件中一阵折腾无果(要么写不全,要么写重了,反正没办法完美分离,要么与现存代码没办法完美兼容),差点放弃准备自 ...
- rsync入门使用
rsync是用来同步文件的,但是是基于增量同步的,也就是说每次同步时不需要把全部文件数据都传输过去,只需要将不相同的部分(也就是说增量差异内容)传输过去. 其基本命令格式为rsync [option] ...
- CodeBlocks中去掉下划线的方法
[问题] 如上图所示,某些字符下面会出现红色下划线,看着挺难受后的,决定想办法去掉. 这是拼写检查插件在作怪,把这个插件屏蔽掉就OK了. [步骤一]点击[插件]下的[管理插件]按钮 [步骤二]点击[管 ...
- Go语言编程 (许式伟 等 著)
第1章 初识Go语言 1.1 语言简史 1.2 语言特性 1.2.1 自动垃圾回收 1.2.2 更丰富的内置类型 1.2.3 函数多返回值 1.2.4 错误处理 1.2.5 匿名函数和闭包 1.2.6 ...
- mysql 的 docker 镜像使用
mysql 的 docker 镜像使用: 下载镜像: docker pull mysql:8.0.14 运行容器: docker run -it -e MYSQL_ROOT_PASSWORD=mypw ...
- plsql远程访问数据库 解决ora-12541:TNS:无监听程序
今天在windows server 2012上安装了一个oracle 11g的数据库,但是安装 完成以后发现在我的机器上访问数据库出现错误,ora-12541:TNS:无监听程序. 后来查询了很多资料 ...
- Jmeter JDBC Request--测试数据库连接 拒绝解决方案
有时会遇到回应信息如下: 1 Cannot create PoolableConnectionFactory (Access denied for user 'root'@'10.0.1.23' (u ...
- tornado输入-get_query_argument()等 笔记
最外面的代码结构 import tornado.web import tornado.ioloop import tornado.options import tornado.httpserver f ...
- Linux平台下停止后台进程脚本编写
1.场景说明 [root@master ~]# jps -m 33050 Jps -m 3299 NameNode 3747 ResourceManager 9028 ConsoleConsumer ...
- 数据仓库专题(21):Kimball总线矩阵说明-官方版
一.前言 Over the years, I have found that a matrix depiction of the data warehouse plan is a pretty goo ...