ASP.NET Core 2 API中基于请求传递Bearer Token的身份验证最佳实践
Hey there! Let's walk through the best practices for implementing Bearer Token (JWT) authentication in your ASP.NET Core 2 API—this is a standard setup, and I’ve helped lots of teams nail this securely and efficiently.
First, you’ll need to set up the authentication middleware in your Startup.cs. Start by adding the required services, then enable authentication in the request pipeline.
Step 1: Add Authentication Services
In ConfigureServices, register the JWT bearer authentication scheme with validation parameters tailored to your setup:
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; public void ConfigureServices(IServiceCollection services) { // Add MVC core services services.AddMvc(); // Configure JWT authentication services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { // Core security checks (don’t skip these in production!) ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, // Match these values to what your token issuer uses ValidIssuer = "your-api-issuer", ValidAudience = "your-api-audience", // Use a strong, secret key (store this securely in production) IssuerSigningKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])) }; }); }
Step 2: Enable Authentication in the Pipeline
In the Configure method, make sure to add UseAuthentication() before UseMvc()—this ensures authentication runs before routing and endpoint authorization (a common mistake to avoid!):
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Critical: Enable authentication middleware first app.UseAuthentication(); app.UseMvc(); }
Once the middleware is set up, lock down your endpoints using the [Authorize] attribute. You can apply it to entire controllers or individual actions:
Protect an Entire Controller
[Authorize] [Route("api/[controller]")] public class OrdersController : Controller { // All actions here require a valid Bearer Token [HttpGet] public IActionResult GetUserOrders() { // Return user-specific order data } }
Protect a Single Action
[Route("api/[controller]")] public class ProductsController : Controller { [HttpGet] public IActionResult GetPublicProducts() { // No auth required for public product listings } [Authorize] [HttpPost] public IActionResult CreateProduct([FromBody] Product product) { // Requires valid token to create a product } }
Use Policies for Granular Access Control
For role-based or claim-based authorization, define custom policies in ConfigureServices:
services.AddAuthorization(options => { options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin")); options.AddPolicy("PremiumUser", policy => policy.RequireClaim("SubscriptionTier", "Premium")); });
Then apply the policy to your endpoint:
[Authorize(Policy = "AdminOnly")] [HttpDelete("{id}")] public IActionResult DeleteProduct(int id) { // Only users with the "Admin" role can delete products }
Beyond the basic setup, these practices will keep your authentication layer robust:
- Mandate HTTPS: Bearer Tokens are sent in the
Authorizationheader—HTTPS prevents interception and tampering. Never deploy to production without it. - Shorten token lifetimes: Set access tokens to expire quickly (15-30 minutes). Use refresh tokens to let users get new access tokens without re-authenticating.
- Secure refresh tokens: Store refresh tokens in HttpOnly, Secure cookies (to block XSS attacks) or encrypt them in your database. Avoid local storage if possible.
- Use strong signing keys: For symmetric keys, use a 256-bit+ random string. In production, store this key in a secure vault (not plaintext in
appsettings.json). For higher security, use asymmetric RSA keys instead. - Never skip validation checks: Don’t set
ValidateIssuerorValidateLifetimetofalsein production—these checks block forged or expired tokens. - Avoid sensitive data in JWTs: JWTs are Base64-encoded (not encrypted), so anyone can decode them. Never put passwords, PII, or sensitive business data in the payload.
- Log authentication failures: Track failed auth attempts to detect brute-force attacks. Hook into the JWT middleware’s events to log these:
options.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { _logger.LogError("Auth failed: {Reason}", context.Exception.Message); return Task.CompletedTask; } };
To verify your API works as expected, send a request with the Bearer Token in the Authorization header:
GET /api/orders HTTP/1.1 Host: your-api-domain.com Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Use tools like Postman or curl to test: you should get a 401 Unauthorized without a valid token, and 200 OK with a valid one.
内容的提问来源于stack exchange,提问作者Murtoza

