77 lines
2.2 KiB
C#
77 lines
2.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Linq;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Options;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using ReallifeGamemode.Database;
|
|
using ReallifeGamemode.Database.Entities;
|
|
using ReallifeGamemode.Database.Models;
|
|
|
|
namespace ReallifeGamemode.DataService.Logic
|
|
{
|
|
public class JwtTokenGenerator : LogicBase
|
|
{
|
|
private ServerConfig config;
|
|
|
|
public JwtTokenGenerator(IOptions<ServerConfig> config, DatabaseContext dbContext) : base(dbContext)
|
|
{
|
|
this.config = config.Value;
|
|
}
|
|
|
|
public string GenerateUserToken(User user)
|
|
{
|
|
if(user == null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
|
|
var key = Encoding.ASCII.GetBytes(config.TokenSecret);
|
|
|
|
var tokenDescriptor = new SecurityTokenDescriptor
|
|
{
|
|
Subject = new ClaimsIdentity(new[]
|
|
{
|
|
new Claim(ClaimTypes.Name, user.Id.ToString()),
|
|
new Claim(ClaimTypes.Role, user.AdminLevel.ToString())
|
|
}),
|
|
Expires = DateTime.Now.AddDays(1),
|
|
IssuedAt = DateTime.Now,
|
|
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
|
|
Issuer = "LOGDATASERVICE"
|
|
};
|
|
|
|
var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));
|
|
|
|
return token;
|
|
}
|
|
|
|
public string GetDebugToken(byte[] key)
|
|
{
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
|
|
var tokenDescriptor = new SecurityTokenDescriptor
|
|
{
|
|
Subject = new ClaimsIdentity(new[]
|
|
{
|
|
new Claim(ClaimTypes.Name, 1.ToString()),
|
|
new Claim(ClaimTypes.Role, (AdminLevel.PROJEKTLEITUNG).ToString())
|
|
}),
|
|
Expires = DateTime.Now.AddDays(1),
|
|
IssuedAt = DateTime.Now,
|
|
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
|
|
Issuer = "LOGDATASERVICE"
|
|
};
|
|
|
|
var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));
|
|
|
|
return token;
|
|
}
|
|
}
|
|
}
|