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. SpringCloud系列五:Ribbon 负载均衡(Ribbon 基本使用、Ribbon 负载均衡、自定义 Ribbon 配置、禁用 Eureka 实现 Ribbon 调用)

    1.概念:Ribbon 负载均衡 2.具体内容 现在所有的服务已经通过了 Eureka 进行了注册,那么使用 Eureka 注册的目的是希望所有的服务都统一归属到 Eureka 之中进 行处理,但是现 ...

  2. Chrome添加Axure RP插件

    之前一直用 Firefox 浏览器浏览原型文件,一直用不惯,而且用 Firefox 的唯一目的就是看原型.其他都是用 Chrome 浏览器,来回切换,各种麻烦,然后下定决心解决 Chrome 浏览器无 ...

  3. Nginx配置跨域支持功能

    跨域是前端开发中经常会遇到的问题,前端调用后台服务时,通常会遇到 No 'Access-Control-Allow-Origin' header is present on the requested ...

  4. NTP时间服务

    时间服务 NTP:Network Time Protocol 作用:用来给其他主机提供时间同步服务 NTP的配置文件 /etc/ntp.conf NTP相关的命令 date:显示/修改系统时间 hwc ...

  5. javascript中的map和reduce

    今天在看“廖雪峰官方网站”的js教程时,看到了map和reduce.其中有一个练习题是:不使用js内置的parseInt()函数,利用map和reduce操作实现一个string2int()函数(先将 ...

  6. Day08 - Ruby比一比:String的+=与concat串接

    前情提要: 在第七天我们透过比较Symbol和String,发现字串比符号多了更多方法!为了活用string method,今天我们接续前文,来探讨一题跟字串有关的题目: Ruby经典面试题目#08( ...

  7. ARTS打卡计划第二周-Algorithm

    665. 非递减数列  https://leetcode-cn.com/problems/non-decreasing-array/ 给定一个长度为 n 的整数数组,你的任务是判断在最多改变 1 个元 ...

  8. 通过ajax返回值

    通过ajax获取数据 然后使用 在console.log可以得到值 但是 返回值的在另一个ajax却没有结果为空 百度了一下 才发现少加了这句话 这样同步就可以正常使用了

  9. 【Spring】Spring3+Spring3MVCの環境構築(中)

    参考URL: https://www.cnblogs.com/lnsylt/p/10258457.html ■目録 ■環境設定 ①pom.xml <?xml version="1.0& ...

  10. centos7更改时区

    1,linux系统更换时区 2,时间同步 1,linux系统更换时区 注:# timedatectl # 查看系统时间方面的各种状态 # timedatectl list-timezones # 列出 ...