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);
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值