获取授权类型为密码的OAuth2令牌

xt0899hw  于 2023-03-17  发布在  其他
关注(0)|答案(1)|浏览(159)

我尝试使用IServiceCollection.AddAccessTokenManagement -> ClientCredentialsTokenRequest对象在C#中配置“通用”OAuth2客户端身份验证。我可以创建grant_type=client_credentials身份验证,没有任何问题,它可以工作。不幸的是,我不知道如何以相同的方式使用grant_type=password。我有用户名、密码、获取有效令牌所需的访问令牌URL和ClientID(在Postman中有效)。我如何在C#中实现类似的东西?

private static void ConfigureOuathAuthentication(IServiceCollection services, OuathAuthenticationConfiguration ouathAuthenticationConfiguration)
{
    services.AddAccessTokenManagement(options =>
    {
        options.Client.Clients.Add("identityserver", new ClientCredentialsTokenRequest
        {
            Address = ouathAuthenticationConfiguration.Address,
            ClientId = ouathAuthenticationConfiguration.ClientId,
            ClientSecret = ouathAuthenticationConfiguration.ClientSecret,
            Scope = ouathAuthenticationConfiguration.Scope, // optional
            GrantType = ouathAuthenticationConfiguration.GrantType
        });
    });

    services.AddClientAccessTokenHttpClient("client_ouath", configureClient: client =>
    {
        client.BaseAddress = new Uri(ouathAuthenticationConfiguration.Address);
    });
}
kgsdhlau

kgsdhlau1#

根据您的代码片段,我添加了Resource Owner Password Credentials流,也称为password流。

private static void ConfigureOuathAuthentication(IServiceCollection services, OuathAuthenticationConfiguration ouathAuthenticationConfiguration)
{
    services.AddAccessTokenManagement(options =>
    {
        options.Client.Clients.Add("identityserver", new ClientCredentialsTokenRequest
        {
            Address = ouathAuthenticationConfiguration.Address,
            ClientId = ouathAuthenticationConfiguration.ClientId,
            ClientSecret = ouathAuthenticationConfiguration.ClientSecret,
            Scope = ouathAuthenticationConfiguration.Scope, // optional
            GrantType = ouathAuthenticationConfiguration.GrantType
        });
    });

    options.Client.Clients.Add("resource-owner", new UsernamePasswordTokenRequest
    {
        Address = "address-for-resource-owner-client",
        ClientId = "clientid-for-resource-owner-client",
        ClientSecret = "clientsecret-for-resource-owner-client",
        Scope = "scope-for-resource-owner-client",
        UserName = "your-username",
        Password = "your-password",
        GrantType = "password"
    });

    services.AddClientAccessTokenHttpClient("client_ouath", configureClient: client =>
    {
        client.BaseAddress = new Uri(ouathAuthenticationConfiguration.Address);
    });
}

如果您有一个有效的身份提供者支持它,并且提供了适当的参数,那么它应该可以工作。

相关问题