使用 JWT 添加剩余身份验证

问题描述 投票:0回答:1

我需要使用jwt开发rest身份验证。

我知道如何从 url 获取令牌,但在本例中不是从 url 获取令牌。 api 使用 jwt 生成响应,但我不知道如何从响应中获取该 jwt

我正在尝试使用 IdentityModel,但是当我尝试这样做时出现错误

var client = new HttpClient();

var response = await client.RequestTokenAsync(new TokenRequest
{
    Address = "https://demo.identityserver.io/connect/token",
    GrantType = "custom",

    ClientId = "client",
    ClientSecret = "secret",

    Parameters =
    {
        { "custom_parameter", "custom value"},
        { "scope", "api1" }
    }
});

我无法创建该 HttpClient 并且提供 VS 的使用没有该方法

c# .net asp.net-core jwt
1个回答
0
投票

您可以尝试在控制台应用程序中执行以下操作:
安装包

Identiy.Model

    private static async Task Main(string[] args)
    {
        // from discoverydocument to get token endpoint information
        var client = new HttpClient();
        var disco = await client.GetDiscoveryDocumentAsync("https://localhost:5001"); //identity server URL
        if (disco.IsError)
        {
            Console.WriteLine(disco.Error);
            return;
        }
        else
        {
            Console.WriteLine(disco.AuthorizeEndpoint);
            Console.WriteLine(disco.TokenEndpoint);
        }

        // request for client-flow token
        var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
        {
            Address = disco.TokenEndpoint,

            ClientId = "client",
            ClientSecret = "secret",
            Scope = "api2",
            //GrantType ="client_credentials",
 
        });

        if (tokenResponse.IsError)
        {
            Console.WriteLine(tokenResponse.Error);
            return;
        }

        Console.WriteLine(tokenResponse.Json);



        // use token to access api
        var apiClient = new HttpClient();
        apiClient.SetBearerToken(tokenResponse.AccessToken);

        var response = await apiClient.GetAsync("https://localhost:7171/identity");   //the api protected by [Authorize]
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.StatusCode);
        }
        else
        {
            var content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        }

    }
© www.soinside.com 2019 - 2024. All rights reserved.