mirror of
https://github.com/JogmansonReal/Radicade.git
synced 2026-10-26 07:29:00 -07:00
Radicade Public Code
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Text;
|
||||
using RadicadeServer.DB;
|
||||
|
||||
namespace RadicadeServer.Extensions
|
||||
{
|
||||
public static class UserExtension
|
||||
{
|
||||
public static long? GetUserId(this ClaimsPrincipal req)
|
||||
{
|
||||
string? userIdStr = req.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (userIdStr == null) return null;
|
||||
return long.Parse(userIdStr);
|
||||
}
|
||||
|
||||
public static string? GetPlatId(this ClaimsPrincipal req)
|
||||
{
|
||||
string? userIdStr = req.FindFirstValue("rn.platid");
|
||||
return userIdStr;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public static long? GetUserId(this string req)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(req)) return null;
|
||||
string token = req.Trim();
|
||||
|
||||
|
||||
if (token.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
|
||||
token = token.Substring(7).Trim();
|
||||
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
var key = Encoding.ASCII.GetBytes(DBConfig.JwtKey);
|
||||
|
||||
var principal = tokenHandler.ValidateToken(token, new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(key),
|
||||
ValidateIssuer = false,
|
||||
ValidateAudience = false,
|
||||
}, out _);
|
||||
|
||||
var tokenClaim = principal.Claims.FirstOrDefault(claim => claim.Type == "userId")?.Value;
|
||||
if (tokenClaim == null) return null;
|
||||
return long.Parse(tokenClaim);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user