各种语言实现的oauth认证: http://oauth.net/code/

上一篇文章介绍了如何使用基本的http认证来实现asp.net web api的跨平台安全认证。 这里说明一个如何使用oauth实现的认证。oauth大家可能不陌生。那么这里需要注意的是我们使用的是.net平台一个比较好的开源oauth库。 DOTNETOPENAUTH。

就像上图所示,我们需要一个ISSSUE Server来给我们一个token,然后再去资源服务器请求资源,也就是Web API Server。

首先在oAuthIssuer服务端我们需要实现一个DotNetOpenAuth的接口:IAuthorizationServer

对接口的实现:

public class OAuth2Issuer : IAuthorizationServer{private readonly IssuerConfiguration _configuration;public OAuth2Issuer(IssuerConfiguration configuration){if (configuration == null) throw new ArgumentNullException("configuration");_configuration = configuration;}public RSACryptoServiceProvider AccessTokenSigningKey{get{return (RSACryptoServiceProvider)_configuration.SigningCertificate.PrivateKey;}}public DotNetOpenAuth.Messaging.Bindings.ICryptoKeyStore CryptoKeyStore{get { throw new NotImplementedException(); }}public TimeSpan GetAccessTokenLifetime(DotNetOpenAuth.OAuth2.Messages.IAccessTokenRequest accessTokenRequestMessage){return _configuration.TokenLifetime;}public IClientDescription GetClient(string clientIdentifier){const string secretPassword = "test1243";return new ClientDescription(secretPassword, new Uri("http://localhost/"), ClientType.Confidential);}public RSACryptoServiceProvider GetResourceServerEncryptionKey(DotNetOpenAuth.OAuth2.Messages.IAccessTokenRequest accessTokenRequestMessage){return (RSACryptoServiceProvider)_configuration.EncryptionCertificate.PublicKey.Key;}public bool IsAuthorizationValid(DotNetOpenAuth.OAuth2.ChannelElements.IAuthorizationDescription authorization){//claims added to the tokenauthorization.Scope.Add("adminstrator");authorization.Scope.Add("poweruser");return true;}public bool IsResourceOwnerCredentialValid(string userName, string password){return true;}public DotNetOpenAuth.Messaging.Bindings.INonceStore VerificationCodeNonceStore{get{throw new NotImplementedException();}}}

在 Web API Server端,我们需要使用Http Message Handler来获取httprequest信息;并进行是否有授权认证。

 public class OAuth2Handler : DelegatingHandler{private readonly ResourceServerConfiguration _configuration;public OAuth2Handler(ResourceServerConfiguration configuration){if (configuration == null) throw new ArgumentNullException("configuration");_configuration = configuration;}protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken){HttpContextBase httpContext;string userName;HashSet<string> scope;if (!request.TryGetHttpContext(out httpContext))throw new InvalidOperationException("HttpContext must not be null.");var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer((RSACryptoServiceProvider)_configuration.IssuerSigningCertificate.PublicKey.Key,(RSACryptoServiceProvider)_configuration.EncryptionVerificationCertificate.PrivateKey));var error = resourceServer.VerifyAccess(httpContext.Request, out userName, out scope);if (error != null)return Task<HttpResponseMessage>.Factory.StartNew(error.ToHttpResponseMessage);var identity = new ClaimsIdentity(scope.Select(s => new Claim(s, s)));if (!string.IsNullOrEmpty(userName))identity.Claims.Add(new Claim(ClaimTypes.Name, userName));httpContext.User = ClaimsPrincipal.CreateFromIdentity(identity);Thread.CurrentPrincipal = httpContext.User;return base.SendAsync(request, cancellationToken);}}

这里的ResourceServerConfiguration 我们是使用加密证书的。

客户端调用代码:

调用API获取数据之前需要从IssueServer获取Token。

GetAccessToken:

看一下Token信息:

{"access_token":"gAAAAIoUBVBrZ5jAxe5XeTgnJ8mGwwKsCReknueg4gLGlDQ77lR1yPfxt0yNfWLCBT7hxnHjRjuEwDTJ3J1YAnqML4MIgQg8A2cz2bs0EnxvCMfKnayKEesRM-lxLTFbWMpSxe2Xvjm61IbaXjrMkYDRMnV4Do8-7132tiOLIv02WOGlJAEAAIAAAACJ8F3SsE6cTI1XsioW_xOxHeESDzG16y01Gxm3HikYFUC3XIdekpPw0yMB4tavPmUj-kRyC1halbUX7JKf-Dihm6Ou5mexe9lcYTr9or_kH7WcDN5ZCryUK3OaecvwwjQVr5o9XD2ZyZSNDCNhVRFc5ypvP85zZCBW1KJkP3OTCV4AkMN-ROvgI8jxutYdsLLN-YbB7Ot5iypzWWbW0QxiwOzMEqG9nVtPwnIWOUMOvW5KbiELELhgjap60mwHzGrHG4TtA4jrNy8S9zjixO_q-FrgpAuC06CkSH-R4w9yPCLLDc9m3UoAnknFjd4PUbWLxCvlBpEK2sg03ENa0EOKzc2O5fEic9P-BiYt6afMwTgLkJlGBBjmCBpGZMkfLTw","token_type":"bearer","expires_in":"300","scope":"http:\/\/localhost\/ adminstrator poweruser"}

客户端调用:

http://www.cnblogs.com/n-pei/archive/2012/05/29/2524673.html

Asp.Net MVC 4 Web API 中的安全认证-使用OAuth相关推荐

  1. 转-Asp.Net MVC及Web API框架配置会碰到的几个问题及解决方案

    前言 刚开始创建MVC与Web API的混合项目时,碰到好多问题,今天拿出来跟大家一起分享下.有朋友私信我问项目的分层及文件夹结构在我的第一篇博客中没说清楚,那么接下来我就准备从这些文件怎么分文件夹说 ...

  2. Asp.Net MVC及Web API添加身份验证及错误处理的过滤器

    先说身份验证的问题.无论是mvc还是api都有一个安全性的问题,未通过身份验证的人能不能访问的问题.我们新一个空项目时,默认是没有身份验证的,除非你在控制器类或者方法上面加上Authorize属性才会 ...

  3. 架构设计(ASP.NET MVC+Knockout+Web API+SignalR)

    最近忙于重构项目的架构设计,没有时间发博客,也没有时间回复邮件及博文评论,忘各位见谅: 今天先发布架构设计图,同样没有时间写相关的介绍也没有时间回复评论,所以就不发在首页,希望给看到的朋友一些参考,同 ...

  4. Asp.Net中WebForm与MVC,Web API模式对比

    webform,web mvc和web api都是asp.net官方的三套框架,想对比下三者的关系,查了下资料,web api跟web mvc基本同属一脉,只是mvc多了一个视图渲染,网上有些博客介绍 ...

  5. [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了

    园子里关于ASP.NET Core Web API的教程很多,但大多都是使用EF+Mysql或者EF+MSSQL的文章.甚至关于ASP.NET Core Web API中使用Dapper+Mysql组 ...

  6. (四)Asp.net web api中的坑-【api的返回值】

    (四)Asp.net web api中的坑-[api的返回值] 原文:(四)Asp.net web api中的坑-[api的返回值] void无返回值 IHttpActionResult HttpRe ...

  7. ASP.NET Web API中的参数绑定总结

    ASP.NET Web API中的action参数类型可以分为简单类型和复杂类型. HttpResponseMessage Put(int id, Product item) id是int类型,是简单 ...

  8. 【ASP.NET Web API教程】5.5 ASP.NET Web API中的HTTP Cookie

    5.5 HTTP Cookies in ASP.NET Web API 5.5 ASP.NET Web API中的HTTP Cookie 本文引自:http://www.asp.net/web-api ...

  9. ASP.NET Web API中的Controller

    虽然通过Visual Studio向导在ASP.NET Web API项目中创建的 Controller类型默认派生与抽象类型ApiController,但是ASP.NET Web API框架本身只要 ...

最新文章

  1. python yaml用法详解
  2. ajax核心代码提交,ajax表单在Asp.net核心提交后的RedirectToAction
  3. Mysql中怎样使用update更新某列的数据减去指定值
  4. SpaceEmacs Rock Day5 学习笔记
  5. eclipse 使用 maven 无法编译 jsp 文件的问题
  6. centos7.2编译php,CentOS7.2编译安装PHP7.2.3之史上最详细步骤。
  7. java之try catch finally
  8. 修复Winsock(转)
  9. 查看eclipse中已经安装的插件(英文版界面)
  10. linux多线程如何分配到多核上,Linux多线程编程 多核编程
  11. 对我启发最大的数学学习方法
  12. 使用Auto.js实现微信自动发朋友圈脚本
  13. 【2019-06-27】现在不杂
  14. Spring学习之浅析refresh()执行逻辑
  15. [转载]郭云深先生解说形意拳经--九要论
  16. 工作流——流程设计器
  17. Linux环境下配置虚拟ip,方法2:单网卡绑定多IP
  18. VS 点击页面自动定位到解决方案资源管理器目录位置
  19. 密码学—安全归约问题(Reduction)
  20. 键入传真服务器位置是什么意思,2014传真服务器主要功能与技术参数说明.doc

热门文章

  1. LeetCode 37. Sudoku Solver--数独求解(回溯法)--Java 3ms,Python 80ms 解法
  2. Linux环境下使用Mysql连接外部机器
  3. win8计算机上工具选项在哪,Win8.1在开始菜单中找不到“便笺”工具如何恢复
  4. android 组件导出安全,App安全检测实践基础:组件安全(二)
  5. vue点击增加class_Vuevbind动态绑定class
  6. 总结:Apache架构师30条架构原则
  7. Elasticsearch入常用RESTful API总结
  8. iOS性能优化:Instruments使用实战
  9. Python测试框架pytest(03)setup和teardown
  10. 电子计算机微机调试员,电子计算机(微机)装配调试员国家职业标准