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 所有请求参数 ...
随机推荐
- Surface Pro 6 遇到的一系列问题
当屏幕很烫的时候,触摸屏会部分失灵,越烫越明显,但是 Surface Pen 仍然可以使用,建议这个时候关机,等它冷静了再开机 不过不排除更新导致的触控失灵(新的更新没有考虑到老的硬件,微软也许之后永 ...
- redis(二)redis的主从模式和集群模式
redis(二)redis的主从模式和集群模式 主从模式 集群模式 主从模式 redis的主从模式,指的是针对多台redis实例时候,只存在一台主服务器master,提供读写的功能,同时存在依附在这台 ...
- 创建shell脚本文件
简单来说脚本就是将需要执行的命令保存到文本中,按照顺序(由上往下执行),它是解释型的,不需要 编译 脚本格式 #!/bin/bash或者#!/bin/env bash开头 第一个shell脚本:hel ...
- 微信小程序携带参数跳转页面/获取页面栈
页面跳转携带参数(以传递两个参数为例) a.wxml 页面传递 1 <navigator url="/pages/b/b?id=1&sid='289'"> &l ...
- Exception processing template "success": Exception parsing document: template="success",
代码很简单 package com.kele.controller; import org.springframework.stereotype.Controller;import org.sprin ...
- 【AHOI 2015】 小岛 - 最短路
描述 西伯利亚北部的寒地,坐落着由 N 个小岛组成的岛屿群,我们把这些小岛依次编号为 1 到 N . 起初,岛屿之间没有任何的航线.后来随着交通的发展,逐渐出现了一些连通两座小岛的航线.例如增加一条在 ...
- 【算法•日更•第五十期】二分图(km算法)
▎前言 戳开这个链接看看,惊不惊喜,意不意外?传送门. 没想到我的博客竟然被别人据为己有了,还没办法投诉. 这年头写个博客太难了~~~ 之前小编写过了二分图的一些基础知识和匈牙利算法,今天来讲一讲km ...
- 深入了解Promise对象,写出优雅的回调代码,告别回调地狱
深入浅出了解Promise 引言 正文 一.Promise简介 二.Promise的三种状态 三.函数then( ) 四.函数catch( ) 五.函数finally( ) 六.函数all( ) 七. ...
- 使用 codeblocks 编写C++ udp组播程序遇到的问题
编译错误 会出现好多undefined reference to'WSAStartup to@8之类的错误,都是undefind开头的 解决方法: Settings -> Compiler se ...
- Jmeter 常用函数(30)- 详解 __if
如果你想查看更多 Jmeter 常用函数可以在这篇文章找找哦 https://www.cnblogs.com/poloyy/p/13291704.html 作用 判断给定条件是否成立 语法格式 ${_ ...