WEBAPI 增加身份验证
1,在Webapi项目下添加如下引用:
Microsoft.AspNet.WebApi.Owin
Owin
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security.OAuth
Microsoft.Owin.Security.Cookies
Microsoft.AspNet.Identity.Owin
Microsoft.Owin.Cors
2, 在项目下新建Startup类,这个类将作为owin的启动入口,添加下面的代码

3,修改 Startup类中方法
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
public class Startup{ public void Configuration(IAppBuilder app) { // 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888 ConfigAuth(app); HttpConfiguration config = new HttpConfiguration(); WebApiConfig.Register(config); app.UseCors(CorsOptions.AllowAll); app.UseWebApi(config); } public void ConfigAuth(IAppBuilder app) { OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), //获取 access_token 授权服务请求地址 AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), //access_token 过期时间 Provider = new SimpleAuthorizationServerProvider(), //access_token 相关授权服务 RefreshTokenProvider = new SimpleRefreshTokenProvider() //refresh_token 授权服务 }; app.UseOAuthAuthorizationServer(option); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); }} |
4, OAuth身份认证,新建SimpleAuthorizationServerProvider类
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider{ public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { context.Validated(); return Task.FromResult<object>(null); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); AccountService accService = new AccountService(); string md5Pwd = LogHelper.MD5CryptoPasswd(context.Password); IList<object[]> ul = accService.Login(context.UserName, md5Pwd); if (ul.Count() == 0) { context.SetError("invalid_grant", "The username or password is incorrect"); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("sub", context.UserName)); identity.AddClaim(new Claim("role", "user")); context.Validated(identity); }} |
5, 新建SimpleRefreshTokenProvider类
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
public class SimpleRefreshTokenProvider : AuthenticationTokenProvider{ private static ConcurrentDictionary<string, string> _refreshTokens = new ConcurrentDictionary<string, string>(); /// <summary> /// 生成 refresh_token /// </summary> public override void Create(AuthenticationTokenCreateContext context) { context.Ticket.Properties.IssuedUtc = DateTime.UtcNow; context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(60); context.SetToken(Guid.NewGuid().ToString("n")); _refreshTokens[context.Token] = context.SerializeTicket(); } /// <summary> /// 由 refresh_token 解析成 access_token /// </summary> public override void Receive(AuthenticationTokenReceiveContext context) { string value; if (_refreshTokens.TryRemove(context.Token, out value)) { context.DeserializeTicket(value); } }} |
6, 在要加验证的接口上加上[Authorize]标记
|
1
2
3
4
5
6
7
8
9
10
|
[Authorize]public class EmployeeController : ApiController{ //查询所有员工 [HttpGet] public IList<UC_Employee> GetAllEmps() { return new List<UC_Employee>(); }} |
7,调用api程序

8,传入参数,获取token

9,传入access_token

WEBAPI 增加身份验证的更多相关文章
- WebApi 增加身份验证 (OAuth 2.0方式)
1,在Webapi项目下添加如下引用: Microsoft.AspNet.WebApi.Owin Owin Microsoft.Owin.Host.SystemWeb Microsoft.Owin.S ...
- 关于WEB Service&WCF&WebApi实现身份验证之WebApi篇
之前先后总结并发表了关于WEB Service.WCF身份验证相关文章,如下: 关于WEB Service&WCF&WebApi实现身份验证之WEB Service篇. 关于WEB S ...
- 关于WEB Service&WCF&WebApi实现身份验证之WCF篇(2)
因前段时间工作变动(换了新工作)及工作较忙暂时中断了该系列文章,今天难得有点空闲时间,就继续总结WCF身份验证的其它方法.前面总结了三种方法(详见:关于WEB Service&WCF& ...
- ASP.NET WEBAPI 的身份验证和授权
定义 身份验证(Authentication):确定用户是谁. 授权(Authorization):确定用户能做什么,不能做什么. 身份验证 WebApi 假定身份验证发生在宿主程序称中.对于 web ...
- c# WebApi之身份验证:Basic基础认证
为什么需要身份认证 身份认证是为了提高接口访问的安全性,如果没有身份验证,那么任何匿名用户只要知道服务器的url,就可以随意访问服务器,从而访问或者操作数据库,这会是很恐怖的事. 什么是Basic基础 ...
- 关于WEB Service&WCF&WebApi实现身份验证之WCF篇(1)
WCF身份验证一般常见的方式有:自定义用户名及密码验证.X509证书验证.ASP.NET成员资格(membership)验证.SOAP Header验证.Windows集成验证.WCF身份验证服务(A ...
- WebApi 登录身份验证
前言:Web 用户的身份验证,及页面操作权限验证是B/S系统的基础功能,一个功能复杂的业务应用系统,通过角色授权来控制用户访问,本文通过Form认证,Mvc的Controller基类及Action的权 ...
- 关于WEB Service&WCF&WebApi实现身份验证之WEB Service篇
在这个WEB API横行的时代,讲WEB Service技术却实显得有些过时了,过时的技术并不代表无用武之地,有些地方也还是可以继续用他的,我之所以会讲解WEB Service,源于我最近面试时被问到 ...
- asp.net webapi 自定义身份验证
/// <summary> /// 验证 /// </summary> /// Account API账号 /// TimeStamp 请求时间 /// Sign 所有请求参数 ...
随机推荐
- Springboot2.x整合logback slf4j
Springboot项目的pom里引入的parent <parent> <groupId>org.springframework.boot</groupId> &l ...
- Java高级篇反射和注解
反射是什么? 反射的作用?能带来什么好处? 反射的使用? 注解的使用? 注解和反射配合实战...
- Vue3 为何使用 Proxy 实现数据监听
博客地址:https://ainyi.com/93 vue3 响应式数据放弃了 Object.defineProperty,而使用Proxy来代替它 我们知道,在 vue2 中,实现数据监听是使用Ob ...
- 2020-05-31:假如Redis里面有1亿个key,其中有10w个key是以某个固定的已知的前缀开头的,如何将它们全部找出来?
福哥答案2020-05-31: 使用keys指令可以扫出指定模式的key列表.对方接着追问:如果这个redis正在给线上的业务提供服务,那使用keys指令会有什么问题?这个时候你要回答redis关键的 ...
- C#开发笔记之01-为什么开源框架会大量的使用protected virtual?
C#开发笔记概述 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/957 访问. 我们在很多开源框架中会经常看到prote ...
- 题解 洛谷 P3332
题目描述 权值线段树套线段树板子题 首先观察题目,判断为二维偏序问题 操作1为区间修改,所以一定是外部线段树维护权值,内部线段树维护所在区间,否则时间复杂度爆炸qwq 为方便查找,哈希时我采用哈希每个 ...
- 解决React路由跳转时出现的红色警告: Warning: Failed prop type: Invalid prop `component` of type `object` supplied to `Route`, expected `function`.
一.报警如图: 二.查找路由版本 我使用路由版本是4.3.1的,然后我测试所有4.0+版本都会出现以上警告. 三.未解决前的代码 三.我又解读了一下报警告内容的大致意思:就是props需要通过函数返回 ...
- 什么是BFC?看这一篇就够了
BFC 定义 BFC(Block formatting context)直译为"块级格式化上下文".它是一个独立的渲染区域,只有Block-level box参与, 它规定了内部的 ...
- 网络基础之IP地址
一.IP地址 1.IP地址就是给互联网上每一台主机 (或路由器)每一个接口分配一个在全世界范围内是唯一的32位二进制的地址标识符.现在由互联网名字和数字分配机构ICANN进行分配. 2.转换成十进制 ...
- java基础-04:标识符与关键字
在Java中,标识符是代表你对程序中某个方法或变量赋予的一个名称,而这个名称不能是关键字 关键字: