您的位置:首页 > 编程语言 > ASP

【ASP.NET Core分布式项目实战】(一)IdentityServer4登录中心、oauth密码模式identity server4实现

2018-01-14 21:39 3431 查看
本博客根据http://video.jessetalk.cn/my/course/5视频整理

资料

OAuth2 流程:http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html

博客园晓晨的关于identityServer4的中文文档地址: http://www.cnblogs.com/stulzq/p/8119928.html

Docker中文文档 https://yeasy.gitbooks.io/docker_practice/content/

OAuth2.0概念

OAuth2.0(Open Authorization)是一个开放授权协议;第三方应用不需要接触到用户的账户信息(如用户名密码),通过用户的授权访问用户资源

OAuth的步骤一般如下:

1、客户端要求用户给予授权
2、用户同意给予授权
3、根据上一步获得的授权,向认证服务器请求令牌(token)
4、认证服务器对授权进行认证,确认无误后发放令牌
5、客户端使用令牌向资源服务器请求资源
6、资源服务器使用令牌向认证服务器确认令牌的正确性,确认无误后提供资源

该协议的参与者至少包含:

RO (resource owner): 资源所有者:用户。

RS (resource server): 资源服务器:数据中心;它存储资源,并处理对资源的访问请求。如:API资源,相册服务器、博客服务器。

AS (authorization server): 授权服务器

Client: 第三方应用

四种模式:

1、授权码模式(authorization code)
2、简化模式(implicit)
3、密码模式(resource owner password credentials)
4、客户端模式(client credentials)

接下来我们使用客户端模式来实现一个IdentityServer4授权

客户端模式(Client Credentials Grant)

客户端模式(ClientCredentials):经常运用于服务器对服务器中间通讯使用;步骤如下:

1、客户端直接用自身的信息向授权服务器请求token:

HTTP请求:

granttype:授权类型

scope:授权范围

POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials&scope=api001


2、授权服务器验证信息后返回token

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache

{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"example",
"expires_in":3600,
"example_parameter":"example_value"
}


using System;
using System.Net.Http;
using IdentityModel.Client;

namespace PwdClient
{
class Program
{
static void Main(string[] args)
{
var dico = DiscoveryClient.GetAsync("http://localhost:5000").Result;

//token
var tokenClient = new TokenClient(dico.TokenEndpoint, "pwdClient", "secret");
var tokenResponse = tokenClient.RequestResourceOwnerPasswordAsync("wyt","123456").Result;
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;

}

Console.WriteLine(tokenResponse.Json);
Console.WriteLine("\n\n");

var httpClient = new HttpClient();
httpClient.SetBearerToken(tokenResponse.AccessToken);

var response = httpClient.GetAsync("http://localhost:5001/api/values").Result;
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}

Console.ReadLine();
}
}
}


View Code
运行效果:



如果信任的第三方,不想加入密码,可以在授权服务的Config.cs中Client添加设置RequireClientSecret=false即可

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐