OAuth2.0协议 |IdentityServer4实现认证授权:客户端模式

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

客户端模式的主要特点就是:客户端根据 客户端ID (client_id)与 秘钥(client_secret)向 认证中心发起访问 获取Token

 

var diso = DiscoveryClient.GetAsync("http://127.16.7.6003").Result;
            if (diso.IsError)
            {
                //diso.Error;
            }
            var tokenClient = new TokenClient(diso.TokenEndpoint, "clientId", "secret");
            var tokenResponse = tokenClient.RequestClientCredentialsAsync("api").Result;
            if (tokenResponse.IsError)
            {
                //tokenResponse.Error;
            }

            var httpClient = new HttpClient();
            httpClient.SetBearerToken(tokenResponse.AccessToken);
            var response = httpClient.GetAsync("http://127.0.0.1:6001/UserService/values").Result;
            if (response.IsSuccessStatusCode)
            {
                var result = response.Content.ReadAsStringAsync().Result;
            }

2

using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;
using Xunit;

namespace UserTest
{
    public class UserClientTest
    {
        [Fact]
        public async Task ClientApiTest()
        {
            //get access_token
            var disco = await DiscoveryClient.GetAsync("http://localhost:8001");
            var tokenClient = new TokenClient(disco.TokenEndpoint, "Client", "secret");
            var tokenResponse = await tokenClient.RequestClientCredentialsAsync("UserApi");

            var client = new HttpClient();
            client.SetBearerToken(tokenResponse.AccessToken);//add bearer with access_token
            var response = await client.GetAsync("http://localhost:5001/api/Values");//call API with access_token
            var apiResult = response.Content.ReadAsStringAsync().Result;
            Assert.NotEmpty(apiResult);
        }

        [Fact]
        public async Task PasswordApiTests()
        {
            var disco = await DiscoveryClient.GetAsync("http://localhost:8001");
            var tokenClient = new TokenClient(disco.TokenEndpoint, "ro.Client", "secret");
            var tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync("qwerty", "a123", "UserApi");

            var client = new HttpClient();
            client.SetBearerToken(tokenResponse.AccessToken);//add bearer with access_token
            var response = await client.GetAsync("http://localhost:5001/api/Values");//call API with access_token
            var apiResult = response.Content.ReadAsStringAsync().Result;
            Assert.NotEmpty(apiResult);
        }
    }
}

 

你可能感兴趣的:(微服务)