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

客户端

public class Clients
{
public static List<Client> Get()
{
return new List<Client>
{
// no human involved
new Client
{
ClientName = "App接口服务",
ClientId = "app_test_id",
Enabled = true,
AccessTokenType = AccessTokenType.Reference,
Flow = Flows.ClientCredentials,
ClientSecrets = new List<Secret>
{
new Secret("F621F470-9731-4A25-80EF-67A6F7C5F4B8".Sha256())
},
AllowedScopes = new List<string>
{
"user",
"order"
}
},
// human is involved
new Client
{
ClientName = "username client",
ClientId = "irving",
Enabled = true,
AccessTokenType = AccessTokenType.Reference,
Flow = Flows.ResourceOwner,
ClientSecrets = new List<Secret>
{
new Secret("21B5F798-BE55-42BC-8AA8-0025B903DC3B".Sha256())
},
AllowedScopes = new List<string>
{
"user",
"order"
}
}
};
}
}

用户

public class Users
{
public static List<InMemoryUser> Get()
{
return new List<InMemoryUser>
{
new InMemoryUser
{
Username = "irving",
Password = "123456",
Subject = "1",
Claims = new[]
{
new Claim(Constants.ClaimTypes.GivenName, "Bob"),
new Claim(Constants.ClaimTypes.FamilyName, "Smith")
}
},
new InMemoryUser
{
Username = "bob",
Password = "secret",
Subject = "2"
},
new InMemoryUser
{
Username = "alice",
Password = "secret",
Subject = "3"
}
};
}
}

服务端配置

public class Startup
{
/// <summary>
/// 配置idsv授权服务
/// </summary>
/// <param name="app"></param>
public void Configuration(IAppBuilder app)
{
var opts = new IdentityServerOptions
{
SiteName = "Embedded Homeinns PMS 2.0 OAuth2 Service",
EnableWelcomePage = true,
Factory = new IdentityServerServiceFactory()
.UseInMemoryClients(Clients.Get())
.UseInMemoryScopes(Scopes.Get())
//.UseInMemoryUsers(new List<InMemoryUser>()),
.UseInMemoryUsers(Users.Get()),
RequireSsl = false,
//SigningCertificate = new X509Certificate2(string.Format(@"{0}\bin\identityServer\idsrv3test.pfx", AppDomain.CurrentDomain.BaseDirectory), "idsrv3test")
};
app.UseIdentityServer(opts); /*
//自定义路由
app.Map("/identity", idsrvApp =>
{
idsrvApp.UseIdentityServer(opts);
});
*/
}

控制器

[Route("api/v1/values")]
public class ValuesController : ApiController
{
public IHttpActionResult Get()
{
var caller = User as ClaimsPrincipal;
var subjectClaim = caller.FindFirst("sub");
if (subjectClaim != null)
{
return Json(new
{
message = "OK user",
client = caller.FindFirst("client_id").Value,
subject = subjectClaim.Value
});
}
else
{
return Json(new
{
message = "OK computer",
client = caller.FindFirst("client_id").Value
});
}
}
}

控制台

class Program
{
static void Main(string[] args)
{
/*
POST http://192.168.210.165/connect/token HTTP/1.1
Accept: application/json
Authorization: Basic YXBwX3Rlc3RfaWQ6RjYyMUY0NzAtOTczMS00QTI1LTgwRUYtNjdBNkY3QzVGNEI4
Content-Type: application/x-www-form-urlencoded
Host: 192.168.210.165
Content-Length: 40
Expect: 100-continue
Connection: Keep-Alive grant_type=client_credentials&scope=user
*/ /*
GET http://192.168.210.165:88/api/v1/values HTTP/1.1
Authorization: Bearer 9f82476751e1f8b93f1ea6df7de83b51
Host: 192.168.210.165:88
*/
var log = new LoggerConfiguration()
.WriteTo
.LiterateConsole(outputTemplate: "{Timestamp:HH:mm} [{Level}] ({Name:l}){NewLine} {Message}{NewLine}{Exception}")
.CreateLogger(); //ClientCredentials
var token = new TokenClient(
"http://192.168.210.165/connect/token",
"app_test_id",
"F621F470-9731-4A25-80EF-67A6F7C5F4B8");
var response = token.RequestClientCredentialsAsync("user").Result;
var client = new HttpClient();
client.SetBearerToken(response.AccessToken);
log.Information(client.GetStringAsync("http://192.168.210.165:88/api/v1/values").Result); //ResourceOwner
var resourceOwnerClient = new TokenClient(
"http://192.168.210.165/connect/token",
"irving",
"21B5F798-BE55-42BC-8AA8-0025B903DC3B");
var data = resourceOwnerClient.RequestResourceOwnerPasswordAsync("irving", "123456", "order").Result;
client.SetBearerToken(data.AccessToken);
log.Information(client.GetStringAsync("http://192.168.210.165:88/api/v1/values").Result);
Console.ReadKey();
}
}
}

基于 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. 『GreenPlum系列』GreenPlum 4节点集群安装(图文教程)

      目标架构如上图   一.硬件评估 cpu主频,核数推荐CPU核数与磁盘数的比例在12:12以上Instance上执行时只能利用一个CPU核资源进行计算,推荐高主频 内存容量 网络带宽重分布操作 R ...

  2. [Tomcat 源码分析系列] (附件) : catalina.bat 脚本

    摘自 apache-tomcat-8.0.39-src 源码包中的 catalina.bat 脚本内容 @echo off rem Licensed to the Apache Software Fo ...

  3. centos dns配置

    vi /etc/sysconfig/network-scripts/ifcfg-[tab两下] 新增以下修改 ONBOOT=yes  #开启自动启用网络连接 IPADDR0=192.168.21.12 ...

  4. [转载] 3. JebAPI 之 jeb.api.ast

    本文转载自: https://www.zybuluo.com/oro-oro/note/143651 0. 序 Jeb 本身是支持变量重命名的,所以,混淆了的变量名.类名可以修改. 实际上,它还可以做 ...

  5. ASP.NET ZERO 学习 事件总线

    用于注册和触发客户端的全局事件. 介绍 Pub/sub事件模型广泛用于客户端,ABP包含了一个简单的全局事件总线来 注册并 触发事件. 注册事件 可以使用abp.event.on来注册一个全局事件.一 ...

  6. python学习之——计算文件行数

    # -*- coding: cp936 -*- #转载源于:http://blog.csdn.net/houyj1986/article/details/21196027 #计算文件行数 #1.文件比 ...

  7. 問題排查:建立選單時的錯誤 errcode:65318,errmsg:must use utf-8 charset hint: [Vwda70520vr18]

    目前已知:程式存檔時,將檔案編碼格式設定成 UTF-8 即可. 筆者使用的文字編輯器為 Editplus 3.51,檔案編碼格式很多帶 UTF8.Unicode 字眼的選項,選 UTF-8 即可.

  8. NSDate获取当前时间,并且转化为需要的格式

    NSDate *date = [NSDate date]; NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; [formatter ...

  9. 对象转型 casting

    一个基类的引用类型变量可以"指向"其子类对象. 一个基类的引用不可以访问其子类对象新增加的成员(属性和方法). 基类强制转型成子类,则能访问子类独有的成员. 可以使用 引用变量in ...

  10. (必看)ping值不代表网速

    在下售卖美国.香港VPN服务器多年,在于客户的交流中,最多关心的就是ping值速度,认为ping速度越低速度越快,以此来评判一台VPN服务器的速度快慢,这其实是一个误区!现在来详细说明下. 1.pin ...