IdentityServer4 管理界面

Maj*_*aho 4 c# security access-token identityserver4

我正在开发在 github GitHub IdentityServer4.AdminUI上开发的 IdentityServer4.AdminUI

首先,我简单地创建了一个新用户并设置了它的密码,然后我创建了名为Api_Name 的ApiResource。然后我创建了具有相同名称的 IdentityResource Api_Name。最后,我创建了名为Api_Client 的新客户端,并将客户端允许的范围设置为Api_Name,将允许的授予类型设置为密码,最后将客户端密码设置为秘密

现在,我创建了新的 WebApi 项目(Core 2.1)并在启动类中使用它

public void ConfigureServices(IServiceCollection services) {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        services.AddMvcCore().AddAuthorization().AddJsonFormatters();

        services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options => {
                options.Authority = "http://localhost:5000"; //Identity Server URL
                options.RequireHttpsMetadata = false; // make it false since we are not using https
                options.ApiName = "Api_Name"; //api name which should be registered in IdentityServer
            });
    }

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

        app.UseAuthentication();

        app.UseHttpsRedirection();
        app.UseMvc();
    }
Run Code Online (Sandbox Code Playgroud)

并且确定我在 WebApi 控制器中使用了 [Authorize] 属性

最后,测试。我创建了控制台应用程序并使用此代码

var identityServer = await DiscoveryClient.GetAsync("http://localhost:5000"); //discover the IdentityServer
        if (identityServer.IsError) {
            Console.Write(identityServer.Error);
            return;
        }

        HttpClient client = new HttpClient();

        var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest {
            Address = identityServer.TokenEndpoint,
            ClientId = "Api_Client",
            ClientSecret = "secret",

            UserName = "Majd",
            Password = "P@ssw0rd@123"
        });

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

        //Call the API

        client.SetBearerToken(tokenResponse.AccessToken);

        var response = await client.GetAsync("https://localhost:44368/api/values");
        var response2 = await client.GetAsync("https://localhost:44368/api/values/1");
        var content = await response.Content.ReadAsStringAsync();
        Console.WriteLine(JArray.Parse(content));
        Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)

问题是 response2 返回 UnAuthorized 401。那么为什么我收到这个错误,因为我使用了从身份服务器收到的访问令牌

Vid*_*ius 6

您还需要在令牌请求中添加请求的范围(即使您说允许客户端访问Api_Name)。

    var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest {
        Address = identityServer.TokenEndpoint,
        ClientId = "Api_Client",
        ClientSecret = "secret",

        UserName = "Majd",
        Password = "P@ssw0rd@123",
        Scope = "Api_Name"
    });
Run Code Online (Sandbox Code Playgroud)

在 IDS4 中,令牌仅针对已请求的范围发出,这与 IDS3 不同,在 IDS3 中,您可以获得客户端允许的所有范围。因此,就您的 Api 身份验证中间件而言,由于令牌不够,您的客户端无法访问它。