密码模式(Resource Owner Password Credentials Grant)中,用户向客户端提供自己的用户名和密码。客户端使用这些信息,向"服务商提供商"索要授权。基于之前的 IdentityServer3 实现 OAuth 2.0 授权服务【客户端模式(Client Credentials Grant)】 修改。

客户端

  1. public class Clients
  2. {
  3. public static List<Client> Get()
  4. {
  5. return new List<Client>
  6. {
  7. // no human involved
  8. new Client
  9. {
  10. ClientName = "App接口服务",
  11. ClientId = "app_test_id",
  12. Enabled = true,
  13. AccessTokenType = AccessTokenType.Reference,
  14. Flow = Flows.ClientCredentials,
  15. ClientSecrets = new List<Secret>
  16. {
  17. new Secret("F621F470-9731-4A25-80EF-67A6F7C5F4B8".Sha256())
  18. },
  19. AllowedScopes = new List<string>
  20. {
  21. "user",
  22. "order"
  23. }
  24. },
  25. // human is involved
  26. new Client
  27. {
  28. ClientName = "username client",
  29. ClientId = "irving",
  30. Enabled = true,
  31. AccessTokenType = AccessTokenType.Reference,
  32. Flow = Flows.ResourceOwner,
  33. ClientSecrets = new List<Secret>
  34. {
  35. new Secret("21B5F798-BE55-42BC-8AA8-0025B903DC3B".Sha256())
  36. },
  37. AllowedScopes = new List<string>
  38. {
  39. "user",
  40. "order"
  41. }
  42. }
  43. };
  44. }
  45. }

用户

  1. public class Users
  2. {
  3. public static List<InMemoryUser> Get()
  4. {
  5. return new List<InMemoryUser>
  6. {
  7. new InMemoryUser
  8. {
  9. Username = "irving",
  10. Password = "123456",
  11. Subject = "1",
  12. Claims = new[]
  13. {
  14. new Claim(Constants.ClaimTypes.GivenName, "Bob"),
  15. new Claim(Constants.ClaimTypes.FamilyName, "Smith")
  16. }
  17. },
  18. new InMemoryUser
  19. {
  20. Username = "bob",
  21. Password = "secret",
  22. Subject = "2"
  23. },
  24. new InMemoryUser
  25. {
  26. Username = "alice",
  27. Password = "secret",
  28. Subject = "3"
  29. }
  30. };
  31. }
  32. }

服务端配置

  1. public class Startup
  2. {
  3. /// <summary>
  4. /// 配置idsv授权服务
  5. /// </summary>
  6. /// <param name="app"></param>
  7. public void Configuration(IAppBuilder app)
  8. {
  9. var opts = new IdentityServerOptions
  10. {
  11. SiteName = "Embedded Homeinns PMS 2.0 OAuth2 Service",
  12. EnableWelcomePage = true,
  13. Factory = new IdentityServerServiceFactory()
  14. .UseInMemoryClients(Clients.Get())
  15. .UseInMemoryScopes(Scopes.Get())
  16. //.UseInMemoryUsers(new List<InMemoryUser>()),
  17. .UseInMemoryUsers(Users.Get()),
  18. RequireSsl = false,
  19. //SigningCertificate = new X509Certificate2(string.Format(@"{0}\bin\identityServer\idsrv3test.pfx", AppDomain.CurrentDomain.BaseDirectory), "idsrv3test")
  20. };
  21. app.UseIdentityServer(opts);
  22.  
  23. /*
  24. //自定义路由
  25. app.Map("/identity", idsrvApp =>
  26. {
  27. idsrvApp.UseIdentityServer(opts);
  28. });
  29. */
  30. }

控制器

  1. [Route("api/v1/values")]
  2. public class ValuesController : ApiController
  3. {
  4. public IHttpActionResult Get()
  5. {
  6. var caller = User as ClaimsPrincipal;
  7. var subjectClaim = caller.FindFirst("sub");
  8. if (subjectClaim != null)
  9. {
  10. return Json(new
  11. {
  12. message = "OK user",
  13. client = caller.FindFirst("client_id").Value,
  14. subject = subjectClaim.Value
  15. });
  16. }
  17. else
  18. {
  19. return Json(new
  20. {
  21. message = "OK computer",
  22. client = caller.FindFirst("client_id").Value
  23. });
  24. }
  25. }
  26. }

控制台

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. /*
  6. POST http://192.168.210.165/connect/token HTTP/1.1
  7. Accept: application/json
  8. Authorization: Basic YXBwX3Rlc3RfaWQ6RjYyMUY0NzAtOTczMS00QTI1LTgwRUYtNjdBNkY3QzVGNEI4
  9. Content-Type: application/x-www-form-urlencoded
  10. Host: 192.168.210.165
  11. Content-Length: 40
  12. Expect: 100-continue
  13. Connection: Keep-Alive
  14.  
  15. grant_type=client_credentials&scope=user
  16. */
  17.  
  18. /*
  19. GET http://192.168.210.165:88/api/v1/values HTTP/1.1
  20. Authorization: Bearer 9f82476751e1f8b93f1ea6df7de83b51
  21. Host: 192.168.210.165:88
  22. */
  23. var log = new LoggerConfiguration()
  24. .WriteTo
  25. .LiterateConsole(outputTemplate: "{Timestamp:HH:mm} [{Level}] ({Name:l}){NewLine} {Message}{NewLine}{Exception}")
  26. .CreateLogger();
  27.  
  28. //ClientCredentials
  29. var token = new TokenClient(
  30. "http://192.168.210.165/connect/token",
  31. "app_test_id",
  32. "F621F470-9731-4A25-80EF-67A6F7C5F4B8");
  33. var response = token.RequestClientCredentialsAsync("user").Result;
  34. var client = new HttpClient();
  35. client.SetBearerToken(response.AccessToken);
  36. log.Information(client.GetStringAsync("http://192.168.210.165:88/api/v1/values").Result);
  37.  
  38. //ResourceOwner
  39. var resourceOwnerClient = new TokenClient(
  40. "http://192.168.210.165/connect/token",
  41. "irving",
  42. "21B5F798-BE55-42BC-8AA8-0025B903DC3B");
  43. var data = resourceOwnerClient.RequestResourceOwnerPasswordAsync("irving", "123456", "order").Result;
  44. client.SetBearerToken(data.AccessToken);
  45. log.Information(client.GetStringAsync("http://192.168.210.165:88/api/v1/values").Result);
  46. Console.ReadKey();
  47. }
  48. }
  49. }

基于 IdentityServer3 实现 OAuth 2.0 授权服务【密码模式(Resource Owner Password Credentials)】的更多相关文章

  1. 基于 IdentityServer3 实现 OAuth 2.0 授权服务【客户端模式(Client Credentials Grant)】

    github:https://github.com/IdentityServer/IdentityServer3/ documentation:https://identityserver.githu ...

  2. 基于 IdentityServer3 实现 OAuth 2.0 授权服务数据持久化

    最近花了一点时间,阅读了IdentityServer的源码,大致了解项目整体的抽象思维.面向对象的重要性; 生产环境如果要使用 IdentityServer3 ,主要涉及授权服务,资源服务的部署负载的 ...

  3. Oauth2.0(六):Resource Owner Password Credentials 授权和 Client Credentials 授权

    这两种简称 Password 方式和 Client 方式吧,都只适用于应用是受信任的场景.一个典型的例子是同一个企业内部的不同产品要使用本企业的 Oauth2.0 体系.在有些情况下,产品希望能够定制 ...

  4. 基于OWIN WebAPI 使用OAuth授权服务【客户端验证授权(Resource Owner Password Credentials Grant)】

    适用范围 前面介绍了Client Credentials Grant ,只适合客户端的模式来使用,不涉及用户相关.而Resource Owner Password Credentials Grant模 ...

  5. OAuth2.0学习(1-6)授权方式3-密码模式(Resource Owner Password Credentials Grant)

    授权方式3-密码模式(Resource Owner Password Credentials Grant) 密码模式(Resource Owner Password Credentials Grant ...

  6. 使用Resource Owner Password Credentials Grant授权发放Token

    对应的应用场景是:为自家的网站开发手机 App(非第三方 App),只需用户在 App 上登录,无需用户对 App 所能访问的数据进行授权. 客户端获取Token: public string Get ...

  7. 第37章 资源所有者密码验证(Resource Owner Password Validation) - Identity Server 4 中文文档(v1.0.0)

    如果要使用OAuth 2.0资源所有者密码凭据授权(aka password),则需要实现并注册IResourceOwnerPasswordValidator接口: public interface ...

  8. OAuth密码模式说明(resource owner password credentials)

    用户向客户端(third party application)提供用户名和密码. 客户端将用户名和密码发给认证服务器(Authorization server),向后者请求令牌(token). 认证服 ...

  9. 理解OAuth 2.0授权

    一.什么是OAuth 二.什么场景下会用到OAuth授权 三.OAuth 2.0中的4个成员 四.OAuth 2.0授权流程 五.OAuth 2.0授权模式 1.    authorization c ...

随机推荐

  1. mongodb 的安装和使用

    官方网址 http://www.mongodb.org 1.下载mongodb-win32-i386-latest.zip 解压 mongodb 3.1.5 需要 win7 下 下载安装内存补丁 ht ...

  2. html-css实例

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...

  3. ubuntu 14.04 更新 gcc/g++ 4.9.2

    ubuntu 14.04 更新 gcc/g++ 4.9.2 最近看到c++11非常的好用,尤其是自带了regex,于是稍微学了一下c++11的新特性.可是我在编译一个regex程序是却发现稍微复杂一点 ...

  4. 主机名链接数据库,无法生成 SSPI 上下文

    两台Server,环境一样,都使用同一域账号. 1的SQL Server可以通过Windows认证连接到2,但2通过Windows认证连接1时报如下错误: 目标主体名称不正确,无法生成 SSPI 上下 ...

  5. newCachedThreadPool线程池

    public static ExecutorService newCachedThreadPool()创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们.对于执行很多短期异步任 ...

  6. phpPgAdmin安装与配置

    1.phpPgAdmin不需要安装,直接从Sourceforge下载压缩包,解压到“/var/www/”文件夹下即可. 解压后,要为该文件夹赋予root用户和root组的权限 chown -R roo ...

  7. oc中的枚举定义

    typedef NS_ENUM(类型,枚举名){        枚举名+值名,       枚举名+值名,}; 该方法定义的枚举,OC会自动把其转换成合适当前版本的枚举.如果枚举值可合并的话 NS_E ...

  8. jQuery 屏幕遮罩

    1.先做一个可以覆盖整个屏幕的div,颜色为黑色,然后再设置透明度,作为遮罩#zhezhao { position: absolute; top: 0px; left: 0px; width: 100 ...

  9. args

    java 中args一般存在main主类方法内,String args[ ]或者String[ ] args表示给主方法传一个字符串数组. 而args是一个字符串数组的变量名,不是关键字,是argum ...

  10. 【MVC】 异常处理

    [MVC] 异常处理 一 . 自定义 HandleErrorAttribute public class ExceptionLogAttribute : HandleErrorAttribute { ...