WebApi 增加身份验证 (OAuth 2.0方式)
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类中方法
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类
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类
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]标记
[Authorize]
public class EmployeeController : ApiController
{
//查询所有员工
[HttpGet]
public IList<UC_Employee> GetAllEmps()
{
return new List<UC_Employee>();
}
}
7,调用api程序

8,传入参数,获取token

9,传入access_token

WebApi 增加身份验证 (OAuth 2.0方式)的更多相关文章
- WEBAPI 增加身份验证
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& ...
- 关于WEB Service&WCF&WebApi实现身份验证之WCF篇(1)
WCF身份验证一般常见的方式有:自定义用户名及密码验证.X509证书验证.ASP.NET成员资格(membership)验证.SOAP Header验证.Windows集成验证.WCF身份验证服务(A ...
- ASP.NET WEBAPI 的身份验证和授权
定义 身份验证(Authentication):确定用户是谁. 授权(Authorization):确定用户能做什么,不能做什么. 身份验证 WebApi 假定身份验证发生在宿主程序称中.对于 web ...
- c# WebApi之身份验证:Basic基础认证
为什么需要身份认证 身份认证是为了提高接口访问的安全性,如果没有身份验证,那么任何匿名用户只要知道服务器的url,就可以随意访问服务器,从而访问或者操作数据库,这会是很恐怖的事. 什么是Basic基础 ...
- WebApi 登录身份验证
前言:Web 用户的身份验证,及页面操作权限验证是B/S系统的基础功能,一个功能复杂的业务应用系统,通过角色授权来控制用户访问,本文通过Form认证,Mvc的Controller基类及Action的权 ...
- ASP.NET WebAPI 集成 Swagger 启用 OAuth 2.0 配置问题
在 ASP.NET WebAPI 集成 Swagger 后,由于接口使用了 IdentityServer 做的认证,调试起来很不方便:看了下 Swashbuckle 的文档 ,是支持 OAuth2.0 ...
- 关于WEB Service&WCF&WebApi实现身份验证之WEB Service篇
在这个WEB API横行的时代,讲WEB Service技术却实显得有些过时了,过时的技术并不代表无用武之地,有些地方也还是可以继续用他的,我之所以会讲解WEB Service,源于我最近面试时被问到 ...
随机推荐
- github PageHelper使用PageInfo数据错乱问题
如果出现了数据错乱,检查一下代码是否正确 PageHelper.start(1,10); List<MyEntity> lists = mapper.query(); PageInfo&l ...
- node note
1.关于next() next()函数接受一个Error对象,在判断错误时,返回这个next()函数,并传入自定义的Error对象可以被向下捕捉,你也可以自定义统一捕捉错误Error的中间件,在app ...
- ZigZag Conversion 之字形转换字符串
1.题目 The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows ...
- wget -r -c -nd
wget -r -c -nd -r 递归下载 -c 断点续传 -nd 不创建目录, wget默认会创建一个目录 -l1 (L one) 递归一层,只下载指定文件夹中的内容, 不下载下一级目录中的.–n ...
- Eclipse设置类,方法注释模版
首先打开Eclipse配置选项:Window->Preference->Java->Code Style->Code Template 配置Comments下的每个选项的模版, ...
- Spring MVC随笔记录
根据https://blog.csdn.net/abc997995674/article/details/80353410整理 @ModelAttribute 可以用在方法.方法参数上,也可以和@re ...
- 字节、字、bit、Byte、byte的关系区分
1.位(bit) 来自英文bit,音译为"比特", 表示二进制位.位是计算机内部数据存储最小单位,11010100是一个8位二进制数.一个二进制位只可以表示 ...
- python--第二十三天总结(一对多和多对多)
Django 的 ORM 有多种关系:一对一,多对一,多对多. 各自定义的方式为 : 一对一: OneToOneField 多对一: ForeignKey 多 ...
- SSM商城开发学习
功能模块:前端:门户.商品搜索.商品展示.购物车.注册&登录 后端:商品管理.订单管理.cms 上线,bug,维护,停到上线,维护,打包,上线 某一个模块出现bug,停到这个模块 tomcat ...
- Shell中sed----学习
sed原理及使用 目录 前言 一.简介 二.处理流程 三.命令选项options 四.pattern 1. 模式空间 2. 模式空间的转换 3. 地址匹配 五.procedure 1. 替换命令: s ...