ASP.NET Core API JWT

Models/ApplicationUser.cs

using System.ComponentModel.DataAnnotations;

namespace blog.Models;

public class ApplicationUser
{
    [Key]
    public int Id { get; set; }
    public string PhoneNumber { get; set; } = string.Empty;
    public byte[] PasswordSalt { get; set; } = default!;
    public string PasswordHash { get; set; } = string.Empty;
    public string? NickName { get; set; }
}

 

Data/ApplicationDbContext.cs

using blog.Models;
using Microsoft.EntityFrameworkCore;

namespace blog.Data;

public class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : DbContext(options)
{
    public DbSet<ApplicationUser> Users { get; set; } = default!;

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ApplicationUser>().HasIndex(x => x.PhoneNumber).IsUnique();
    }
}

 

Program.cs

using System.Text;
using xxx.Data;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);

string connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("connection string 'DefaultConnection' is not found");

builder.Services.AddDbContext<ApplicationDbContext>(c => c.UseSqlite(connectionString));
builder.Services.AddAuthentication(c =>
{
    c.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    c.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    c.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(c =>
{
    c.SaveToken = true;
    c.RequireHttpsMetadata = false;
    c.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateLifetime = true,
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = builder.Configuration["JWT:Issuer"],
        ValidAudience = builder.Configuration["JWT:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:Secret"]!))
    };
});

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.EnableTryItOutByDefault();
});

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

 

Models/SeedDb.cs

using Microsoft.AspNetCore.Identity;

namespace blog.Models
{
  public static class SeedDb
  {
    public static void Init(IServiceProvider serviceProvider)
    {
      using ApplicationDbContext context = serviceProvider.GetRequiredService<ApplicationDbContext>();
      if (!context.Users.Any())
      {
        var user = new ApplicationUser
        {

        };

        context.Users.Add(user);
      }
    }
  }
}

 

Controllers/UserController.cs/Login

using blog.Data;
using blog.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using System.Security.Cryptography;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace blog.Controllers;

[ApiController]
[Route("/api/[controller]/[action]")]
public class UserController(ApplicationDbContext context, IConfiguration configuration) : ControllerBase
{
    private readonly ApplicationDbContext context = context;
    private readonly IConfiguration configuration = configuration;

    #region Create User
    [HttpPost]
    public async Task<IActionResult> Create(CreateUser createUser)
    {
        string secret = configuration["Secret"] ?? throw new InvalidOperationException("'Secret' is emtpy.");

        if (createUser.Secret != secret)
        {
            return BadRequest("Secret is incorrect.");
        }

        if (createUser.Password != createUser.ConfirmPassword)
        {
            return BadRequest("Mismatched password.");
        }

        try
        {
            byte[] salt = RandomNumberGenerator.GetBytes(128 / 8);
            string hash = Convert.ToBase64String(KeyDerivation.Pbkdf2(
                password: createUser.Password,
                salt: salt,
                prf: KeyDerivationPrf.HMACSHA256,
                iterationCount: 100000,
                numBytesRequested: 256 / 8
            ));

            var user = new ApplicationUser
            {
                PhoneNumber = createUser.PhoneNumber,
                PasswordSalt = salt,
                PasswordHash = hash
            };

            await context.Users.AddAsync(user);
            await context.SaveChangesAsync();

            return Ok("User created.");
        }
        catch (Exception ex)
        {
            return Problem($"{ex.Message} {ex.InnerException?.Message}");
        }
    }
    #endregion

    #region Login User
    [HttpPost]
    public async Task<IActionResult> Login(Models.Login login)
    {
        try
        {
            var user = await context.Users.FirstAsync(x => x.PhoneNumber == login.PhoneNumber);

            if (user is null)
            {
                return NotFound("User does not exist.");
            }

            string hash = Convert.ToBase64String(KeyDerivation.Pbkdf2(
                password: login.Password,
                salt: user.PasswordSalt,
                prf: KeyDerivationPrf.HMACSHA256,
                iterationCount: 100000,
                numBytesRequested: 256 / 8
            ));

            if (hash != user.PasswordHash)
            {
                return Unauthorized("Password incorrect.");
            }

            var claims = new List<Claim>
            {
                new("Id", user.Id.ToString()),
                new("PhoneNumber", user.PhoneNumber)
            };

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:Secret"]!));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var securityToken = new JwtSecurityToken(
                issuer: configuration["JWT:Issuer"],
                audience: configuration["JWT:Audience"],
                claims: claims,
                signingCredentials: credentials,
                expires: DateTime.Now.AddYears(1)
            );

            var token = new JwtSecurityTokenHandler().WriteToken(securityToken);

            return Ok(new { token });
        }
        catch (Exception ex)
        {
            return Problem($"{ex.Message} {ex.InnerException?.Message}");
        }
    }
    #endregion
}

 

Fetch User Principal

using System.Security.Claims;

namespace blog.Models;

public class UserInfo(ClaimsPrincipal user)
{
    private ClaimsIdentity? claimsIdentity = user.Identity as ClaimsIdentity;

    public int Id
    {
        get
        {
            return Convert.ToInt32(claimsIdentity?.FindFirst("Id")?.Value);
        }
    }

    public string PhoneNumber
    {
        get
        {
            return claimsIdentity?.FindFirst("PhoneNumber")?.Value!;
        }
    }
}
[HttpGet]
[Authorize]
public IActionResult Get()
{
    var userInfo = new UserInfo(User);
    return Ok(new { userInfo.Id, userInfo.PhoneNumber });
}
创建时间:11/30/2022 11:19:51 AM 修改时间:6/11/2024 1:44:10 PM