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

如何通过Web API将.NET Identity数据存储到数据库中

Hey there! Let's break down your problem step by step—since you're new to web dev and navigating .NET Identity alongside a separate database server via Web API, I totally get the confusion. Let's start with clarifying your approach first, then dive into configuration fixes.

1. Is Your Authorization Approach Correct?

Short answer: Yes, choosing .NET Identity is the right move here. It’s built specifically to handle external logins (like Google and WS-Federation) and manage user identity data out of the box, so you don’t have to reinvent the wheel for storing login associations, user claims, or security tokens.

That said, the key thing to clarify is your architecture:

  • Are you hosting .NET Identity directly in your Web API (so the API handles all identity storage and authentication)?
  • Or does your web app host Identity, but need to forward identity data to the local database via your existing Web API?

Both are valid, but the configuration steps differ—let’s cover both scenarios.

2. Configuring .NET Identity to Store Data via Web API

This is the cleaner architecture: your API manages all identity logic and connects directly to your local database, while your web app acts as a client that uses the API for auth and data operations.

Here’s how to set it up:

  • Install required packages in your API project:
    dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore
    dotnet add package Microsoft.EntityFrameworkCore.SqlServer # Or your database provider
    
  • Create a custom DbContext that inherits from IdentityDbContext to map Identity tables to your local database:
    public class ApplicationDbContext : IdentityDbContext<IdentityUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options) { }
    }
    
  • Register Identity and DbContext in Program.cs:
    // Configure connection string to your local database server
    builder.Services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("LocalDbConnection")));
    
    // Register Identity services with Entity Framework storage
    builder.Services.AddIdentity<IdentityUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
    
    // Add JWT authentication for the web app to communicate with the API
    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = builder.Configuration["Jwt:Issuer"],
                ValidAudience = builder.Configuration["Jwt:Audience"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
            };
        });
    
  • Add external login handling in your API: Create endpoints to accept external login tokens (from Google/WS-Federation), validate them, and create/link a local Identity user to the external account.

Case B: Web App Hosts Identity, Uses API to Store Data

If you must keep Identity in the web app but forward data to the local DB via your API, you’ll need to replace Identity’s default storage providers with custom ones that call your API:

  • Implement custom user/role stores: Create classes that implement IUserStore<IdentityUser> and IRoleStore<IdentityRole>. In each method (like CreateAsync, FindByIdAsync), call your Web API’s endpoints to perform the database operation.
    Example snippet for CreateAsync:
    public async Task<IdentityResult> CreateAsync(IdentityUser user, CancellationToken cancellationToken)
    {
        var httpClient = _httpClientFactory.CreateClient();
        var response = await httpClient.PostAsJsonAsync("/api/users", user, cancellationToken);
        return response.IsSuccessStatusCode ? IdentityResult.Success : IdentityResult.Failed();
    }
    
  • Register custom stores in your web app’s Program.cs:
    builder.Services.AddIdentity<IdentityUser, IdentityRole>()
        .AddUserStore<CustomUserStore>()
        .AddRoleStore<CustomRoleStore>()
        .AddDefaultTokenProviders();
    

Note: This approach is more work since you’ll need to implement all required Identity store methods, but it’s doable if your architecture requires it.

3. Integrating Google and WS-Federation Logins

Regardless of your architecture, the external login setup in your web app is similar:

  • Configure Google Login in Program.cs:
    builder.Services.AddAuthentication()
        .AddGoogle(options =>
        {
            var googleConfig = builder.Configuration.GetSection("Authentication:Google");
            options.ClientId = googleConfig["ClientId"];
            options.ClientSecret = googleConfig["ClientSecret"];
            options.CallbackPath = "/signin-google"; // Must match your Google OAuth callback setup
        });
    
  • Configure WS-Federation Login:
    builder.Services.AddAuthentication()
        .AddWsFederation(options =>
        {
            options.MetadataAddress = builder.Configuration["Authentication:WsFederation:MetadataAddress"];
            options.Wtrealm = builder.Configuration["Authentication:WsFederation:Realm"];
            options.CallbackPath = "/signin-wsfed";
        });
    
  • Add login buttons in your web app’s UI that link to /login/google and /login/wsfed (you’ll need to set up these routes to trigger the external login flow).
  • Sync external users to your DB: After the external login callback, take the user’s info (like email, name) and send it to your API to create or link a local Identity user.
4. Common Pitfalls to Avoid
  • Database Access: Ensure your public server can reach your local database server (check firewall rules, network permissions, and connection string accuracy).
  • CORS: If your web app and API are on different domains, configure CORS in the API to allow the web app’s origin.
  • Token Security: Always use HTTPS to transmit JWT tokens between the web app and API. Set reasonable token expiration times and secure your signing key.
  • User Association: Make sure users who log in with multiple external providers (e.g., Google and WS-Federation) are linked to the same local user account to avoid duplicates.

Overall, you’re on the right track—.NET Identity is perfect for your use case. If you get stuck on a specific code snippet or configuration step, share more details about your project structure, and we can troubleshoot further.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 19:24:09