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

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.

1. Create a New ASP.NET Core Web API Project

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).

2. Install Required NuGet Packages

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.JwtBearer
  • Microsoft.IdentityModel.Tokens
  • System.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
3. Configure JWT Authentication in Startup.cs

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();
    }
}
4. Build a Login Endpoint to Generate Tokens

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; }
}
5. Create a Protected API Endpoint

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)}"
        };
    }
}
6. Test the Flow

Here’s how to test your setup:

  1. Run the project (press F5). Note the HTTPS port (looks like https://localhost:xxxx).
  2. Use Postman, curl, or VS’s built-in API tester to send a POST request to https://localhost:xxxx/api/auth/login with this JSON body:
    {
        "username": "demoUser",
        "password": "demoPass123"
    }
    
  3. You’ll get a Token in the response. Copy this token.
  4. Send a GET request to https://localhost:xxxx/api/values, and add this header to the request:
    Authorization: Bearer YOUR_COPIED_TOKEN_HERE
    
  5. You should see the protected data returned!
Key Production Tips
  • Never hardcode secrets: Store your JWT key in environment variables or appsettings.json (use Configuration["Jwt:SecretKey"] to read it).
  • Enable HTTPS: Set RequireHttpsMetadata = true in production to ensure tokens are only transmitted over secure connections.
  • Configure Issuer/Audience: Set ValidateIssuer = true and ValidateAudience = 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:24:48