DamageAssessment_Backend/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Services/TokenServiceProvider.cs

85 lines
3.6 KiB
C#

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using DamageAssesment.Api.UsersAccess.Db;
using DamageAssesment.Api.UsersAccess.Interfaces;
using DamageAssesment.Api.UsersAccess.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
namespace DamageAssesment.Api.UsersAccess.Services
{
public class TokenServiceProvider : ITokenServiceProvider
{
private readonly UsersAccessDbContext usersAccessDbContext;
private readonly JwtSettings jwtSettings;
private readonly IConfiguration configuration;
public TokenServiceProvider(IOptions<JwtSettings> options, UsersAccessDbContext usersAccessDbContext, IConfiguration configuration)
{
this.usersAccessDbContext = usersAccessDbContext;
this.configuration = configuration;
this.jwtSettings = options.Value;
}
public async Task<string> GenerateToken(Models.User user)
{
var randomnumber = new byte[32];
using (var ramdomnumbergenerator = RandomNumberGenerator.Create())
{
ramdomnumbergenerator.GetBytes(randomnumber);
string refreshtoken = Convert.ToBase64String(randomnumber);
var token = await usersAccessDbContext.Tokens.FirstOrDefaultAsync(item => item.UserId == user.Id);
if (token != null)
{
token.RefreshToken = refreshtoken;
}
else
{
usersAccessDbContext.Tokens.Add(new Db.Token()
{
UserId = user.Id,
RefreshToken = refreshtoken,
IsActive = true
});
}
await usersAccessDbContext.SaveChangesAsync();
return refreshtoken;
}
}
public async Task<TokenResponse> TokenAuthenticate(Models.User user, Claim[] claims)
{
var token = new JwtSecurityToken(claims: claims, expires: DateTime.Now.AddSeconds(20),
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.securitykey)), SecurityAlgorithms.HmacSha256)
);
var jwttoken = new JwtSecurityTokenHandler().WriteToken(token);
return new TokenResponse() { jwttoken = jwttoken, refreshtoken = await GenerateToken(user) };
}
public async Task<string> ConvertJsonToDadeSchoolsJwt(string json)
{
var jsonObject = JObject.Parse(json);
var claims = new Claim[jsonObject.Count];
int i = 0;
foreach (var property in jsonObject.Properties())
{
claims[i++] = new Claim(property.Name, property.Value.ToString());
}
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetValue<string>("Dadeschools:TokenClientSecret")));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddDays(3),
SigningCredentials = credentials
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}
}