访问被IdentityServer4保护的api时,取得token的方式

1、通过ClientId、ClientSecret来获得token,代码如下:

认证服务器端:

                    ClientId = client.ClientId,
                    ClientName = client.ClientName,
                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    ClientSecrets = { new Secret("123456".Sha256()) },
                    AllowedScopes = { client.Scope },
                    AllowOfflineAccess = true

客户端:

            var httpClient = new HttpClient();
            var disco = httpClient.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest
            {
                Address = System.Configuration.ConfigurationManager.AppSettings["AuthorizationCenterUrl"],
                Policy =
                {
                     RequireHttps=false
                }
            }).Result;
            if (disco.IsError)
            {
                throw new Exception(disco.Error);
            }
            var tokenResponse = httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address = disco.TokenEndpoint,
                ClientId = "localHtml",
                ClientSecret = "123456",
                Scope = "SourceApi"
            });
            string token = tokenResponse.Result.AccessToken;

2、通过用户名密码获得token

  首先认证服务器端需要允许当前AllowedScopes 

                    Client oneResult = new Client
                    {
                        ClientId = client.ClientId,
                        ClientName = client.ClientName,
                        AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                        ClientSecrets = { new Secret("111111".Sha256()) },
                        AllowOfflineAccess = true,
                        RequireConsent = false,
                        RequireClientSecret = false,
                        AllowedScopes =
                        {
                            IdentityServerConstants.StandardScopes.OpenId,
                            IdentityServerConstants.StandardScopes.Profile,
                            IdentityServerConstants.StandardScopes.OfflineAccess,
                            "role",
                            "CommonAPI"
                        },
                        AuthorizationCodeLifetime = 36000,
                        IdentityTokenLifetime = 36000,
                        UserSsoLifetime = 36000
                    };

  然后用这个客户端id和用户名密码获得的token就可以有权限访问资源名称为:CommonAPI的数据

客户端:

uni.request({
                            url: baseUrl + '/connect/token',
                            method: 'POST',
                            header: {
                                'content-type': "application/x-www-form-urlencoded"
                            },
                            data: {
                                username: this.user_name,
                                password: this.password_encryptioned, //B942B751A119FB3146B40679638F38B9
                                grant_type: 'password',
                                client_id: 'localHtml'
                            },
                            success: res => {
                                if (res.statusCode === 200) {
                                    console.log(res);
                                    uni.setStorageSync('access_token', res.data.token_type + ' ' + res.data.access_token);
                                    uni.setStorageSync('user_name', this.user_name);
                                    uni.showToast({
                                        icon: 'none',
                                        title: '登录成功! '
                                    });
                                    uni.navigateTo({
                                        url:"../TypeSelect/TypeSelect"
                                    })
                                } else {
                                    uni.showToast({
                                        icon: 'none',
                                        title: '[' + res.statusCode +']登录失败!  请检查用户名/密码是否输入正确!',
                                        duration: 3000
                                    })
                                }
                            },
                            fail: () => {
                                uni.showToast({
                                    icon: 'none',
                                    title: '失败,请检查网络!',
                                    duration: 3000
                                })
                            }
                        })

然后利用这个token访问资源成功。

 

posted @ 2021-05-07 23:56  星星c#  阅读(430)  评论(0编辑  收藏  举报