Asp.Net Core 2基于令牌的身份验证技术求助(VS2017社区版环境)
Hey there! Since you're new to ASP.NET Core and token-based authentication, I’ll walk you through a complete, beginner-friendly example that works perfectly with Visual Studio Community 2017. Let’s break this down step by step, with code you can copy-paste and test right away.
Open Visual Studio 2017, go to File > New > Project, select ASP.NET Core Web Application, name your project, and choose the Web API template (stick with ASP.NET Core 2.2, the latest fully supported version for VS2017).
You’ll need a few packages to handle JWT authentication. Open the NuGet Package Manager (right-click your project > Manage NuGet Packages) and install these:
Microsoft.AspNetCore.Authentication.JwtBearerMicrosoft.IdentityModel.TokensSystem.IdentityModel.Tokens.Jwt
Alternatively, run these commands in the Package Manager Console:
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 2.2.0 Install-Package Microsoft.IdentityModel.Tokens -Version 5.4.0 Install-Package System.IdentityModel.Tokens.Jwt -Version 5.4.0
Next, we’ll set up the authentication services and middleware. Open Startup.cs and update the ConfigureServices and Configure methods:
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { // Add controller support services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // Configure JWT authentication var secretKey = Encoding.ASCII.GetBytes("YourSuperSecureSecretKey_AtLeast16CharsLong"); // Use env vars in production! services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; // Set to true in production options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(secretKey), ValidateIssuer = false, // Disable for dev; set your actual issuer in production ValidateAudience = false // Disable for dev; set your actual audience in production }; }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); // Important: Add authentication middleware BEFORE MVC app.UseAuthentication(); app.UseMvc(); } }
Let’s create an AuthController to handle user login and issue JWT tokens. Right-click your project > Add > Controller > API Controller - Empty, name it AuthController:
using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; [Route("api/[controller]")] [ApiController] public class AuthController : ControllerBase { // POST api/auth/login [HttpPost("login")] public IActionResult Login([FromBody] LoginRequest loginRequest) { // In production, replace this with database validation! if (loginRequest.Username == "demoUser" && loginRequest.Password == "demoPass123") { // Create claims (user data stored in the token) var claims = new[] { new Claim(ClaimTypes.Name, loginRequest.Username), new Claim(ClaimTypes.Role, "User"), // Add roles or custom claims as needed new Claim("CustomClaim", "MyCustomValue") }; var secretKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("YourSuperSecureSecretKey_AtLeast16CharsLong")); var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); // Create the JWT token var token = new JwtSecurityToken( issuer: null, // Set your issuer URL in production audience: null, // Set your audience URL in production claims: claims, expires: DateTime.Now.AddHours(1), // Token expires after 1 hour signingCredentials: signingCredentials); // Return the token as JSON return Ok(new { Token = new JwtSecurityTokenHandler().WriteToken(token), Expiration = token.ValidTo }); } // If credentials are invalid, return 401 Unauthorized return Unauthorized("Invalid username or password"); } } // Model for login requests public class LoginRequest { public string Username { get; set; } public string Password { get; set; } }
Now let’s make an endpoint that requires a valid token to access. Open the auto-generated ValuesController and add the [Authorize] attribute:
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; [Route("api/[controller]")] [ApiController] [Authorize] // This makes the entire controller require authentication public class ValuesController : ControllerBase { // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { // Access current user's data from the token var currentUsername = User.Identity.Name; var userRoles = User.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value); return new List<string> { "Hello from protected endpoint!", $"Current User: {currentUsername}", $"Roles: {string.Join(", ", userRoles)}" }; } }
Here’s how to test your setup:
- Run the project (press F5). Note the HTTPS port (looks like
https://localhost:xxxx). - Use Postman, curl, or VS’s built-in API tester to send a POST request to
https://localhost:xxxx/api/auth/loginwith this JSON body:{ "username": "demoUser", "password": "demoPass123" } - You’ll get a
Tokenin the response. Copy this token. - Send a GET request to
https://localhost:xxxx/api/values, and add this header to the request:Authorization: Bearer YOUR_COPIED_TOKEN_HERE - You should see the protected data returned!
- Never hardcode secrets: Store your JWT key in environment variables or
appsettings.json(useConfiguration["Jwt:SecretKey"]to read it). - Enable HTTPS: Set
RequireHttpsMetadata = truein production to ensure tokens are only transmitted over secure connections. - Configure Issuer/Audience: Set
ValidateIssuer = trueandValidateAudience = true, then specify valid issuers/audience values to prevent token spoofing. - Implement refresh tokens: For longer sessions, add a refresh token mechanism so users don’t have to log in every hour.
内容的提问来源于stack exchange,提问作者Shahjahan

