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

@@ -0,0 +1,9 @@
using System.Collections.Generic;
namespace skydiveLogs_api.Model
{
public class CorsSettings
{
public string FrontUrl { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
using System.Collections.Generic;
namespace skydiveLogs_api.Model
{
public class JwtSettings
{
public string Issuer { get; set; }
public string Passphrase { get; set; }
}
}

View File

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

View File

@@ -56,9 +56,9 @@
"latitude": "44.00109", "latitude": "44.00109",
"longitude": "4.75815", "longitude": "4.75815",
"name": "Skydive Pujaut", "name": "Skydive Pujaut",
"address": null, "address": "Aérodrome Avignon-Pujaut</br>30131 Pujaut",
"website": "www.skydive-pujaut.com", "website": "www.skydive-pujaut.com",
"email": null, "email": "info@skydivepujaut.com",
"type": [ "type": [
"dz" "dz"
], ],

View File

@@ -4,6 +4,8 @@
{ {
public int Id { get; set; } public int Id { get; set; }
public string Email { get; set; }
public string FirstName { get; set; } public string FirstName { get; set; }
public string LastName { get; set; } public string LastName { get; set; }

View File

@@ -1,7 +1,5 @@
using System.Linq; using System.Text;
using System.Text;
using System.IO; using System.IO;
using System;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
@@ -15,6 +13,8 @@ using AutoMapper;
using skydiveLogs_api.Ioc; using skydiveLogs_api.Ioc;
using skydiveLogs_api.Business.Interface; using skydiveLogs_api.Business.Interface;
using skydiveLogs_api.Model;
namespace skydiveLogs_api namespace skydiveLogs_api
{ {
@@ -32,9 +32,12 @@ namespace skydiveLogs_api
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0); .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
// JWT // JWT
var jwtConf = Configuration.GetSection("JWT") var jwtSection = Configuration.GetSection("JWT");
.GetChildren() services.Configure<JwtSettings>(jwtSection);
.ToDictionary(d => d.Key, d => d.Value);
var jwtSettings = new JwtSettings();
jwtSection.Bind(jwtSettings);
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => .AddJwtBearer(options =>
{ {
@@ -45,22 +48,22 @@ namespace skydiveLogs_api
ValidateAudience = true, ValidateAudience = true,
ValidateLifetime = true, ValidateLifetime = true,
ValidateIssuerSigningKey = true, ValidateIssuerSigningKey = true,
ValidIssuer = jwtConf["Issuer"], ValidIssuer = jwtSettings.Issuer,
ValidAudience = jwtConf["Issuer"], ValidAudience = jwtSettings.Issuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConf["Key"])) IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Passphrase))
}; };
}); });
// CORS // CORS
var corsConf = Configuration.GetSection("Cors") var corsSettings = new CorsSettings();
.GetChildren() Configuration.GetSection("Cors").Bind(corsSettings);
.ToDictionary(d => d.Key, d => d.Value);
services.AddCors(options => services.AddCors(options =>
{ {
options.AddDefaultPolicy( options.AddDefaultPolicy(
builder => builder =>
{ {
builder.WithOrigins(corsConf["FrontUrl"]) builder.WithOrigins(corsSettings.FrontUrl)
.AllowAnyHeader() .AllowAnyHeader()
.AllowAnyMethod(); .AllowAnyMethod();
}); });
@@ -106,7 +109,6 @@ namespace skydiveLogs_api
var initDbService = serviceProvider.GetRequiredService<IInitDbService>(); var initDbService = serviceProvider.GetRequiredService<IInitDbService>();
initDbService.GenerateDb(); initDbService.GenerateDb();
} }
} }
public IConfiguration Configuration { get; } public IConfiguration Configuration { get; }

View File

@@ -11,7 +11,7 @@
}, },
"JWT": { "JWT": {
"Issuer": "NoIdea", "Issuer": "NoIdea",
"Key": "the very long and strong passphrase to encrypt the token" "Passphrase": "the very long and strong passphrase to encrypt the token"
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
"ConnectionStrings": { "ConnectionStrings": {