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方式)的更多相关文章

  1. WEBAPI 增加身份验证

    1,在Webapi项目下添加如下引用: Microsoft.AspNet.WebApi.Owin Owin Microsoft.Owin.Host.SystemWeb Microsoft.Owin.S ...

  2. 关于WEB Service&WCF&WebApi实现身份验证之WebApi篇

    之前先后总结并发表了关于WEB Service.WCF身份验证相关文章,如下: 关于WEB Service&WCF&WebApi实现身份验证之WEB Service篇. 关于WEB S ...

  3. 关于WEB Service&WCF&WebApi实现身份验证之WCF篇(2)

    因前段时间工作变动(换了新工作)及工作较忙暂时中断了该系列文章,今天难得有点空闲时间,就继续总结WCF身份验证的其它方法.前面总结了三种方法(详见:关于WEB Service&WCF& ...

  4. 关于WEB Service&WCF&WebApi实现身份验证之WCF篇(1)

    WCF身份验证一般常见的方式有:自定义用户名及密码验证.X509证书验证.ASP.NET成员资格(membership)验证.SOAP Header验证.Windows集成验证.WCF身份验证服务(A ...

  5. ASP.NET WEBAPI 的身份验证和授权

    定义 身份验证(Authentication):确定用户是谁. 授权(Authorization):确定用户能做什么,不能做什么. 身份验证 WebApi 假定身份验证发生在宿主程序称中.对于 web ...

  6. c# WebApi之身份验证:Basic基础认证

    为什么需要身份认证 身份认证是为了提高接口访问的安全性,如果没有身份验证,那么任何匿名用户只要知道服务器的url,就可以随意访问服务器,从而访问或者操作数据库,这会是很恐怖的事. 什么是Basic基础 ...

  7. WebApi 登录身份验证

    前言:Web 用户的身份验证,及页面操作权限验证是B/S系统的基础功能,一个功能复杂的业务应用系统,通过角色授权来控制用户访问,本文通过Form认证,Mvc的Controller基类及Action的权 ...

  8. ASP.NET WebAPI 集成 Swagger 启用 OAuth 2.0 配置问题

    在 ASP.NET WebAPI 集成 Swagger 后,由于接口使用了 IdentityServer 做的认证,调试起来很不方便:看了下 Swashbuckle 的文档 ,是支持 OAuth2.0 ...

  9. 关于WEB Service&WCF&WebApi实现身份验证之WEB Service篇

    在这个WEB API横行的时代,讲WEB Service技术却实显得有些过时了,过时的技术并不代表无用武之地,有些地方也还是可以继续用他的,我之所以会讲解WEB Service,源于我最近面试时被问到 ...

随机推荐

  1. POIUtils 读取 poi

    依赖: <!-- ############ poi ############## --> <dependency> <groupId>org.apache.poi& ...

  2. pyqt5 -—-布局管理

    绝对布局 例如: 我们使用move()方法定位了每一个元素,使用x.y坐标.x.y坐标的原点是程序的左上角. lbl1 = QLabel('Zetcode', self) lbl1.move(15, ...

  3. 记录小白实习生的HashMap源码 put元素 的学习和一些疑问

    首先看HashMap存储结构 transient Node<K,V>[] table; static class Node<K,V> implements Map.Entry& ...

  4. Unable to locate appropriate constructor on class报错

    在项目开发中,使用Hibernate里的JPA criteria查询,但是在写完之后使用时,会报错:Unable to locate appropriate constructor on class, ...

  5. 每日一练之贪心算法(P2587)

    洛谷——P2587 [ZJOI2008]泡泡堂 两队人马进行比赛, 战斗力值各有差异, 如果一方获胜得两分,战平各得一分,失败不得分,求可取得的最佳战绩与最差战绩. 思路:1)最强的打得过最强的就直接 ...

  6. hadoop streaming 中跑python程序,自定义模块的导入

    今天在做代码重构,以前将所有python文件放到一个文件夹下,上传到hadoop上跑,没有问题:不过随着任务的复杂性增加,感觉这样甚是不合理,于是做了个重构,建了好几个包存放不同功能的python文件 ...

  7. hadoop fs -text和hadoop fs -cat的区别(转)

    转自:https://www.jianshu.com/p/4462613d3f57

  8. Harbor私有镜像仓库(上)

    上图配置为工作环境 特别注意:win10现在不允许使用私有ca证书,到时登录浏览器会失败,可以选用火狐浏览器. 创建自己的CA证书 openssl req -newkey rsa:4096 -node ...

  9. SpringCloud-day05-服务调用Ribbon

    6.服务调用Ribbon 6.1Ribbon简介 前面讲了eureka服务注册与发现,但是结合eureka集群的服务调用并没有谈到.这里就要用到Ribbon,结合eureka,来实现服务的调用: Ri ...

  10. python 编程

    1.一个str A,列表B的所有元素都在A中时返回True A = 'HeooWoldHomeUbuntuCentOSFedora'B = ['Ubuntu', 'CentOS', 'Home', ' ...