mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-05 18:48:41 +00:00
feat(backend:authentication): implement API key authentication scheme and update authorization policies
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SharpbinV3.Server.Extensions;
|
||||
using SharpbinV3.Server.Services;
|
||||
|
||||
namespace SharpbinV3.Server.Authentication
|
||||
{
|
||||
public sealed class ApiKeyAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder,
|
||||
ApiKeyService apiKeyService
|
||||
) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
private readonly ApiKeyService _apiKeyService = apiKeyService;
|
||||
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
var apiKeyString = Context.GetApiKey();
|
||||
if (string.IsNullOrEmpty(apiKeyString))
|
||||
return AuthenticateResult.NoResult();
|
||||
|
||||
var apiKey = await _apiKeyService.GetByKeyAsync(apiKeyString);
|
||||
if (apiKey == null || apiKey.User == null)
|
||||
return AuthenticateResult.Fail("Invalid API key.");
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new("uuid", apiKey.User.UUID.ToString()),
|
||||
new("username", apiKey.User.Username ?? ""),
|
||||
new("displayname", apiKey.User.DisplayName ?? ""),
|
||||
new("totp_enabled", (apiKey.User.Totp != null).ToString()),
|
||||
};
|
||||
|
||||
if (apiKey.User.Roles != null)
|
||||
claims.AddRange(apiKey.User.Roles.Select(r => new Claim(ClaimTypes.Role, r.ToString())));
|
||||
|
||||
var identity = new ClaimsIdentity(claims, AuthSchemes.ApiKey);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
var ticket = new AuthenticationTicket(principal, AuthSchemes.ApiKey);
|
||||
|
||||
Context.SetApiKeyContext(apiKey);
|
||||
await _apiKeyService.UpdateLastUsedAsync(apiKey.UUID);
|
||||
|
||||
return AuthenticateResult.Success(ticket);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace SharpbinV3.Server.Authentication
|
||||
{
|
||||
public static class AuthSchemes
|
||||
{
|
||||
public const string Combined = "Combined";
|
||||
public const string ApiKey = "ApiKey";
|
||||
}
|
||||
}
|
||||
@@ -167,7 +167,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Authorize]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[Route("totp/enroll")]
|
||||
public async Task<IActionResult> StartTotpEnrollment()
|
||||
{
|
||||
@@ -190,16 +190,12 @@ namespace SharpbinV3.Server.Controllers
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[Route("totp/enable")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> EnableTotp([FromBody] EnableTotpDto request)
|
||||
{
|
||||
var uuidClaim = User.Claims.FirstOrDefault(c => c.Type == "UUID")?.Value;
|
||||
if (string.IsNullOrEmpty(uuidClaim))
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
|
||||
var uuid = Guid.Parse(uuidClaim);
|
||||
var uuid = Guid.Parse(User.FindFirst("uuid")!.Value);
|
||||
if (string.IsNullOrWhiteSpace(request.Secret) || string.IsNullOrWhiteSpace(request.Code))
|
||||
return BadRequest(new { success = false, message = "Secret and code are required." });
|
||||
|
||||
@@ -224,7 +220,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[Route("totp/disable")]
|
||||
public async Task<IActionResult> DisableTotp([FromBody] DisableTotpDto dto)
|
||||
{
|
||||
@@ -245,7 +241,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[Route("apikey/create")]
|
||||
[EnableRateLimiting("Strict")]
|
||||
public async Task<IActionResult> CreateApiKey([FromBody] CreateApiKeyRequest request)
|
||||
@@ -309,7 +305,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
}
|
||||
|
||||
[HttpDelete]
|
||||
[Authorize]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[Route("apikey/{uuid}")]
|
||||
public async Task<IActionResult> DeleteApiKey(string uuid)
|
||||
{
|
||||
|
||||
@@ -156,7 +156,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
[HttpPut]
|
||||
[Route("{id}")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> EditPaste(string id)
|
||||
{
|
||||
string content = await new StreamReader(Request.Body).ReadToEndAsync();
|
||||
@@ -167,9 +167,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
if (paste == null)
|
||||
return StatusCode(404, new { success = false, message = "Paste not found." });
|
||||
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
||||
@@ -185,16 +183,14 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
[HttpPatch]
|
||||
[Route("{id}")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] UpdatePasteDto request)
|
||||
{
|
||||
var paste = await _pasteService.Get(id);
|
||||
if (paste == null)
|
||||
return NotFound(new { success = false, message = "Paste not found." });
|
||||
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
|
||||
@@ -246,16 +242,14 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
[HttpDelete]
|
||||
[Route("{id}")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> DeletePaste(string id)
|
||||
{
|
||||
var paste = await _pasteService.Get(id);
|
||||
if (paste == null)
|
||||
return NotFound(new { success = false, message = "Paste not found." });
|
||||
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
||||
@@ -298,16 +292,14 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
[HttpPost]
|
||||
[Route("{id}/report")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> ReportPaste(string id, [FromBody] ReportDto request)
|
||||
{
|
||||
var paste = await _pasteService.Get(id);
|
||||
if (paste == null)
|
||||
return NotFound(new { success = false, message = "Paste not found." });
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
|
||||
if (!Enum.IsDefined(reportType))
|
||||
@@ -347,7 +339,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
[HttpPatch]
|
||||
[Route("{id}/report/{reportId}")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> ModifyPasteReport(string id, int reportId, [FromBody] ReportDto request)
|
||||
{
|
||||
@@ -359,9 +351,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
|
||||
return NotFound(new { success = false, message = "Report not found." });
|
||||
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
|
||||
@@ -383,7 +373,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
[HttpDelete]
|
||||
[Route("{id}/report/{reportId}")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> DeletePasteReport(string id, int reportId)
|
||||
{
|
||||
@@ -395,9 +385,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
|
||||
return NotFound(new { success = false, message = "Report not found." });
|
||||
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
|
||||
|
||||
@@ -15,12 +15,10 @@ namespace SharpbinV3.Server.Controllers
|
||||
[Route("{reportId:int}")]
|
||||
[HttpGet]
|
||||
[EnableRateLimiting("Sliding")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> GetReportById(int reportId)
|
||||
{
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user is null)
|
||||
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
var report = await reportService.GetReportByID(reportId);
|
||||
if (report is null)
|
||||
@@ -57,12 +55,10 @@ namespace SharpbinV3.Server.Controllers
|
||||
[Route("{reportId:int}")]
|
||||
[HttpPatch]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> UpdateReport(int reportId, [FromBody] ReportUpdateDto request)
|
||||
{
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user is null)
|
||||
return Unauthorized(new { success = false, message = "You must be logged in to update reports." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to update reports." });
|
||||
|
||||
@@ -127,12 +123,10 @@ namespace SharpbinV3.Server.Controllers
|
||||
[Route("pastes")]
|
||||
[HttpGet]
|
||||
[EnableRateLimiting("Sliding")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> GetReportsForPastes([FromQuery] ReportQuery request)
|
||||
{
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user is null)
|
||||
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to view pastes." });
|
||||
|
||||
@@ -159,12 +153,10 @@ namespace SharpbinV3.Server.Controllers
|
||||
[Route("users")]
|
||||
[HttpGet]
|
||||
[EnableRateLimiting("Sliding")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> GetReportsForUsers([FromQuery] ReportQuery request)
|
||||
{
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user is null)
|
||||
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to view users." });
|
||||
|
||||
@@ -197,7 +189,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
[Route("all")]
|
||||
[HttpGet]
|
||||
[EnableRateLimiting("Sliding")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> GetAllReports(
|
||||
[FromQuery] Guid? reporterUuid,
|
||||
[FromQuery] ReportTargetType? targetType,
|
||||
@@ -207,9 +199,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
[FromQuery] int pageSize = 20
|
||||
)
|
||||
{
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user is null)
|
||||
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to view reports." });
|
||||
|
||||
|
||||
@@ -53,16 +53,13 @@ namespace SharpbinV3.Server.Controllers
|
||||
[Authorize]
|
||||
public async Task<IActionResult> GetMe([FromQuery] int page = 1)
|
||||
{
|
||||
var userUUID = HttpContext.User?.FindFirst("uuid")?.Value;
|
||||
if (userUUID is null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
|
||||
var userUUID = HttpContext.User.FindFirst("uuid")!.Value;
|
||||
var user = await _userService.GetByUUID(Guid.Parse(userUUID), withPastes: true);
|
||||
return user == null ? NotFound(new { success = false, message = "User not found." }) : await BuildUserResponse(user, page);
|
||||
}
|
||||
|
||||
[HttpPatch("uuid/{uuid}")]
|
||||
[Authorize]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[EnableRateLimiting("Strict")]
|
||||
public async Task<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser)
|
||||
{
|
||||
@@ -70,9 +67,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(ModelState);
|
||||
|
||||
var jwtUser = HttpContext.GetJwtUser();
|
||||
if (jwtUser == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var jwtUser = HttpContext.GetJwtUser()!;
|
||||
|
||||
var user = await _userService.GetByUUID(uuid);
|
||||
if (user == null)
|
||||
@@ -113,13 +108,11 @@ namespace SharpbinV3.Server.Controllers
|
||||
}
|
||||
|
||||
[HttpDelete("uuid/{uuid}")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> DeleteByUUID(Guid uuid, [FromBody] DeleteUserDto dto)
|
||||
{
|
||||
var jwtUser = HttpContext.GetJwtUser();
|
||||
if (jwtUser == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var jwtUser = HttpContext.GetJwtUser()!;
|
||||
|
||||
var user = await _userService.GetByUUID(uuid);
|
||||
if (user == null)
|
||||
@@ -159,12 +152,10 @@ namespace SharpbinV3.Server.Controllers
|
||||
[HttpPost]
|
||||
[Route("{uuid}/report")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> ReportUser(Guid uuid, [FromBody] ReportDto request)
|
||||
{
|
||||
var reporter = HttpContext.GetJwtUser();
|
||||
if (reporter == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var reporter = HttpContext.GetJwtUser()!;
|
||||
|
||||
var reportedUser = await _userService.GetByUUID(uuid);
|
||||
if (reportedUser == null)
|
||||
@@ -210,12 +201,10 @@ namespace SharpbinV3.Server.Controllers
|
||||
[HttpPatch]
|
||||
[Route("{uuid}/report/{reportId}")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> UpdateUserReport(Guid uuid, int reportId, [FromBody] ReportDto request)
|
||||
{
|
||||
var jwtUser = HttpContext.GetJwtUser();
|
||||
if (jwtUser == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var jwtUser = HttpContext.GetJwtUser()!;
|
||||
|
||||
var user = await _userService.GetByUUID(uuid);
|
||||
if (user == null)
|
||||
@@ -239,12 +228,10 @@ namespace SharpbinV3.Server.Controllers
|
||||
[HttpDelete]
|
||||
[Route("{uuid}/report/{reportId}")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> DeleteUserReport(Guid uuid, int reportId)
|
||||
{
|
||||
var jwtUser = HttpContext.GetJwtUser();
|
||||
if (jwtUser == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var jwtUser = HttpContext.GetJwtUser()!;
|
||||
|
||||
var user = await _userService.GetByUUID(uuid);
|
||||
if (user == null)
|
||||
@@ -262,13 +249,11 @@ namespace SharpbinV3.Server.Controllers
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Authorize]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[Route("{uuid}/reports")]
|
||||
public async Task<IActionResult> GetUserReports(Guid uuid, [FromQuery] ReportQuery request)
|
||||
{
|
||||
var jwtUser = HttpContext.GetJwtUser();
|
||||
if (jwtUser == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var jwtUser = HttpContext.GetJwtUser()!;
|
||||
|
||||
var user = await _userService.GetByUUID(uuid);
|
||||
if (user == null)
|
||||
@@ -297,13 +282,11 @@ namespace SharpbinV3.Server.Controllers
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Authorize]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[Route("{uuid}/reports/submitted")]
|
||||
public async Task<IActionResult> GetUserSubmittedReports(Guid uuid, [FromQuery] ReportQuery request)
|
||||
{
|
||||
var jwtUser = HttpContext.GetJwtUser();
|
||||
if (jwtUser == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var jwtUser = HttpContext.GetJwtUser()!;
|
||||
|
||||
var user = await _userService.GetByUUID(uuid);
|
||||
if (user == null)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Text;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.RateLimiting;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
@@ -8,6 +9,7 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.OpenApi;
|
||||
using SharpbinV3.Server.Authentication;
|
||||
using SharpbinV3.Server.Authorization;
|
||||
using SharpbinV3.Server.Data;
|
||||
using SharpbinV3.Server.Extensions;
|
||||
@@ -91,7 +93,34 @@ namespace SharpbinV3.Server
|
||||
.ValidateOnStart();
|
||||
builder.Services.Configure<AuthSettings>(builder.Configuration.GetSection("AuthSettings"));
|
||||
|
||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();
|
||||
builder
|
||||
.Services.AddAuthentication(options =>
|
||||
{
|
||||
options.DefaultAuthenticateScheme = AuthSchemes.Combined;
|
||||
options.DefaultScheme = AuthSchemes.Combined;
|
||||
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
})
|
||||
.AddPolicyScheme(
|
||||
AuthSchemes.Combined,
|
||||
AuthSchemes.Combined,
|
||||
options =>
|
||||
{
|
||||
options.ForwardDefaultSelector = context =>
|
||||
{
|
||||
var apiKeyHeader = context.Request.Headers["X-API-Key"].ToString();
|
||||
if (!string.IsNullOrEmpty(apiKeyHeader))
|
||||
return AuthSchemes.ApiKey;
|
||||
|
||||
var authHeader = context.Request.Headers.Authorization.ToString();
|
||||
if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
|
||||
return JwtBearerDefaults.AuthenticationScheme;
|
||||
|
||||
return JwtBearerDefaults.AuthenticationScheme;
|
||||
};
|
||||
}
|
||||
)
|
||||
.AddJwtBearer()
|
||||
.AddScheme<AuthenticationSchemeOptions, ApiKeyAuthenticationHandler>(AuthSchemes.ApiKey, _ => { });
|
||||
|
||||
builder
|
||||
.Services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme)
|
||||
@@ -125,6 +154,27 @@ namespace SharpbinV3.Server
|
||||
|
||||
builder.Services.AddAuthorizationBuilder().AddPolicy("NotBanned", policy => policy.Requirements.Add(new NotBannedRequirement()));
|
||||
builder.Services.AddAuthorizationBuilder().AddPolicy("AuthAndNotBanned", policy => policy.Requirements.Add(new NotBannedRequirement()));
|
||||
builder
|
||||
.Services.AddAuthorizationBuilder()
|
||||
.AddPolicy(
|
||||
"JwtOnly",
|
||||
policy =>
|
||||
{
|
||||
policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
|
||||
policy.RequireAuthenticatedUser();
|
||||
}
|
||||
);
|
||||
builder
|
||||
.Services.AddAuthorizationBuilder()
|
||||
.AddPolicy(
|
||||
"JwtOnlyAndNotBanned",
|
||||
policy =>
|
||||
{
|
||||
policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
|
||||
policy.RequireAuthenticatedUser();
|
||||
policy.Requirements.Add(new NotBannedRequirement());
|
||||
}
|
||||
);
|
||||
builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(false));
|
||||
builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(true));
|
||||
|
||||
@@ -236,8 +286,6 @@ namespace SharpbinV3.Server
|
||||
app.UseHttpsRedirection();
|
||||
app.UseCors();
|
||||
|
||||
app.UseMiddleware<Middleware.ApiKeyAuthenticationMiddleware>();
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user