IdentityServer4 密码模式

发布时间 2023-08-02 17:27:51作者: huihui_teresa

1.Config添加用户的配置

public class Config
{
    /// <summary>
    /// 提示invalid_scope 添加
    /// </summary>
    public static IEnumerable<ApiScope> ApiScopes =>
        new ApiScope[] {new ApiScope("api")};

    public static IEnumerable<ApiResource> GetResources()
    {
        return new List<ApiResource>
        {
            new ApiResource("api","My Api")
        };
    }

    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            new Client
            {
                ClientId = "client",
                AllowedGrantTypes = GrantTypes.ClientCredentials,
                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },
                AllowedScopes = {"api"}
            },
            //密码模式添加
            new Client
            {
                ClientId = "pwdClient",
                AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },
                AllowedScopes = {"api"}
            }
        };
    }

    /// <summary>
    /// 密码模式在客户端基础上添加的测试用户
    /// </summary>
    /// <returns></returns>
    public static List<TestUser> GetTestUsers()
    {
        return new List<TestUser>
        {
            new TestUser
            {
                SubjectId = "1",
                Username = "huihui",
                Password = "123456"
            }
        };
    }
}

2.添加Client的配置

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentityServer()
        .AddDeveloperSigningCredential()
        .AddInMemoryApiResources(Config.GetResources())
        .AddInMemoryClients(Config.GetClients())
        //这个ApiScopes需要新加上,否则访问提示invalid_scope
        .AddInMemoryApiScopes(Config.ApiScopes)
        .AddTestUsers(Config.GetTestUsers())
        ;

    services.AddControllers();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseRouting();

    app.UseIdentityServer();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

3.密码模式获取token

  • localhost:5000/connect/token
  • post请求
  • body,x-www-form-urlencode添加参数
    • client_id:pwdClient
    • client_secret:secret
    • grant_type:password
    • username:huihui
    • password:123456
{
    "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IkFDMEU3NUU4QzdGNjI0NkRBNjY2RDE5RjVCMDdCNjkyIiwidHlwIjoiYXQrand0In0.eyJuYmYiOjE2NDEzODQzODksImV4cCI6MTY0MTM4Nzk4OSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiY2xpZW50X2lkIjoicHdkQ2xpZW50Iiwic3ViIjoiMSIsImF1dGhfdGltZSI6MTY0MTM4NDM4OSwiaWRwIjoibG9jYWwiLCJqdGkiOiI0QkNCREExRTVFNjUzNUVCMkY2MTY0OUU3MzIwNTk2QSIsImlhdCI6MTY0MTM4NDM4OSwic2NvcGUiOlsiYXBpIl0sImFtciI6WyJwd2QiXX0.NbeaxQH3qs-aXbRysFTltz2vkzKjjMvjAV0UXhH0VeqGaXSbSKzWnghmCuJLeOtn57NbLgVqsaBogIT4nxQcbkU7FfOTyFJbpgl5qJYsdRAhw0UQNc14EHO3DjCOHI6Z14i3L7sw87bpND1Z3_mcG4ijxHoSyNOBfk9uDoCe4j-007DnGS6pUJJk_P5QxEMa9FBy61KYyj5ZTRTCtNDWJRfs792ZcSqX9UqHhjXZMRdyNkd8ix_SsdRrliQq8GEn60E3qTs80yOoowtEnF8N03yGMQpcFb3f5EFPsRXKHO3ppPHNKvr6cyID5kaeE4wNg_lvYokTjyRPsB603vGzew",
    "expires_in": 3600,
    "token_type": "Bearer",
    "scope": "api"
}

获取token

4.postman请求api

Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IkFDMEU3NUU4QzdGNjI0NkRBNjY2RDE5RjVCMDdCNjkyIiwidHlwIjoiYXQrand0In0.eyJuYmYiOjE2NDEzODQ1MzYsImV4cCI6MTY0MTM4ODEzNiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiY2xpZW50X2lkIjoicHdkQ2xpZW50Iiwic3ViIjoiMSIsImF1dGhfdGltZSI6MTY0MTM4NDUzNiwiaWRwIjoibG9jYWwiLCJqdGkiOiIwN0FFNTk4MENDNUJENTMxMTE5QTg3RkNDRjNFMEYyOSIsImlhdCI6MTY0MTM4NDUzNiwic2NvcGUiOlsiYXBpIl0sImFtciI6WyJwd2QiXX0.lXcUyrUyUi_3xXtwPw-K-1u-qX4cF-m8RM5cSe9WDNB3XzLNdcg-IlsRjDmelHjB28gyUQTOkNV5r85K38-ciPzPGnlqNNDyc_3CrH9kD4OrCRD-oUGF24rcmEDuqOEXKBSbUCVl4oFsPNpAtAUTnNFENGMHW6ue_oAi5Ic1ZTbsxTBR09z-910PJfPnv8EEb1CFiD4CZ9SzXtK8_yHChdSUvapgtca5ZVGAuVwE8TlVtSjWGrpPP-HSCTdWeyrEvZXYNojifsQipDO0klRgf3g5fBl-dhzevV_IggG3jfXYchJeSjZroRo9_t1SRL7bF25R54cvy2RJFyBkWi_-Mg

aa

这样postman就请求成功了。

5.添加控制台应用调用api

  1. Nuget添加 IdentityModel
  2. 控制台应用程序调用
static async Task Main(string[] args)
{
    var client = new HttpClient();
    var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");
    if (disco.IsError)
    {
        Console.WriteLine(disco.Error);
    }
    var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
    {
        Address = disco.TokenEndpoint,
        ClientId = "pwdClient",
        ClientSecret = "secret",
        Scope = "api",
        UserName = "jesse",
        Password = "123456"
    });
    if (tokenResponse.IsError)
    {
        Console.WriteLine(tokenResponse.Error);
        return;
    }
    Console.WriteLine(tokenResponse.Json);

    //调用api
    var apiClient = new HttpClient();
    apiClient.SetBearerToken(tokenResponse.AccessToken);

    var response = await apiClient.GetAsync("http://localhost:5001/WeatherForecast");
    if (!response.IsSuccessStatusCode)
    {
        Console.WriteLine(response.StatusCode);
    }
    else
    {
        var content = await response.Content.ReadAsStringAsync();
        Console.WriteLine(JArray.Parse(content));
    }

    Console.ReadKey();
}

aa

参考官网地址:https://identityserver4.readthedocs.io/en/latest/