From 7bb702e46cf836ec17bc1529b2758097276a5a70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Andr=C3=A9?= Date: Thu, 19 Mar 2020 21:33:09 +0100 Subject: [PATCH] Beging to add the authorization with a JWT token --- .../Interface/IJumpService.cs | 7 ++- Back/skydiveLogs-api.Business/JumpService.cs | 8 ++- .../Interface/IJumpRepository.cs | 4 +- Back/skydiveLogs-api.Data/JumpRepository.cs | 8 ++- Back/skydiveLogs-api.Model/Jump.cs | 2 + .../Controllers/JumpController.cs | 10 +++- .../Controllers/UserController.cs | 59 ++++++++++++++++++- Back/skydiveLogs-api/DataContract/UserResp.cs | 2 + Back/skydiveLogs-api/Startup.cs | 49 +++++++++++++-- 9 files changed, 132 insertions(+), 17 deletions(-) diff --git a/Back/skydiveLogs-api.Business/Interface/IJumpService.cs b/Back/skydiveLogs-api.Business/Interface/IJumpService.cs index caf8d39..240f919 100644 --- a/Back/skydiveLogs-api.Business/Interface/IJumpService.cs +++ b/Back/skydiveLogs-api.Business/Interface/IJumpService.cs @@ -7,15 +7,16 @@ namespace skydiveLogs_api.Business.Interface { public interface IJumpService { - IEnumerable GetAllJumps(); + IEnumerable GetAllJumps(User connectedUser); Jump GetJumpById(int id); void AddNewJump(int aircraftId, int dzId, int jumpTypeId, - int gearId, - Jump jump); + int gearId, + Jump jump, + User connectedUser); void UpdateJump(int id, Jump jump); diff --git a/Back/skydiveLogs-api.Business/JumpService.cs b/Back/skydiveLogs-api.Business/JumpService.cs index 23017f7..91322f2 100644 --- a/Back/skydiveLogs-api.Business/JumpService.cs +++ b/Back/skydiveLogs-api.Business/JumpService.cs @@ -27,7 +27,8 @@ namespace skydiveLogs_api.Business int dzId, int jumpTypeId, int gearId, - Jump jump) + Jump jump, + User connectedUser) { var selectedGear = _gearService.GetGearById(gearId); var selectedJumpType = _jumpTypeService.GetJumpTypeById(jumpTypeId); @@ -38,6 +39,7 @@ namespace skydiveLogs_api.Business jump.JumpType = selectedJumpType; jump.DropZone = selectedDropZone; jump.Gear = selectedGear; + jump.UserId = connectedUser.Id; _jumpRepository.Add(jump); } @@ -47,9 +49,9 @@ namespace skydiveLogs_api.Business throw new NotImplementedException(); } - public IEnumerable GetAllJumps() + public IEnumerable GetAllJumps(User connectedUser) { - return _jumpRepository.GetAll(); + return _jumpRepository.GetAll(connectedUser.Id); } public Jump GetJumpById(int id) diff --git a/Back/skydiveLogs-api.Data/Interface/IJumpRepository.cs b/Back/skydiveLogs-api.Data/Interface/IJumpRepository.cs index bdc0d1e..8ed49ab 100644 --- a/Back/skydiveLogs-api.Data/Interface/IJumpRepository.cs +++ b/Back/skydiveLogs-api.Data/Interface/IJumpRepository.cs @@ -1,9 +1,11 @@ using skydiveLogs_api.Model; - +using System.Collections.Generic; namespace skydiveLogs_api.Data.Interface { public interface IJumpRepository : IRepository { + IEnumerable GetAll(int userId); + } } diff --git a/Back/skydiveLogs-api.Data/JumpRepository.cs b/Back/skydiveLogs-api.Data/JumpRepository.cs index a743ad1..c0c4447 100644 --- a/Back/skydiveLogs-api.Data/JumpRepository.cs +++ b/Back/skydiveLogs-api.Data/JumpRepository.cs @@ -17,13 +17,14 @@ namespace skydiveLogs_api.Data _col = _dataProvider.CollOfJump; } - public IEnumerable GetAll() + public IEnumerable GetAll(int userId) { return _col.Include(x => x.Aircraft) .Include(x => x.DropZone) .Include(x => x.Gear) .Include(x => x.JumpType) .FindAll() + .Where(j => j.UserId == userId) .ToList(); } @@ -53,6 +54,11 @@ namespace skydiveLogs_api.Data throw new System.NotImplementedException(); } + public IEnumerable GetAll() + { + throw new System.NotImplementedException(); + } + private readonly IDataProvider _dataProvider; private readonly ILiteCollection _col; diff --git a/Back/skydiveLogs-api.Model/Jump.cs b/Back/skydiveLogs-api.Model/Jump.cs index 963fd28..7641314 100644 --- a/Back/skydiveLogs-api.Model/Jump.cs +++ b/Back/skydiveLogs-api.Model/Jump.cs @@ -14,6 +14,8 @@ namespace skydiveLogs_api.Model public Gear Gear { get; set; } + public int UserId { get; set; } + public int ExitAltitude { get; set; } public int DeployAltitude { get; set; } diff --git a/Back/skydiveLogs-api/Controllers/JumpController.cs b/Back/skydiveLogs-api/Controllers/JumpController.cs index 88ac5f7..0f6af87 100644 --- a/Back/skydiveLogs-api/Controllers/JumpController.cs +++ b/Back/skydiveLogs-api/Controllers/JumpController.cs @@ -1,6 +1,8 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Cors; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authentication.JwtBearer; using AutoMapper; @@ -13,6 +15,7 @@ namespace skydiveLogs_api.Controllers { [Route("api/[controller]")] [ApiController] + [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class JumpController : ControllerBase { public JumpController(IJumpService jumpService, @@ -27,7 +30,9 @@ namespace skydiveLogs_api.Controllers [EnableCors] public IEnumerable Get() { - var result = _jumpService.GetAllJumps(); + var connectedUser = new User() { Id = 1 }; // TEST + var result = _jumpService.GetAllJumps(connectedUser); + return _mapper.Map>(result); } @@ -49,7 +54,8 @@ namespace skydiveLogs_api.Controllers value.DropZoneId, value.JumpTypeId, value.GearId, - _mapper.Map(value)); + _mapper.Map(value), + null /* Provenant du token */); } // PUT: api/Jump/5 diff --git a/Back/skydiveLogs-api/Controllers/UserController.cs b/Back/skydiveLogs-api/Controllers/UserController.cs index 20dfb22..28246cb 100644 --- a/Back/skydiveLogs-api/Controllers/UserController.cs +++ b/Back/skydiveLogs-api/Controllers/UserController.cs @@ -1,5 +1,8 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Cors; +using Microsoft.AspNetCore.Authorization; +using Microsoft.IdentityModel.Tokens; +using System.IdentityModel.Tokens.Jwt; using AutoMapper; @@ -7,6 +10,10 @@ using skydiveLogs_api.Business.Interface; using skydiveLogs_api.DataContract; using skydiveLogs_api.Model; +using System; +using System.Text; +using System.Security.Claims; + namespace skydiveLogs_api.Controllers { @@ -22,15 +29,32 @@ namespace skydiveLogs_api.Controllers } // POST: api/User + [AllowAnonymous] [HttpPost("Authenticate")] [EnableCors] - public UserResp Authenticate([FromBody] UserReq value) + public IActionResult Authenticate([FromBody] UserReq value) { - var result = _userService.GetByLogin(value.Login, value.Password); - return _mapper.Map(result); + IActionResult result; + var foundUser = _userService.GetByLogin(value.Login, value.Password); + + if (foundUser == null) + { + result = BadRequest(new { message = "Username or password is incorrect" }); + } + else + { + foundUser.Password = null; + var resp = _mapper.Map(foundUser); + resp.Token = CreateToken(value); + + result = Ok(resp); + } + + return result; } // POST: api/User + [AllowAnonymous] [HttpPost] [EnableCors] public void Post([FromBody] UserReq value) @@ -38,6 +62,35 @@ namespace skydiveLogs_api.Controllers _userService.AddNewUser(_mapper.Map(value)); } + private string CreateToken(UserReq model) + { + var tokenHandler = new JwtSecurityTokenHandler(); + var key = Encoding.ASCII.GetBytes("tata"); + var tokenDescriptor = new SecurityTokenDescriptor + { + Subject = new ClaimsIdentity(new Claim[] + { + new Claim(ClaimTypes.Name, model.Login) + }), + Expires = DateTime.UtcNow.AddMinutes(30), + SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) + }; + var token = tokenHandler.CreateToken(tokenDescriptor); + return tokenHandler.WriteToken(token); + + + + //var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("tata" /* this._configuration["jwt:key"] */)); + //var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); + + //var token = new JwtSecurityToken("toto" /* this._configuration["jwt:issuer"] */, + // "toto" /* this._configuration["jwt:issuer"] */, + // expires: System.DateTime.Now.AddMinutes(30), + // signingCredentials: credentials); + + //return new JwtSecurityTokenHandler().WriteToken(token); + } + private readonly IUserService _userService; private readonly IMapper _mapper; } diff --git a/Back/skydiveLogs-api/DataContract/UserResp.cs b/Back/skydiveLogs-api/DataContract/UserResp.cs index 87f6b35..622331a 100644 --- a/Back/skydiveLogs-api/DataContract/UserResp.cs +++ b/Back/skydiveLogs-api/DataContract/UserResp.cs @@ -9,5 +9,7 @@ public string LastName { get; set; } public string Login { get; set; } + + public string Token { get; set; } } } diff --git a/Back/skydiveLogs-api/Startup.cs b/Back/skydiveLogs-api/Startup.cs index 2252988..98302ac 100644 --- a/Back/skydiveLogs-api/Startup.cs +++ b/Back/skydiveLogs-api/Startup.cs @@ -1,12 +1,16 @@ -using Microsoft.AspNetCore.Builder; +using System.Linq; +using System.Text; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using System.Linq; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.IdentityModel.Tokens; + +using AutoMapper; using skydiveLogs_api.Ioc; -using AutoMapper; namespace skydiveLogs_api @@ -23,6 +27,41 @@ namespace skydiveLogs_api { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); + // JWT + //services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + // .AddJwtBearer(options => + // { + // options.SaveToken = true; + // options.TokenValidationParameters = new TokenValidationParameters() + // { + // ValidateIssuer = true, + // ValidateAudience = true, + // ValidateLifetime = true, + // ValidateIssuerSigningKey = true, + // ValidIssuer = "toto", // Configuration["jwt:issuer"], + // ValidAudience = "toto", // Configuration["jwt:issuer"], + // IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("tata" /* this.Configuration["jwt:key"] */)) + // }; + // }); + var key = Encoding.ASCII.GetBytes("tata"); + services.AddAuthentication(x => + { + x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer(x => + { + x.RequireHttpsMetadata = false; + x.SaveToken = true; + x.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(key), + ValidateIssuer = false, + ValidateAudience = false + }; + }); + // CORS var corsConf = Configuration.GetSection("Cors") .GetChildren() @@ -30,7 +69,7 @@ namespace skydiveLogs_api services.AddCors(options => { options.AddDefaultPolicy( - builder => + builder => { builder.WithOrigins(corsConf["FrontUrl"]) .AllowAnyHeader() @@ -61,6 +100,8 @@ namespace skydiveLogs_api app.UseCors(); //app.UseHttpsRedirection(); + app.UseAuthentication(); + app.UseMvc(); }