OAuth2.0资料

初衷:一直想整理授权系列demo,让自己项目高端大尚,列出新手授权系列,帮助小白程序员不用在为授权头疼

OAuth 允许用户提供一个令牌,而不是用户名和密码来访问他们存放在特定服务提供者的数据。每一个令牌授权一个特定的网站(例如,视频编辑网站)在特定的时段(例如,接下来的 2 小时内)内访问特定的资源(例如仅仅是某一相册中的视频)。这样,OAuth 让用户可以授权第三方网站访问他们存储在另外服务提供者的某些特定信息,而非所有内容。

以上概念来自:https://zh.wikipedia.org/wiki/OAuth

详细理论知识,参考文章如下文章,本文章重在实践

1.http://www.cnblogs.com/lanxiaoke/p/6358332.html

2.https://www.cnblogs.com/selimsong/p/8037717.html

3.http://www.cnblogs.com/xishuai/p/aspnet-webapi-owin-oauth2.html

项目实践开发

步骤1和步骤2都行,看官乐意就行

步骤1

通过NuGet安装

Microsoft.Owin.Security.OAuth

Owin Microsoft.Owin.Host.SystemWeb(重点)

步骤2

Owin Microsoft.Owin.Host.SystemWeb(重点)

Microsoft.Owin.Security.OAuth

Microsoft.Owin.Security.Cookies(可忽略)

Microsoft.AspNet.Identity.Owin

重点在于步骤1少了一个核心dll,少了这个核心dll无法启动部署owin

新增Startup.cs

  1. [assembly: OwinStartup(typeof(OAuth2.Startup))]
  2. namespace OAuth2
  3. {
  4. public partial class Startup
  5. {
  6. public void Configuration(IAppBuilder app)
  7. {
  8. ConfigureAuth(app);
  9. }
  10. }
  11. }

Owin Microsoft.Owin.Host.SystemWeb 通过这个dll,程序启动时候注册,如果不引用,该方法不会生效,看官可以打个断点试一试

新增Startup.Auth.cs

  1. namespace OAuth2
  2. {
  3. public partial class Startup
  4. {
  5. public void ConfigureAuth(IAppBuilder app)
  6. {
  7. app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
  8. {
  9. //从url中获取token,兼容hearder方式
  10. //Provider = new QueryStringOAuthBearerProvider("access_token")
  11. });
  12. var OAuthOptions = new OAuthAuthorizationServerOptions
  13. {
  14. AllowInsecureHttp = true,
  15. TokenEndpointPath = new PathString("/token"), //获取 access_token 认证服务请求地址
  16. AuthorizeEndpointPath = new PathString("/authorize"), //获取 authorization_code 认证服务请求地址
  17. AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(), //access_token 过期时间
  18.  
  19. Provider = new OpenAuthorizationServerProvider(), //access_token 相关认证服务
  20. AuthorizationCodeProvider = new OpenAuthorizationCodeProvider(), //authorization_code 认证服务
  21. RefreshTokenProvider = new OpenRefreshTokenProvider() //refresh_token 认证服务
  22. };
  23.  
  24. app.UseOAuthBearerTokens(OAuthOptions); //表示 token_type 使用 bearer 方式
  25.  
  26. }
  27. }
  28.  
  29. public class QueryStringOAuthBearerProvider : OAuthBearerAuthenticationProvider
  30. {
  31. readonly string _name;
  32.  
  33. public QueryStringOAuthBearerProvider(string name)
  34. {
  35. _name = name;
  36. }
  37.  
  38. public override Task RequestToken(OAuthRequestTokenContext context)
  39. {
  40. var value = context.Request.Query.Get(_name);
  41.  
  42. if (!string.IsNullOrEmpty(value))
  43. {
  44. context.Token = value;
  45. }
  46.  
  47. return Task.FromResult<object>(null);
  48. }
  49. }
  50.  
  51. }

眼光犀利的同学肯定注意到这两个类名相同,命名空间也相同,为什么没有报错  请注意关键字 partial

OpenAuthorizationServerProvider示例代码  详细见demo,只提代码需要注意地方

  1. /// <summary>
  2. /// 验证 client 信息
  3. /// </summary>
  4. public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
  5. {
  6. string clientId;
  7. string clientSecret;
  8. if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
  9. {
  10. context.TryGetFormCredentials(out clientId, out clientSecret);
  11. }
  12.  
  13. if (clientId != "xishuai" || clientSecret != "")
  14. {
  15. context.SetError("invalid_client", "client or clientSecret is not valid");
  16. return;
  17. }
  18. context.Validated();
  19. }

  1. public string BaseString()
  2. {
  3. string clientId = "xishuai";
  4. string clientSecret = "";
  5. return Convert.ToBase64String(Encoding.ASCII.GetBytes(clientId + ":" + clientSecret));
  6. }
  1. 验证生效如图 按照如下格式 key:value,然后base64编码
  1. context.TryGetBasicCredentials 否则解析不了 验证不通过

OpenAuthorizationCodeProvider示例代码 详细见demo

OpenRefreshTokenProvider 示例代码 详细见demo

新增ValueController.cs

  1. public class ValueController : ApiController
  2. {
  3. // GET api/values access_token验证才能访问
  4. [Authorize]
  5. [HttpGet]
  6. public IEnumerable<string> Index()
  7. {
  8. return new string[] { "value1", "value2" };
  9. }

  10. //获取授权code
  11. [HttpGet]
  12. [Route("api/authorization_code")]
  13. public HttpResponseMessage Get(string code)
  14. {
  15. return new HttpResponseMessage()
  16. {
  17. Content = new StringContent(code, Encoding.UTF8, "text/plain")
  18. };
  19. }
  20.  
  21. }

新增OAuthon2Controller.cs

  1. public class OAuthon2Controller : Controller
  2. {
  3. //根据你项目端口
  4. private const string HOST_ADDRESS = "http://localhost:60903";
  5.  
  6. // GET: OAuthon2 直接获取授权code链接,方便获取code
  7. public string Index()
  8. {
  9. string clientId = "xishuai";
  10. string url = $"{HOST_ADDRESS}/authorize?grant_type=authorization_code&response_type=code&client_id={clientId}&redirect_uri={HttpUtility.UrlEncode($"{HOST_ADDRESS}/api/authorization_code")}";
  11. return url;
  12. }
  13.  
  14. }

根据获取的url,   在将红色部分url复制出来到浏览器中可以获取到code

现在code有了  将获取access_token

grant_type:authorization_code

code:图上红色url返回给你的

client_id:xishuai 可以理解为appid  自定义,因为代码中固定了,你可以改

redirect_uri:这个链接你也能改的,接受code 在ValueController.cs   (action:api/authorization_code)

http://localhost:60903/api/authorization_code

这个地方需要注意  需要和你获取code redirect_uri保持一致就行

string url = $"{HOST_ADDRESS}/authorize?grant_type=authorization_code&response_type=code&client_id={clientId}&redirect_uri={HttpUtility.UrlEncode($"{HOST_ADDRESS}/api/authorization_code")}";

然后你就拿到access_token 去调用 api/Value/Index

如果这个地方你输入错,会获取失败

Authorization     Bearer后面空格 在输入access_token

源码下载

ASP.NET OAuth 2.0 新手上路的更多相关文章

  1. ASP.NET WebApi OWIN 实现 OAuth 2.0

    OAuth(开放授权)是一个开放标准,允许用户让第三方应用访问该用户在某一网站上存储的私密的资源(如照片,视频,联系人列表),而无需将用户名和密码提供给第三方应用. OAuth 允许用户提供一个令牌, ...

  2. IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架学习保护API

    IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架学习之保护API. 使用IdentityServer4 来实现使用客户端凭据保护ASP.N ...

  3. [转]An introduction to OAuth 2.0 using Facebook in ASP.NET Core

    本文转自:http://andrewlock.net/an-introduction-to-oauth-2-using-facebook-in-asp-net-core/ This is the ne ...

  4. ASP.NET 中OAUTH 2.0 及OPENID CONNECT的介绍

        了解以下内容对ASP.NET 5中的验证中间件应用有很大帮助! OAUTH2是目前很多大型网站都使用的对外提供开放资源接口的应用标准,比入taobao\alipay\腾讯\豆瓣等.它和目前的另 ...

  5. asp.net权限认证:OWIN实现OAuth 2.0 之客户端模式(Client Credential)

    asp.net权限认证系列 asp.net权限认证:Forms认证 asp.net权限认证:HTTP基本认证(http basic) asp.net权限认证:Windows认证 asp.net权限认证 ...

  6. asp.net权限认证:OWIN实现OAuth 2.0 之密码模式(Resource Owner Password Credential)

    asp.net权限认证系列 asp.net权限认证:Forms认证 asp.net权限认证:HTTP基本认证(http basic) asp.net权限认证:Windows认证 asp.net权限认证 ...

  7. asp.net权限认证:OWIN实现OAuth 2.0 之授权码模式(Authorization Code)

    asp.net权限认证系列 asp.net权限认证:Forms认证 asp.net权限认证:HTTP基本认证(http basic) asp.net权限认证:Windows认证 asp.net权限认证 ...

  8. asp.net权限认证:OWIN实现OAuth 2.0 之简化模式(Implicit)

    asp.net权限认证系列 asp.net权限认证:Forms认证 asp.net权限认证:HTTP基本认证(http basic) asp.net权限认证:Windows认证 asp.net权限认证 ...

  9. ASP.NET WebApi OWIN 实现 OAuth 2.0(自定义获取 Token)

    相关文章:ASP.NET WebApi OWIN 实现 OAuth 2.0 之前的项目实现,Token 放在请求头的 Headers 里面,类似于这样: Accept: application/jso ...

随机推荐

  1. jenkins之构建触发器

    build whenever a snapshot dependency is built 当job依赖的快照版本被build时,执行本job. build after other projects ...

  2. 使用docker快速搭建环境-安装mysql

    install docker sudo apt-get install -y docker.io download mysql sudo docker pull mysql start mysql s ...

  3. Vim中异步语法检查ale配置

    注意 在设置let g:ale_sign_error = '✗'和let g:ale_sign_warning = '⚡'这些时,可能vim不让你保存,提示fenc这个东西. 所以,为了保险起见,你最 ...

  4. zookeeper无故挂掉,启动不起来的问题

    一台测试的服务器重启后,运行zookeeperd的启动脚本显示启动成功: [plain] view plain copy     JMX enabled by default Using config ...

  5. HDFS NameNode HA 部署文档

    简介: HDFS High Availability Using the Quorum Journal Manager Hadoop 2.x 中,HDFS 组件有三个角色:NameNode.DataN ...

  6. springmvc 类型转换器 数据回显及提示信息

    处理器的写法: 类型转换器的写法: 类型转换器在springmvc.xml中的配置如下: index.jsp的写法:

  7. helm 安装 spinnaker

    $ curl -Lo values.yaml https://raw.githubusercontent.com/kubernetes/charts/master/stable/spinnaker/v ...

  8. Excel VBA入门(八)单元格边框

    本文基于以下文件 http://pan.baidu.com/s/1nvJtsu9 (部分)内容预览: 1. 边框样式 Sub cell_format() Dim sht As Worksheet Di ...

  9. PLSQL Developer工具的使用

    1.运行 2.字体大小 导入csv文件. 任何工具都有失败的可能, 这个时候,也失败了. 当然还有另一种可能,文件被人为改过了,括号改过了,就即使使用下面的kettle工具也没用了.这时可以导出文件对 ...

  10. weblogic 初始化

    weblogic无法启动,或是忘记了登陆密码,需要初始化,可以删除weblogic配置然后重新生成配置.步骤如下 1> 找到weblogic的启动路径,打开jdeveloper,run后,查看日 ...