Beging to add the authorization with a JWT token

This commit is contained in:
Sébastien André
2020-03-19 21:33:09 +01:00
parent 170ccbd9c5
commit 7bb702e46c
9 changed files with 132 additions and 17 deletions

View File

@@ -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<UserResp>(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<UserResp>(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<User>(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;
}