main
Peace 11 months ago
parent 8f3ea3a35d
commit 2ed27c0a60
  1. 1
      AspNetCoreApi/AspNetCoreApi.csproj
  2. 28
      AspNetCoreApi/Controllers/AuthController.cs
  3. 26
      AspNetCoreApi/Controllers/NeedAuthController.cs
  4. 27
      AspNetCoreApi/Program.cs
  5. 48
      AspNetCoreApi/Services/JWTAuthenticationService.cs

@ -7,6 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.6" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.6" /> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.6" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.6"> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.6">

@ -0,0 +1,28 @@
using AspNetCoreApi.Services;
using Microsoft.AspNetCore.Mvc;
namespace AspNetCoreApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class AuthController : ControllerBase
{
private readonly JWTAuthenticationService _service;
public AuthController(JWTAuthenticationService service)
{
_service = service;
}
[HttpPost("authenticate")]
public async Task<IActionResult> Authenticate(string username, string password)
{
var token = await _service.Authenticate(username, password);
if (token == null)
{
return Unauthorized();
}
return Ok(new { Token = token });
}
}
}

@ -0,0 +1,26 @@
using AspNetCoreApi.Models;
using AspNetCoreApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace AspNetCoreApi.Controllers
{
[ApiController]
[Authorize]
[Route("[controller]")]
public class NeedAuthController : ControllerBase
{
private readonly ILogger<ProductController> _logger;
public NeedAuthController(ILogger<ProductController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetNeedAuth")]
public string Get()
{
return "Authorized";
}
}
}

@ -3,8 +3,11 @@ using AspNetCoreApi.DbContexts;
using AspNetCoreApi.Middlewares; using AspNetCoreApi.Middlewares;
using AspNetCoreApi.Models; using AspNetCoreApi.Models;
using AspNetCoreApi.Services; using AspNetCoreApi.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace AspNetCoreApi namespace AspNetCoreApi
{ {
@ -32,6 +35,29 @@ namespace AspNetCoreApi
.AddEntityFrameworkStores<AppDbContext>() .AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders(); .AddDefaultTokenProviders();
// JWT Authorization
string jwtKey = "ThisIsMyMyJWTKey1234!ThisIsMyMyJWTKey1234!";
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "MyIssuer",
ValidAudience = "MyAudience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey))
};
});
builder.Services.AddScoped<JWTAuthenticationService>();
// Add services to the container. // Add services to the container.
builder.Services.AddControllers(); builder.Services.AddControllers();
@ -55,6 +81,7 @@ namespace AspNetCoreApi
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();

@ -0,0 +1,48 @@
using AspNetCoreApi.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace AspNetCoreApi.Services
{
public class JWTAuthenticationService
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly string _key = "ThisIsMyMyJWTKey1234!ThisIsMyMyJWTKey1234!";
public JWTAuthenticationService(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task<string> Authenticate(string username, string password)
{
var user = await _userManager.FindByNameAsync(username);
if (user == null)
return null;
if (await _userManager.CheckPasswordAsync(user, password) == false)
return null;
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(_key);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.NameIdentifier, user.Id)
}),
Expires = DateTime.UtcNow.AddHours(0.5),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}
}
Loading…
Cancel
Save