Web应用、Web API与移动应用间统一认证方案咨询
Hey there! Let's break down some practical, self-hosted authentication solutions that work seamlessly for your .NET Core Web API, .NET Core Web App, and Xamarin mobile app—no third-party services required. All these approaches will replace your existing Basic Auth with a unified, more secure model.
This is the most straightforward approach for cross-platform scenarios, as JWT tokens work equally well in web apps and mobile apps.
Step 1: Configure Your Web API to Support JWT
In your API's Program.cs (for .NET 6+):
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, // Pull these values from your appsettings.json (never hardcode!) ValidIssuer = builder.Configuration["Jwt:Issuer"], ValidAudience = builder.Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:SecretKey"])) }; }); // Don't forget to add these middleware calls in the correct order app.UseAuthentication(); app.UseAuthorization();
Step 2: Add a Login Endpoint to Your API
Create an endpoint to validate user credentials and issue JWT tokens:
[AllowAnonymous] [HttpPost("auth/login")] public IActionResult Login([FromBody] LoginRequest model) { // Replace this with your existing user validation logic (e.g., check against a database) if (IsValidUser(model.Username, model.Password)) { var claims = new List<Claim> { new Claim(ClaimTypes.Name, model.Username), // Add roles or custom claims as needed new Claim(ClaimTypes.Role, "AuthenticatedUser") }; var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.UTF8.GetBytes(builder.Configuration["Jwt:SecretKey"]); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.UtcNow.AddHours(2), // Adjust token lifetime as needed Issuer = builder.Configuration["Jwt:Issuer"], Audience = builder.Configuration["Jwt:Audience"], SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return Ok(new { Token = tokenHandler.WriteToken(token) }); } return Unauthorized("Invalid username or password"); }
Step 3: Integrate with .NET Core Web App
Store the JWT token securely (e.g., in an HttpOnly cookie or session) and attach it to every API request:
// Example login call in your Web App var loginResponse = await _httpClient.PostAsJsonAsync("https://yourapi.com/auth/login", new LoginRequest { Username = "user123", Password = "securePass!" }); var tokenResult = await loginResponse.Content.ReadFromJsonAsync<TokenResponse>(); // Store token in HttpOnly cookie for security Response.Cookies.Append("AuthToken", tokenResult.Token, new CookieOptions { HttpOnly = true, Secure = true, Expires = DateTime.UtcNow.AddHours(2) }); // For subsequent API calls, retrieve the token and add it to the request header var token = Request.Cookies["AuthToken"]; _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
Step 4: Integrate with Xamarin App
Use Xamarin's SecureStorage to store the token securely, then attach it to API requests:
// Login flow in Xamarin var client = new HttpClient(); var loginContent = new StringContent(JsonSerializer.Serialize(new { Username = "user123", Password = "securePass!" }), Encoding.UTF8, "application/json"); var loginResponse = await client.PostAsync("https://yourapi.com/auth/login", loginContent); if (loginResponse.IsSuccessStatusCode) { var tokenResult = await loginResponse.Content.ReadFromJsonAsync<TokenResponse>(); // Store token securely await SecureStorage.SetAsync("AuthToken", tokenResult.Token); } // Subsequent API calls var authToken = await SecureStorage.GetAsync("AuthToken"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
If your web app relies heavily on server-side sessions (e.g., MVC/Razor Pages), you can use cookie authentication for the web app while keeping JWT for the mobile app—your API will support both.
Step 1: Configure API for Dual Authentication
builder.Services.AddAuthentication() // Cookie auth for web app .AddCookie(options => { options.Cookie.Name = "WebAppAuthCookie"; options.LoginPath = "/auth/login-web"; options.ExpireTimeSpan = TimeSpan.FromHours(8); }) // JWT auth for mobile .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => { // Same JWT configuration as Option 1 }); // Set default authorization policy to accept both auth methods builder.Services.AddAuthorization(options => { options.DefaultPolicy = new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser() .Build(); });
Step 2: Add Web App Login Endpoint
[AllowAnonymous] [HttpPost("auth/login-web")] public async Task<IActionResult> LoginWeb([FromBody] LoginRequest model) { if (IsValidUser(model.Username, model.Password)) { var claims = new List<Claim> { new Claim(ClaimTypes.Name, model.Username) }; var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties { IsPersistent = model.RememberMe }); return Ok(); } return Unauthorized(); }
Your web app will automatically attach the auth cookie to API requests, while your Xamarin app uses the JWT flow from Option 1.
If you need features like refresh tokens, role-based access control, or standardized OAuth2 flows, host your own Identity Server (Duende IdentityServer is the modern, open-source successor to IdentityServer4). This is still self-hosted—no third-party services involved.
Key benefits:
- Supports Authorization Code Flow with PKCE (secure for both web and mobile apps)
- Built-in token refresh and revocation
- Centralized user management (can integrate with ASP.NET Core Identity)
High-Level Steps:
- Create a separate Identity Server project and configure client apps (web app + Xamarin) and API resources.
- Update your Web API to validate JWT tokens issued by your Identity Server.
- In your web app, redirect users to the Identity Server login page for authentication.
- In your Xamarin app, use the IdentityModel library to implement the PKCE flow and retrieve tokens.
- Token Storage: Always store JWTs securely—use HttpOnly cookies for web apps, and
SecureStoragefor Xamarin. Never store tokens in plain text or unencrypted storage. - Password Hashing: Ensure user passwords are hashed (use ASP.NET Core Identity's
PasswordHasheror similar) in your database—never store plain text passwords. - Secret Management: Keep your JWT signing key and Identity Server secrets in environment variables or a secure configuration store (not in code or appsettings.json in production).
- Token Expiry: Set reasonable token lifetimes and implement refresh token functionality to avoid frequent user logins.
内容的提问来源于stack exchange,提问作者DSA

