Adding locations micro-service
This commit is contained in:
@@ -1,17 +1,17 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Bcrypt.Net-Next" Version="4.0.3" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.8" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.8" />
|
||||
<PackageReference Include="MongoDB.Driver" Version="3.4.3" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Bcrypt.Net-Next" Version="4.0.3" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.8" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.8" />
|
||||
<PackageReference Include="MongoDB.Driver" Version="3.4.3" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<ActiveDebugProfile>https</ActiveDebugProfile>
|
||||
</PropertyGroup>
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<ActiveDebugProfile>https</ActiveDebugProfile>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -1,6 +1,6 @@
|
||||
@AuthApi_HostAddress = http://localhost:5279
|
||||
|
||||
GET {{AuthApi_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
@AuthApi_HostAddress = http://localhost:5279
|
||||
|
||||
GET {{AuthApi_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
|
||||
@@ -1,113 +1,113 @@
|
||||
using AuthApi.Models;
|
||||
using AuthApi.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
|
||||
namespace AuthApi.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class AuthController : ControllerBase
|
||||
{
|
||||
private readonly UserService _users;
|
||||
private readonly IConfiguration _cfg;
|
||||
private readonly BlacklistService _blacklist;
|
||||
|
||||
public AuthController(UserService users, IConfiguration cfg, BlacklistService blacklist)
|
||||
{
|
||||
_users = users; _cfg = cfg; _blacklist = blacklist;
|
||||
}
|
||||
|
||||
[HttpPost("register")]
|
||||
public async Task<IActionResult> Register([FromBody] RegisterRequest req)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(req.Username) || string.IsNullOrWhiteSpace(req.Password))
|
||||
return BadRequest("Username and password required");
|
||||
|
||||
if (await _users.GetByUsernameAsync(req.Username) != null)
|
||||
return BadRequest("User already exists");
|
||||
|
||||
var hash = BCrypt.Net.BCrypt.HashPassword(req.Password);
|
||||
var user = new User { Username = req.Username, PasswordHash = hash, Role = "USER", Email = req.Email };
|
||||
await _users.CreateAsync(user);
|
||||
return Ok("User created");
|
||||
}
|
||||
|
||||
[HttpPost("login")]
|
||||
public async Task<IActionResult> Login([FromBody] LoginRequest req)
|
||||
{
|
||||
var user = await _users.GetByUsernameAsync(req.Username);
|
||||
if (user == null || !BCrypt.Net.BCrypt.Verify(req.Password, user.PasswordHash))
|
||||
return Unauthorized();
|
||||
|
||||
var (accessToken, jti, expUtc) = GenerateJwtToken(user);
|
||||
user.RefreshToken = Guid.NewGuid().ToString("N");
|
||||
user.RefreshTokenExpiry = DateTime.UtcNow.AddDays(7);
|
||||
await _users.UpdateAsync(user);
|
||||
|
||||
return Ok(new { accessToken, refreshToken = user.RefreshToken, user.Username, user.Role, jti, exp = expUtc });
|
||||
}
|
||||
|
||||
[HttpPost("refresh")]
|
||||
public async Task<IActionResult> Refresh([FromBody] RefreshRequest req)
|
||||
{
|
||||
var user = await _users.GetByUsernameAsync(req.Username);
|
||||
if (user == null || user.RefreshToken != req.RefreshToken || user.RefreshTokenExpiry < DateTime.UtcNow)
|
||||
return Unauthorized("Invalid or expired refresh token");
|
||||
|
||||
var (accessToken, _, expUtc) = GenerateJwtToken(user);
|
||||
return Ok(new { accessToken, exp = expUtc });
|
||||
}
|
||||
|
||||
[HttpPost("logout")]
|
||||
[Authorize(Roles = "USER,SUPER")]
|
||||
public async Task<IActionResult> Logout()
|
||||
{
|
||||
var token = HttpContext.Request.Headers["Authorization"].FirstOrDefault()?.Replace("Bearer ", "");
|
||||
if (string.IsNullOrWhiteSpace(token)) return BadRequest("Token missing");
|
||||
var jwt = new JwtSecurityTokenHandler().ReadJwtToken(token);
|
||||
await _blacklist.AddToBlacklistAsync(jwt.Id, jwt.ValidTo);
|
||||
return Ok("Logged out.");
|
||||
}
|
||||
|
||||
[HttpPost("role")]
|
||||
[Authorize(Roles = "SUPER")]
|
||||
public async Task<IActionResult> ChangeUserRole([FromBody] ChangeRoleRequest req)
|
||||
{
|
||||
if (req.NewRole is not ("USER" or "SUPER")) return BadRequest("Role must be 'USER' or 'SUPER'");
|
||||
var user = await _users.GetByUsernameAsync(req.Username);
|
||||
if (user is null) return NotFound("User not found");
|
||||
user.Role = req.NewRole;
|
||||
await _users.UpdateAsync(user);
|
||||
return Ok($"{req.Username}'s role updated to {req.NewRole}");
|
||||
}
|
||||
|
||||
[HttpGet("users")]
|
||||
[Authorize(Roles = "SUPER")]
|
||||
public async Task<IActionResult> GetAllUsers() => Ok(await _users.GetAllAsync());
|
||||
|
||||
private (string token, string jti, DateTime expUtc) GenerateJwtToken(User user)
|
||||
{
|
||||
var key = Encoding.UTF8.GetBytes(_cfg["Jwt:Key"]!);
|
||||
var issuer = _cfg["Jwt:Issuer"] ?? "GameAuthApi";
|
||||
var audience = _cfg["Jwt:Audience"] ?? issuer;
|
||||
|
||||
var creds = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256);
|
||||
var jti = Guid.NewGuid().ToString("N");
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim(ClaimTypes.Name, user.Username),
|
||||
new Claim(ClaimTypes.NameIdentifier, user.Id),
|
||||
new Claim(ClaimTypes.Role, user.Role),
|
||||
new Claim(JwtRegisteredClaimNames.Jti, jti)
|
||||
};
|
||||
|
||||
var exp = DateTime.UtcNow.AddMinutes(15);
|
||||
var token = new JwtSecurityToken(issuer, audience, claims, expires: exp, signingCredentials: creds);
|
||||
return (new JwtSecurityTokenHandler().WriteToken(token), jti, exp);
|
||||
}
|
||||
}
|
||||
using AuthApi.Models;
|
||||
using AuthApi.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
|
||||
namespace AuthApi.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class AuthController : ControllerBase
|
||||
{
|
||||
private readonly UserService _users;
|
||||
private readonly IConfiguration _cfg;
|
||||
private readonly BlacklistService _blacklist;
|
||||
|
||||
public AuthController(UserService users, IConfiguration cfg, BlacklistService blacklist)
|
||||
{
|
||||
_users = users; _cfg = cfg; _blacklist = blacklist;
|
||||
}
|
||||
|
||||
[HttpPost("register")]
|
||||
public async Task<IActionResult> Register([FromBody] RegisterRequest req)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(req.Username) || string.IsNullOrWhiteSpace(req.Password))
|
||||
return BadRequest("Username and password required");
|
||||
|
||||
if (await _users.GetByUsernameAsync(req.Username) != null)
|
||||
return BadRequest("User already exists");
|
||||
|
||||
var hash = BCrypt.Net.BCrypt.HashPassword(req.Password);
|
||||
var user = new User { Username = req.Username, PasswordHash = hash, Role = "USER", Email = req.Email };
|
||||
await _users.CreateAsync(user);
|
||||
return Ok("User created");
|
||||
}
|
||||
|
||||
[HttpPost("login")]
|
||||
public async Task<IActionResult> Login([FromBody] LoginRequest req)
|
||||
{
|
||||
var user = await _users.GetByUsernameAsync(req.Username);
|
||||
if (user == null || !BCrypt.Net.BCrypt.Verify(req.Password, user.PasswordHash))
|
||||
return Unauthorized();
|
||||
|
||||
var (accessToken, jti, expUtc) = GenerateJwtToken(user);
|
||||
user.RefreshToken = Guid.NewGuid().ToString("N");
|
||||
user.RefreshTokenExpiry = DateTime.UtcNow.AddDays(7);
|
||||
await _users.UpdateAsync(user);
|
||||
|
||||
return Ok(new { accessToken, refreshToken = user.RefreshToken, user.Username, user.Role, jti, exp = expUtc });
|
||||
}
|
||||
|
||||
[HttpPost("refresh")]
|
||||
public async Task<IActionResult> Refresh([FromBody] RefreshRequest req)
|
||||
{
|
||||
var user = await _users.GetByUsernameAsync(req.Username);
|
||||
if (user == null || user.RefreshToken != req.RefreshToken || user.RefreshTokenExpiry < DateTime.UtcNow)
|
||||
return Unauthorized("Invalid or expired refresh token");
|
||||
|
||||
var (accessToken, _, expUtc) = GenerateJwtToken(user);
|
||||
return Ok(new { accessToken, exp = expUtc });
|
||||
}
|
||||
|
||||
[HttpPost("logout")]
|
||||
[Authorize(Roles = "USER,SUPER")]
|
||||
public async Task<IActionResult> Logout()
|
||||
{
|
||||
var token = HttpContext.Request.Headers["Authorization"].FirstOrDefault()?.Replace("Bearer ", "");
|
||||
if (string.IsNullOrWhiteSpace(token)) return BadRequest("Token missing");
|
||||
var jwt = new JwtSecurityTokenHandler().ReadJwtToken(token);
|
||||
await _blacklist.AddToBlacklistAsync(jwt.Id, jwt.ValidTo);
|
||||
return Ok("Logged out.");
|
||||
}
|
||||
|
||||
[HttpPost("role")]
|
||||
[Authorize(Roles = "SUPER")]
|
||||
public async Task<IActionResult> ChangeUserRole([FromBody] ChangeRoleRequest req)
|
||||
{
|
||||
if (req.NewRole is not ("USER" or "SUPER")) return BadRequest("Role must be 'USER' or 'SUPER'");
|
||||
var user = await _users.GetByUsernameAsync(req.Username);
|
||||
if (user is null) return NotFound("User not found");
|
||||
user.Role = req.NewRole;
|
||||
await _users.UpdateAsync(user);
|
||||
return Ok($"{req.Username}'s role updated to {req.NewRole}");
|
||||
}
|
||||
|
||||
[HttpGet("users")]
|
||||
[Authorize(Roles = "SUPER")]
|
||||
public async Task<IActionResult> GetAllUsers() => Ok(await _users.GetAllAsync());
|
||||
|
||||
private (string token, string jti, DateTime expUtc) GenerateJwtToken(User user)
|
||||
{
|
||||
var key = Encoding.UTF8.GetBytes(_cfg["Jwt:Key"]!);
|
||||
var issuer = _cfg["Jwt:Issuer"] ?? "GameAuthApi";
|
||||
var audience = _cfg["Jwt:Audience"] ?? issuer;
|
||||
|
||||
var creds = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256);
|
||||
var jti = Guid.NewGuid().ToString("N");
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim(ClaimTypes.Name, user.Username),
|
||||
new Claim(ClaimTypes.NameIdentifier, user.Id),
|
||||
new Claim(ClaimTypes.Role, user.Role),
|
||||
new Claim(JwtRegisteredClaimNames.Jti, jti)
|
||||
};
|
||||
|
||||
var exp = DateTime.UtcNow.AddMinutes(15);
|
||||
var token = new JwtSecurityToken(issuer, audience, claims, expires: exp, signingCredentials: creds);
|
||||
return (new JwtSecurityTokenHandler().WriteToken(token), jti, exp);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
|
||||
WORKDIR /src
|
||||
|
||||
# Copy project file first to take advantage of Docker layer caching
|
||||
COPY ["AuthApi.csproj", "./"]
|
||||
RUN dotnet restore "AuthApi.csproj"
|
||||
|
||||
# Copy the remaining source and publish
|
||||
COPY . .
|
||||
RUN dotnet publish "AuthApi.csproj" -c Release -o /app/publish /p:UseAppHost=false
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final
|
||||
WORKDIR /app
|
||||
COPY --from=build /app/publish .
|
||||
|
||||
ENV ASPNETCORE_URLS=http://+:8080 \
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
ENTRYPOINT ["dotnet", "AuthApi.dll"]
|
||||
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
|
||||
WORKDIR /src
|
||||
|
||||
# Copy project file first to take advantage of Docker layer caching
|
||||
COPY ["AuthApi.csproj", "./"]
|
||||
RUN dotnet restore "AuthApi.csproj"
|
||||
|
||||
# Copy the remaining source and publish
|
||||
COPY . .
|
||||
RUN dotnet publish "AuthApi.csproj" -c Release -o /app/publish /p:UseAppHost=false
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final
|
||||
WORKDIR /app
|
||||
COPY --from=build /app/publish .
|
||||
|
||||
ENV ASPNETCORE_URLS=http://+:8080 \
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
ENTRYPOINT ["dotnet", "AuthApi.dll"]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace AuthApi.Models;
|
||||
|
||||
public class RegisterRequest { public string Username { get; set; } = ""; public string Password { get; set; } = ""; public string? Email { get; set; } }
|
||||
public class LoginRequest { public string Username { get; set; } = ""; public string Password { get; set; } = ""; }
|
||||
public class ChangeRoleRequest { public string Username { get; set; } = ""; public string NewRole { get; set; } = ""; }
|
||||
public class RefreshRequest { public string Username { get; set; } = ""; public string RefreshToken { get; set; } = ""; }
|
||||
namespace AuthApi.Models;
|
||||
|
||||
public class RegisterRequest { public string Username { get; set; } = ""; public string Password { get; set; } = ""; public string? Email { get; set; } }
|
||||
public class LoginRequest { public string Username { get; set; } = ""; public string Password { get; set; } = ""; }
|
||||
public class ChangeRoleRequest { public string Username { get; set; } = ""; public string NewRole { get; set; } = ""; }
|
||||
public class RefreshRequest { public string Username { get; set; } = ""; public string RefreshToken { get; set; } = ""; }
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
using MongoDB.Bson;
|
||||
using MongoDB.Bson.Serialization.Attributes;
|
||||
|
||||
namespace AuthApi.Models;
|
||||
|
||||
public class User
|
||||
{
|
||||
[BsonId] [BsonRepresentation(BsonType.ObjectId)]
|
||||
public string Id { get; set; } = default!;
|
||||
public string Username { get; set; } = default!;
|
||||
public string PasswordHash { get; set; } = default!;
|
||||
public string Role { get; set; } = "USER";
|
||||
public string? Email { get; set; }
|
||||
public string? RefreshToken { get; set; }
|
||||
public DateTime? RefreshTokenExpiry { get; set; }
|
||||
}
|
||||
using MongoDB.Bson;
|
||||
using MongoDB.Bson.Serialization.Attributes;
|
||||
|
||||
namespace AuthApi.Models;
|
||||
|
||||
public class User
|
||||
{
|
||||
[BsonId] [BsonRepresentation(BsonType.ObjectId)]
|
||||
public string Id { get; set; } = default!;
|
||||
public string Username { get; set; } = default!;
|
||||
public string PasswordHash { get; set; } = default!;
|
||||
public string Role { get; set; } = "USER";
|
||||
public string? Email { get; set; }
|
||||
public string? RefreshToken { get; set; }
|
||||
public DateTime? RefreshTokenExpiry { get; set; }
|
||||
}
|
||||
|
||||
@@ -1,86 +1,86 @@
|
||||
using AuthApi.Services;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Services.AddControllers();
|
||||
|
||||
// DI
|
||||
builder.Services.AddSingleton<UserService>();
|
||||
builder.Services.AddSingleton<BlacklistService>();
|
||||
|
||||
// Swagger + JWT auth in Swagger
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen(c =>
|
||||
{
|
||||
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Auth API", Version = "v1" });
|
||||
c.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme
|
||||
{
|
||||
Type = SecuritySchemeType.Http,
|
||||
Scheme = "bearer",
|
||||
BearerFormat = "JWT",
|
||||
Description = "Paste your access token here (no 'Bearer ' prefix needed)."
|
||||
});
|
||||
c.AddSecurityRequirement(new OpenApiSecurityRequirement
|
||||
{
|
||||
{
|
||||
new OpenApiSecurityScheme
|
||||
{
|
||||
Reference = new OpenApiReference
|
||||
{ Type = ReferenceType.SecurityScheme, Id = "bearerAuth" }
|
||||
},
|
||||
Array.Empty<string>()
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// AuthN/JWT
|
||||
var cfg = builder.Configuration;
|
||||
var jwtKey = cfg["Jwt:Key"] ?? throw new Exception("Jwt:Key missing");
|
||||
var issuer = cfg["Jwt:Issuer"] ?? "GameAuthApi";
|
||||
var aud = cfg["Jwt:Audience"] ?? issuer;
|
||||
|
||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(o =>
|
||||
{
|
||||
o.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true, ValidIssuer = issuer,
|
||||
ValidateAudience = true, ValidAudience = aud,
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.FromSeconds(30)
|
||||
};
|
||||
o.Events = new JwtBearerEvents
|
||||
{
|
||||
OnTokenValidated = async ctx =>
|
||||
{
|
||||
var jti = ctx.Principal?.FindFirstValue(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Jti);
|
||||
if (!string.IsNullOrEmpty(jti))
|
||||
{
|
||||
var bl = ctx.HttpContext.RequestServices.GetRequiredService<BlacklistService>();
|
||||
if (await bl.IsBlacklistedAsync(jti)) ctx.Fail("Token revoked");
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.MapGet("/healthz", () => Results.Ok("ok"));
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(o =>
|
||||
{
|
||||
o.SwaggerEndpoint("/swagger/v1/swagger.json", "Auth API v1");
|
||||
o.RoutePrefix = "swagger";
|
||||
});
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
app.MapControllers();
|
||||
app.Run();
|
||||
using AuthApi.Services;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Services.AddControllers();
|
||||
|
||||
// DI
|
||||
builder.Services.AddSingleton<UserService>();
|
||||
builder.Services.AddSingleton<BlacklistService>();
|
||||
|
||||
// Swagger + JWT auth in Swagger
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen(c =>
|
||||
{
|
||||
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Auth API", Version = "v1" });
|
||||
c.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme
|
||||
{
|
||||
Type = SecuritySchemeType.Http,
|
||||
Scheme = "bearer",
|
||||
BearerFormat = "JWT",
|
||||
Description = "Paste your access token here (no 'Bearer ' prefix needed)."
|
||||
});
|
||||
c.AddSecurityRequirement(new OpenApiSecurityRequirement
|
||||
{
|
||||
{
|
||||
new OpenApiSecurityScheme
|
||||
{
|
||||
Reference = new OpenApiReference
|
||||
{ Type = ReferenceType.SecurityScheme, Id = "bearerAuth" }
|
||||
},
|
||||
Array.Empty<string>()
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// AuthN/JWT
|
||||
var cfg = builder.Configuration;
|
||||
var jwtKey = cfg["Jwt:Key"] ?? throw new Exception("Jwt:Key missing");
|
||||
var issuer = cfg["Jwt:Issuer"] ?? "GameAuthApi";
|
||||
var aud = cfg["Jwt:Audience"] ?? issuer;
|
||||
|
||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(o =>
|
||||
{
|
||||
o.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true, ValidIssuer = issuer,
|
||||
ValidateAudience = true, ValidAudience = aud,
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.FromSeconds(30)
|
||||
};
|
||||
o.Events = new JwtBearerEvents
|
||||
{
|
||||
OnTokenValidated = async ctx =>
|
||||
{
|
||||
var jti = ctx.Principal?.FindFirstValue(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Jti);
|
||||
if (!string.IsNullOrEmpty(jti))
|
||||
{
|
||||
var bl = ctx.HttpContext.RequestServices.GetRequiredService<BlacklistService>();
|
||||
if (await bl.IsBlacklistedAsync(jti)) ctx.Fail("Token revoked");
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.MapGet("/healthz", () => Results.Ok("ok"));
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(o =>
|
||||
{
|
||||
o.SwaggerEndpoint("/swagger/v1/swagger.json", "Auth API v1");
|
||||
o.RoutePrefix = "swagger";
|
||||
});
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
app.MapControllers();
|
||||
app.Run();
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://localhost:5279",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "https://localhost:7295;http://localhost:5279",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://localhost:5279",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "https://localhost:7295;http://localhost:5279",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,36 +1,36 @@
|
||||
using MongoDB.Bson.Serialization.Attributes;
|
||||
using MongoDB.Driver;
|
||||
|
||||
namespace AuthApi.Services;
|
||||
|
||||
public class BlacklistedToken
|
||||
{
|
||||
[BsonId] public string Jti { get; set; } = default!;
|
||||
public DateTime ExpiresAt { get; set; }
|
||||
}
|
||||
|
||||
public class BlacklistService
|
||||
{
|
||||
private readonly IMongoCollection<BlacklistedToken> _col;
|
||||
|
||||
public BlacklistService(IConfiguration cfg)
|
||||
{
|
||||
var cs = cfg["MongoDB:ConnectionString"] ?? "mongodb://127.0.0.1:27017";
|
||||
var dbName = cfg["MongoDB:DatabaseName"] ?? "GameDb";
|
||||
var client = new MongoClient(cs);
|
||||
var db = client.GetDatabase(dbName);
|
||||
_col = db.GetCollection<BlacklistedToken>("BlacklistedTokens");
|
||||
|
||||
// TTL index so revocations expire automatically
|
||||
var keys = Builders<BlacklistedToken>.IndexKeys.Ascending(x => x.ExpiresAt);
|
||||
_col.Indexes.CreateOne(new CreateIndexModel<BlacklistedToken>(keys, new CreateIndexOptions { ExpireAfter = TimeSpan.Zero }));
|
||||
}
|
||||
|
||||
public Task AddToBlacklistAsync(string jti, DateTime expiresAt) =>
|
||||
_col.ReplaceOneAsync(x => x.Jti == jti,
|
||||
new BlacklistedToken { Jti = jti, ExpiresAt = expiresAt },
|
||||
new ReplaceOptions { IsUpsert = true });
|
||||
|
||||
public Task<bool> IsBlacklistedAsync(string jti) =>
|
||||
_col.Find(x => x.Jti == jti).AnyAsync();
|
||||
}
|
||||
using MongoDB.Bson.Serialization.Attributes;
|
||||
using MongoDB.Driver;
|
||||
|
||||
namespace AuthApi.Services;
|
||||
|
||||
public class BlacklistedToken
|
||||
{
|
||||
[BsonId] public string Jti { get; set; } = default!;
|
||||
public DateTime ExpiresAt { get; set; }
|
||||
}
|
||||
|
||||
public class BlacklistService
|
||||
{
|
||||
private readonly IMongoCollection<BlacklistedToken> _col;
|
||||
|
||||
public BlacklistService(IConfiguration cfg)
|
||||
{
|
||||
var cs = cfg["MongoDB:ConnectionString"] ?? "mongodb://127.0.0.1:27017";
|
||||
var dbName = cfg["MongoDB:DatabaseName"] ?? "GameDb";
|
||||
var client = new MongoClient(cs);
|
||||
var db = client.GetDatabase(dbName);
|
||||
_col = db.GetCollection<BlacklistedToken>("BlacklistedTokens");
|
||||
|
||||
// TTL index so revocations expire automatically
|
||||
var keys = Builders<BlacklistedToken>.IndexKeys.Ascending(x => x.ExpiresAt);
|
||||
_col.Indexes.CreateOne(new CreateIndexModel<BlacklistedToken>(keys, new CreateIndexOptions { ExpireAfter = TimeSpan.Zero }));
|
||||
}
|
||||
|
||||
public Task AddToBlacklistAsync(string jti, DateTime expiresAt) =>
|
||||
_col.ReplaceOneAsync(x => x.Jti == jti,
|
||||
new BlacklistedToken { Jti = jti, ExpiresAt = expiresAt },
|
||||
new ReplaceOptions { IsUpsert = true });
|
||||
|
||||
public Task<bool> IsBlacklistedAsync(string jti) =>
|
||||
_col.Find(x => x.Jti == jti).AnyAsync();
|
||||
}
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
using AuthApi.Models;
|
||||
using MongoDB.Driver;
|
||||
|
||||
namespace AuthApi.Services;
|
||||
|
||||
public class UserService
|
||||
{
|
||||
private readonly IMongoCollection<User> _col;
|
||||
|
||||
public UserService(IConfiguration cfg)
|
||||
{
|
||||
var cs = cfg["MongoDB:ConnectionString"] ?? "mongodb://127.0.0.1:27017";
|
||||
var dbName = cfg["MongoDB:DatabaseName"] ?? "GameDb";
|
||||
var client = new MongoClient(cs);
|
||||
var db = client.GetDatabase(dbName);
|
||||
_col = db.GetCollection<User>("Users");
|
||||
|
||||
var keys = Builders<User>.IndexKeys.Ascending(u => u.Username);
|
||||
_col.Indexes.CreateOne(new CreateIndexModel<User>(keys, new CreateIndexOptions { Unique = true }));
|
||||
}
|
||||
|
||||
public Task<User?> GetByUsernameAsync(string username) =>
|
||||
_col.Find(u => u.Username == username).FirstOrDefaultAsync();
|
||||
|
||||
public Task CreateAsync(User user) => _col.InsertOneAsync(user);
|
||||
|
||||
public Task UpdateAsync(User user) =>
|
||||
_col.ReplaceOneAsync(u => u.Id == user.Id, user);
|
||||
|
||||
public Task<List<User>> GetAllAsync() =>
|
||||
_col.Find(FilterDefinition<User>.Empty).ToListAsync();
|
||||
}
|
||||
using AuthApi.Models;
|
||||
using MongoDB.Driver;
|
||||
|
||||
namespace AuthApi.Services;
|
||||
|
||||
public class UserService
|
||||
{
|
||||
private readonly IMongoCollection<User> _col;
|
||||
|
||||
public UserService(IConfiguration cfg)
|
||||
{
|
||||
var cs = cfg["MongoDB:ConnectionString"] ?? "mongodb://127.0.0.1:27017";
|
||||
var dbName = cfg["MongoDB:DatabaseName"] ?? "GameDb";
|
||||
var client = new MongoClient(cs);
|
||||
var db = client.GetDatabase(dbName);
|
||||
_col = db.GetCollection<User>("Users");
|
||||
|
||||
var keys = Builders<User>.IndexKeys.Ascending(u => u.Username);
|
||||
_col.Indexes.CreateOne(new CreateIndexModel<User>(keys, new CreateIndexOptions { Unique = true }));
|
||||
}
|
||||
|
||||
public Task<User?> GetByUsernameAsync(string username) =>
|
||||
_col.Find(u => u.Username == username).FirstOrDefaultAsync();
|
||||
|
||||
public Task CreateAsync(User user) => _col.InsertOneAsync(user);
|
||||
|
||||
public Task UpdateAsync(User user) =>
|
||||
_col.ReplaceOneAsync(u => u.Id == user.Id, user);
|
||||
|
||||
public Task<List<User>> GetAllAsync() =>
|
||||
_col.Find(FilterDefinition<User>.Empty).ToListAsync();
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5000" } } },
|
||||
"MongoDB": { "ConnectionString": "mongodb://192.168.86.50:27017", "DatabaseName": "promiscuity" },
|
||||
"Jwt": { "Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!", "Issuer": "promiscuity", "Audience": "promiscuity-auth-api" },
|
||||
"Logging": { "LogLevel": { "Default": "Information" } },
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
{
|
||||
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5000" } } },
|
||||
"MongoDB": { "ConnectionString": "mongodb://192.168.86.50:27017", "DatabaseName": "promiscuity" },
|
||||
"Jwt": { "Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!", "Issuer": "promiscuity", "Audience": "promiscuity-auth-api" },
|
||||
"Logging": { "LogLevel": { "Default": "Information" } },
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: promiscuity-auth
|
||||
labels:
|
||||
app: promiscuity-auth
|
||||
spec:
|
||||
replicas: 2
|
||||
selector:
|
||||
matchLabels:
|
||||
app: promiscuity-auth
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: promiscuity-auth
|
||||
spec:
|
||||
containers:
|
||||
- name: promiscuity-auth
|
||||
image: promiscuity-auth:latest
|
||||
imagePullPolicy: IfNotPresent
|
||||
ports:
|
||||
- containerPort: 5000
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /healthz
|
||||
port: 5000
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 10
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: promiscuity-auth
|
||||
labels:
|
||||
app: promiscuity-auth
|
||||
spec:
|
||||
replicas: 2
|
||||
selector:
|
||||
matchLabels:
|
||||
app: promiscuity-auth
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: promiscuity-auth
|
||||
spec:
|
||||
containers:
|
||||
- name: promiscuity-auth
|
||||
image: promiscuity-auth:latest
|
||||
imagePullPolicy: IfNotPresent
|
||||
ports:
|
||||
- containerPort: 5000
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /healthz
|
||||
port: 5000
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 10
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: promiscuity-auth
|
||||
labels:
|
||||
app: promiscuity-auth
|
||||
spec:
|
||||
selector:
|
||||
app: promiscuity-auth
|
||||
type: NodePort
|
||||
ports:
|
||||
- name: http
|
||||
port: 80 # cluster port
|
||||
targetPort: 5000 # container port
|
||||
nodePort: 30080 # same external port you've been using
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: promiscuity-auth
|
||||
labels:
|
||||
app: promiscuity-auth
|
||||
spec:
|
||||
selector:
|
||||
app: promiscuity-auth
|
||||
type: NodePort
|
||||
ports:
|
||||
- name: http
|
||||
port: 80 # cluster port
|
||||
targetPort: 5000 # container port
|
||||
nodePort: 30080 # same external port you've been using
|
||||
|
||||
Reference in New Issue
Block a user