You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IdentityServer4与SignInManager集成技术咨询及现有配置说明

IdentityServer4 Integration for Your Multi-App Solution

Hey there! Let's break down the complete integration plan for your Web API, Web admin frontend, and mobile app using IdentityServer4, building on the partial configuration you shared.

1. Complete Web Admin Frontend Authentication Configuration

Your existing ConfigureServices code is a great start—let's finish the OpenID Connect setup and add the necessary pipeline configuration:

ConfigureServices (Full Version)

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    // Clear default claim mappings to use IdentityServer's original claims
    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    services
        .AddAuthentication(options =>
        {
            options.DefaultScheme = "Cookies";
            options.DefaultChallengeScheme = "oidc";
        })
        .AddCookie("Cookies", options =>
        {
            // Adjust cookie settings for production (secure, same-site, etc.)
            options.Cookie.HttpOnly = true;
            options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            options.Cookie.SameSite = SameSiteMode.Lax;
        })
        .AddOpenIdConnect("oidc", options =>
        {
            // Point to your IdentityServer4 instance
            options.Authority = "https://your-identity-server-url";
            
            // Client credentials registered in IdentityServer
            options.ClientId = "web-admin-client";
            options.ClientSecret = "your-client-secret-here"; // Use a secret manager in production
            
            // Use code flow with PKCE (recommended for web apps)
            options.ResponseType = "code";
            options.UsePkce = true;
            
            // Scopes your app needs (identity + API access)
            options.Scope.Add("openid");
            options.Scope.Add("profile");
            options.Scope.Add("your-api-scope");
            
            // Save tokens to the cookie so we can use them to call the API
            options.SaveTokens = true;
            
            // Redirect and callback paths (must match IdentityServer client config)
            options.CallbackPath = "/signin-oidc";
            options.SignedOutCallbackPath = "/signout-callback-oidc";
        });

    services.AddAuthorization();
}

Configure Pipeline

Don't forget to add authentication and authorization to your middleware pipeline:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ... other middleware (like exception handling, static files) ...

    app.UseRouting();

    // Add authentication BEFORE authorization
    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

2. Protecting Your Web API

Your API needs to validate incoming JWT tokens from IdentityServer. Here's how to configure it:

API ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    services.AddAuthentication("Bearer")
        .AddJwtBearer("Bearer", options =>
        {
            options.Authority = "https://your-identity-server-url";
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateAudience = true,
                ValidAudience = "your-api-resource-name" // Must match IdentityServer's ApiResource
            };
        });

    services.AddAuthorization(options =>
    {
        // Add policy to require authenticated users with valid API scope
        options.AddPolicy("ApiAccess", policy =>
        {
            policy.RequireAuthenticatedUser();
            policy.RequireClaim("scope", "your-api-scope");
        });
    });
}

API Configure Pipeline

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ... other middleware ...

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        // Apply the ApiAccess policy to all API endpoints
        endpoints.MapControllers().RequireAuthorization("ApiAccess");
    });
}

3. Mobile App Integration

For mobile apps (public clients, no client secret), use the Authorization Code Flow with PKCE (the most secure option):

IdentityServer Client Configuration

First, register your mobile app as a client in IdentityServer:

// In your IdentityServer's Config.cs
new Client
{
    ClientId = "mobile-app-client",
    ClientName = "Mobile Application",
    AllowedGrantTypes = GrantTypes.Code,
    RequirePkce = true,
    RequireClientSecret = false, // No secret for mobile apps
    RedirectUris = { "com.your-app-scheme://callback" }, // Custom URI scheme for your app
    PostLogoutRedirectUris = { "com.your-app-scheme://signout-callback" },
    AllowedScopes = { "openid", "profile", "your-api-scope" },
    AllowOfflineAccess = true, // For refresh tokens
    AccessTokenLifetime = 3600, // 1 hour, adjust as needed
    RefreshTokenLifetime = 2592000 // 30 days
}

Mobile App Implementation Steps

  • Use a library like IdentityModel (for .NET MAUI/Xamarin) or platform-specific OAuth libraries to handle the flow.
  • Initiate the authorization request with the PKCE code challenge.
  • After receiving the authorization code, exchange it for an access token, ID token, and refresh token.
  • Use the access token to make authenticated requests to your Web API.
  • When the access token expires, use the refresh token to get a new one without re-authenticating the user.

4. Key IdentityServer4 Setup Requirements

Make sure your IdentityServer instance is configured with the necessary resources and clients:

  • IdentityResources: At minimum, include openid and profile to support user authentication.
  • ApiResources: Define your Web API as an API resource with the scope your apps will use (e.g., your-api-scope).
  • Clients: Register both your Web admin frontend and mobile app as clients with the correct grant types, scopes, and redirect URIs.

内容的提问来源于stack exchange,提问作者Josh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:24:40