博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
基于 IdentityServer3 实现 OAuth 2.0 授权服务【密码模式(Resource Owner Password Credentials)】...
阅读量:4312 次
发布时间:2019-06-06

本文共 6742 字,大约阅读时间需要 22 分钟。

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

客户端

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

用户

public class Users    {        public static List
Get() { return new List
{ 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    {        ///         /// 配置idsv授权服务        ///         ///         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
()), .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();        }    }}

转载于:https://www.cnblogs.com/Irving/p/5714644.html

你可能感兴趣的文章
MQTT协议笔记之mqtt.io项目HTTP协议支持
查看>>
(转)jQuery中append(),prepend()与after(),before()的区别
查看>>
Tecplot: Legend和图像中 Dashed/Dash dot/Long dash 等虚线显示没有区别的问题
查看>>
win8 开发之旅(2) --连连看游戏开发 项目错误的总结
查看>>
一、 object c -基础学习第一天 如何定义一个类
查看>>
Kali Linux的安装
查看>>
我的大学生活-5-08-赵心宁
查看>>
入门阶段
查看>>
Android中使用http协议访问网络
查看>>
Join 与 CountDownLatch 之间的区别
查看>>
vc6下dll调试
查看>>
Ubuntu apt常用命令
查看>>
struts2 配置(部分)
查看>>
python代码迷之错误(ModuleNotFoundError: No module named 'caffe.proto')
查看>>
nodejs adm-zip 解压文件 中文文件名乱码 问题解决
查看>>
<Bootstrap> 学习笔记六. 栅格系统使用案例
查看>>
vector--C++ STL 学习
查看>>
蜕变成蝶~Linux设备驱动之异步通知和异步I/O
查看>>
jquery简单开始
查看>>
作业2
查看>>