AddApiAuthorization 的默认设置(Scaffolded Angular + IdentityServer4)

nop*_*nop 5 identityserver4 angular asp.net-core-3.1

我正在将这个脚手架示例用于 Angular + IdentityServer4。

dotnet new angular -o <output_directory_name> -au Individual
Run Code Online (Sandbox Code Playgroud)

的默认凭据、授权类型、客户端 ID、客户端密码是什么AddApiAuthorization,以便我可以使用 Postman 对其进行测试?因为我所能找到的就是我们可以添加额外的 API 资源、客户端等。我知道默认配置文件

链接到他们的实现:https : //github.com/dotnet/aspnetcore/blob/9a1810c1dbe432fc7bc7e8bc68fa22ab787c0452/src/Identity/ApiAuthorization.IdentityServer/src/IdentityServerBuilderConfigurationExtensions.cs

添加更多客户端和 API 资源的示例:

dotnet new angular -o <output_directory_name> -au Individual
Run Code Online (Sandbox Code Playgroud)

微软的脚手架方式:

AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options =>
{
    options.Clients.AddSPA(
        "My SPA", spa =>
        spa.WithRedirectUri("http://www.example.com/authentication/login-callback")
           .WithLogoutRedirectUri(
               "http://www.example.com/authentication/logout-callback"));

    options.ApiResources.AddApiResource("MyExternalApi", resource =>
        resource.WithScopes("a", "b", "c"));
});
Run Code Online (Sandbox Code Playgroud)

我之前使用原始 IdentityServer4 包的配置。它使用带有 PKCE 的代码:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            configuration.GetConnectionString("DefaultConnection"),
            b => b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName)));

    services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
        .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddIdentityServer()
        .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

    services.AddAuthentication()
        .AddIdentityServerJwt();
    services.AddControllersWithViews();
    services.AddRazorPages();
    // In production, the Angular files will be served from this directory
    services.AddSpaStaticFiles(configuration =>
    {
        configuration.RootPath = "ClientApp/dist";
    });
}
Run Code Online (Sandbox Code Playgroud)

编辑:

@Lasanga Guruge 很好地解释了如何查看默认值。

在此处输入图片说明

info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
      Request starting HTTP/1.1 GET http://localhost:61846/connect/authorize?response_type=code&state=&client_id=CleanArchitecture.WebUI&scope=openid%20profile&redirect_uri=http%3A%2F%2Flocalhost%3A61846%2Fauthentication%2Flogin-callback&code_challenge=HH2xNyUDRhvVlkvL024GD4lJKI0NQFo7QqANot3BCD4&code_challenge_method=S256  
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Request path /connect/authorize matched to endpoint type Authorize
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Endpoint enabled: Authorize, successfully created handler: IdentityServer4.Endpoints.AuthorizeEndpoint
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeEndpoint for /connect/authorize
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      Start authorize request
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      No user present in authorize request
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Start authorize request protocol validation
dbug: IdentityServer4.Stores.ValidatingClientStore[0]
      client configuration validation for client CleanArchitecture.WebUI succeeded.
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Checking for PKCE parameters
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Calling into custom validator: IdentityServer4.Validation.DefaultCustomAuthorizeRequestValidator
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      ValidatedAuthorizeRequest
      {
        "ClientId": "CleanArchitecture.WebUI",
        "ClientName": "CleanArchitecture.WebUI",
        "RedirectUri": "http://localhost:61846/authentication/login-callback",
        "AllowedRedirectUris": [
          "/authentication/login-callback"
        ],
        "SubjectId": "anonymous",
        "ResponseType": "code",
        "ResponseMode": "query",
        "GrantType": "authorization_code",
        "RequestedScopes": "openid profile",
        "Raw": {
          "response_type": "code",
          "state": "",
          "client_id": "CleanArchitecture.WebUI",
          "scope": "openid profile",
          "redirect_uri": "http://localhost:61846/authentication/login-callback",
          "code_challenge": "HH2xNyUDRhvVlkvL024GD4lJKI0NQFo7QqANot3BCD4",
          "code_challenge_method": "S256"
        }
      }
info: IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator[0]
      Showing login: User is not authenticated
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
      Request finished in 46.115ms 302 
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
      Request starting HTTP/1.1 GET http://localhost:61846/Identity/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fresponse_type%3Dcode%26state%26client_id%3DCleanArchitecture.WebUI%26scope%3Dopenid%2520profile%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A61846%252Fauthentication%252Flogin-callback%26code_challenge%3DHH2xNyUDRhvVlkvL024GD4lJKI0NQFo7QqANot3BCD4%26code_challenge_method%3DS256  
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
      Executing endpoint '/Account/Login'
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[3]
      Route matched with {page = "/Account/Login", area = "Identity", action = "", controller = ""}. Executing page /Account/Login
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[101]
      Executing handler method Microsoft.AspNetCore.Identity.UI.V4.Pages.Account.Internal.LoginModel.OnGetAsync - ModelState is Valid
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[11]
      AuthenticationScheme: Identity.External signed out.
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[102]
      Executed handler method OnGetAsync, returned result .
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[103]
      Executing an implicit handler method - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[104]
      Executed an implicit handler method, returned result Microsoft.AspNetCore.Mvc.RazorPages.PageResult.
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[4]
      Executed page /Account/Login in 17.3083ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
      Executed endpoint '/Account/Login'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
      Request finished in 31.3091ms 200 text/html; charset=utf-8
Run Code Online (Sandbox Code Playgroud)

这是否意味着一切正常?

Las*_*uge 5

脚手架应用程序的默认值是

  1. 授权码类型
  2. ClientId 将与应用程序名称相对应。可以在appsettings.json(客户端)和api-authorization.constants.ts(应用程序名称)中更改
  3. 默认情况下,客户端密钥不会应用于客户端
  4. pkce 也已启用。
  5. 没有默认凭据
  6. {ProjectName}API将添加额外的命名范围

您可以致电https://localhost:{port}/_configuration/{clientId}获取信息。要检查有关默认客户端的更多详细信息,您可以调试以下代码

 services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>((config) =>
                {  
                    config.Clients[0].AccessTokenLifetime = 3600   
                });

Run Code Online (Sandbox Code Playgroud)

如果您想编辑默认客户端。

更新

更改 clientId 从appsetting.json

"IdentityServer": {
    "Clients": {
      "{ClientId}": { //To edit the clientId change here
        "Profile": "IdentityServerSPA"
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

注意:正如我上面提到的,如果您更改,ClientId请确保您更改ApplicationNameapi-authorization.constants.ts