Convert the AppSettings to model class

This commit is contained in:
Sébastien André
2020-12-24 20:19:31 +01:00
parent 2991a132bc
commit cd4ac50cb1
7 changed files with 51 additions and 30 deletions

View File

@@ -4,11 +4,10 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.Extensions.Configuration;
using System.Linq;
using System;
using System.Text;
using System.Security.Claims;
using System.Collections.Generic;
using Microsoft.Extensions.Options;
using AutoMapper;
@@ -25,13 +24,11 @@ namespace skydiveLogs_api.Controllers
{
public UserController(IUserService userService,
IMapper mapper,
IConfiguration configuration)
IOptions<JwtSettings> jwtSettings)
{
_userService = userService;
_mapper = mapper;
_jwtConf = configuration.GetSection("JWT")
.GetChildren()
.ToDictionary(d => d.Key, d => d.Value);
_jwtConf = jwtSettings.Value;
}
// GET: api/User/AlwayLogin
@@ -76,9 +73,8 @@ namespace skydiveLogs_api.Controllers
{
IActionResult result;
var newUser = _mapper.Map<User>(userToAdd);
var userAdded = _userService.AddNewUser(newUser);
if (!userAdded)
if (!_userService.AddNewUser(newUser))
{
result = BadRequest(new { message = "Error during the creation of the user." });
}
@@ -96,17 +92,18 @@ namespace skydiveLogs_api.Controllers
private string CreateToken(UserResp foundUser)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtConf["Key"]));
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtConf.Passphrase));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(issuer: _jwtConf["Issuer"],
audience: _jwtConf["Issuer"],
var token = new JwtSecurityToken(issuer: _jwtConf.Issuer,
audience: _jwtConf.Issuer,
expires: DateTime.Now.AddDays(1),
signingCredentials: credentials,
claims: new Claim[]
{
new Claim(ClaimTypes.Name, foundUser.Login),
new Claim(ClaimTypes.UserData, foundUser.Id.ToString())
new Claim(ClaimTypes.UserData, foundUser.Id.ToString()),
new Claim(ClaimTypes.Email, foundUser.Email)
});
return new JwtSecurityTokenHandler().WriteToken(token);
@@ -114,6 +111,6 @@ namespace skydiveLogs_api.Controllers
private readonly IUserService _userService;
private readonly IMapper _mapper;
private readonly Dictionary<string, string> _jwtConf;
private readonly JwtSettings _jwtConf;
}
}