birbmap/Birdmap/Controllers/AuthController.cs

65 lines
2.3 KiB
C#
Raw Normal View History

using AutoMapper;
using Birdmap.API.DTOs;
using Birdmap.BLL.Interfaces;
using Birdmap.Models;
2020-10-21 17:04:54 +02:00
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace Birdmap.Controllers
{
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly IAuthService _service;
private readonly IConfiguration _configuration;
private readonly IMapper _mapper;
2020-10-21 17:04:54 +02:00
public AuthController(IAuthService service, IConfiguration configuration, IMapper mapper)
2020-10-21 17:04:54 +02:00
{
_service = service;
_configuration = configuration;
_mapper = mapper;
2020-10-21 17:04:54 +02:00
}
[AllowAnonymous]
[HttpPost("authenticate")]
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
public async Task<IActionResult> AuthenticateAsync([FromBody] AuthenticateRequest model)
{
var user = await _service.AuthenticateUserAsync(model.Username, model.Password);
2020-10-23 15:05:20 +02:00
var expiresInSeconds = TimeSpan.FromHours(2).TotalSeconds;
2020-10-21 17:04:54 +02:00
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_configuration["Secret"]);
2020-10-21 17:04:54 +02:00
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.Role, user.Role.ToString()),
2020-10-21 17:04:54 +02:00
}),
2020-10-23 15:05:20 +02:00
Expires = DateTime.UtcNow.AddHours(expiresInSeconds),
2020-10-21 17:04:54 +02:00
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
var response = _mapper.Map<AuthenticateResponse>(user);
response.AccessToken = tokenString;
response.TokenType = "Bearer";
response.ExpiresIn = expiresInSeconds;
return Ok(response);
2020-10-21 17:04:54 +02:00
}
}
}