Refactor OAuth handling and add GetAuthorizationUrl method

This commit is contained in:
Dmitri Shimanski
2025-08-22 08:51:44 +03:00
parent d96ed136d7
commit 3d724a4686
9 changed files with 61 additions and 35 deletions

View File

@@ -70,28 +70,6 @@ internal class DiscordSession (IToken token, HttpClient httpClient, ScopesBuilde
return await _req<DiscordConnection>("users/@me/connections");
}
public string GetAuthorizationUrl(string state)
{
NameValueCollection query = new()
{
["client_id"] = clientId.ToString(),
["redirect_uri"] = redirectUri,
["response_type"] = "code",
["scope"] = scopes.ToString(),
["state"] = state,
["prompt"] = prompt ? "consent" : "none"
};
var uriBuilder = new UriBuilder("https://discord.com/api/oauth2/authorize")
{
Query = query.ToString()
};
return uriBuilder.ToString();
}
public IToken GetToken(CancellationToken cancellationToken = default)
{
if (token.AccessToken is null)

View File

@@ -7,7 +7,7 @@ namespace yawaflua.Discord.Net.Entities;
internal class DiscordUser : IUser
{
[JsonPropertyName("id")]
public ulong Id { get; set; }
public string Id { get; set; }
[JsonPropertyName("username")]
public string Username { get; set; }

View File

@@ -7,15 +7,27 @@ namespace yawaflua.Discord.Net.Entities;
internal class OAuthToken (HttpClient client, ulong ClientId, string ClientSecret) : IToken
{
[JsonPropertyName("access_token")] public string AccessToken { get; set; }
public string AccessToken { get; set; }
[JsonPropertyName("expires_in")] public int ExpiresIn { get; set; }
public int ExpiresIn { get; set; }
[JsonPropertyName("refresh_token")] public string RefreshToken { get; set; }
public string RefreshToken { get; set; }
[JsonPropertyName("scope")] public string Scope { get; set; }
public string Scope { get; set; }
[JsonPropertyName("token_type")] public string TokenType { get; set; }
public string TokenType { get; set; }
public static OAuthToken FromDTO(TokenDto dto, HttpClient client, ulong ClientId, string ClientSecret)
{
return new(client, ClientId, ClientSecret)
{
AccessToken = dto.AccessToken,
ExpiresIn = dto.ExpiresIn,
RefreshToken = dto.RefreshToken,
Scope = dto.Scope,
TokenType = dto.TokenType
};
}
public Task RevokeAsync(CancellationToken cancellationToken = default)
{
using var request = new HttpRequestMessage(HttpMethod.Post, "https://discord.com/api/oauth2/token/revoke")

16
Entities/TokenDto.cs Normal file
View File

@@ -0,0 +1,16 @@
using System.Text.Json.Serialization;
namespace yawaflua.Discord.Net.Entities;
public class TokenDto
{
[JsonPropertyName("access_token")] public string AccessToken { get; set; }
[JsonPropertyName("expires_in")] public int ExpiresIn { get; set; }
[JsonPropertyName("refresh_token")] public string RefreshToken { get; set; }
[JsonPropertyName("scope")] public string Scope { get; set; }
[JsonPropertyName("token_type")] public string TokenType { get; set; }
}