oauth2.0 401未经授权访问

7gyucuyw  于 2023-01-25  发布在  其他
关注(0)|答案(2)|浏览(223)

我用的是不和谐网3.5.0版。
我有一个OAuth2访问令牌,我试图使用DiscordRestClient来获取用户的公会,但我得到了401未经授权。

DiscordRestClient discordClient = new();
await discordClient.LoginAsync(TokenType.Bearer, accessToken);
IReadOnlyCollection<IGuild> restGuilds = await discordClient.GetGuildsAsync();

单步执行await discordClient.GetGuildsAsync()会引发异常。

fail: Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost[111]
      Unhandled exception in circuit 'iPxGWxw_tZW73Ya4zYXPehZr3w_Wdcs9uXYuEaUkslY'.
      Discord.Net.HttpException: The server responded with error 401: 401: Unauthorized
         at Discord.Net.Queue.RequestBucket.SendAsync(RestRequest request)
         at Discord.Net.Queue.RequestQueue.SendAsync(RestRequest request)
         at Discord.API.DiscordRestApiClient.SendInternalAsync(String method, String endpoint, RestRequest request)
         at Discord.API.DiscordRestApiClient.SendAsync[TResponse](String method, String endpoint, BucketId bucketId, ClientBucketType clientBucket, RequestOptions options)
         at Discord.API.DiscordRestApiClient.GetGuildAsync(UInt64 guildId, Boolean withCounts, RequestOptions options)
         at Discord.Rest.ClientHelper.GetGuildsAsync(BaseDiscordClient client, Boolean withCounts, RequestOptions options)

我可以成功地使用一个常规的HttpClient虽然,所以我可以确认访问令牌是有效的。

HttpClient httpClient = httpClientFactory.CreateClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
JsonArray? myGuilds = await httpClient.GetFromJsonAsync<JsonArray>("https://discord.com/api/v9/users/@me/guilds");

我哪里做错了?

hjzp0vay

hjzp0vay1#

您可能没有初始化DiscordRestClient

DiscordRestClient discordClient = new();

使用提供的配置初始化新的DiscordRestClient

gg58donl

gg58donl2#

确保在发送初始OAuth2请求时定义了正确的"作用域",例如,由于您尝试在那里获取guildren,因此您的作用域也应该包含"guildren"。
示例:

var args = new Dictionary<string, string?>
            {
                { "response_type", "code" },
                { "client_id", CLIENT_ID_HERE ?? "" },
                { "scope", "identify guilds email" }, // make sure you add all the permissions you need here
                { "state", SESSION_ID_HERE ?? "" },
                { "redirect_uri", REDIRECT_URI_HERE ?? "" }
            };

            string url = QueryHelpers.AddQueryString($"https://discord.com/api/oauth2/authorize", args);
            controller.Redirect(url);

相关问题