DataService hinzugefügt
This commit is contained in:
76
ReallifeGamemode.DataService/Logic/JwtTokenGenerator.cs
Normal file
76
ReallifeGamemode.DataService/Logic/JwtTokenGenerator.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user