KerelOlivier
2 years ago
4 changed files with 102 additions and 3 deletions
@ -0,0 +1,46 @@ |
|||||||
|
using System.IdentityModel.Tokens.Jwt; |
||||||
|
using System.Security.Claims; |
||||||
|
using System.Text; |
||||||
|
using Microsoft.AspNetCore.Mvc; |
||||||
|
using Microsoft.IdentityModel.Tokens; |
||||||
|
|
||||||
|
namespace backend.Controllers; |
||||||
|
|
||||||
|
[ApiController] |
||||||
|
[Route("[controller]")]
|
||||||
|
public class AuthController : ControllerBase |
||||||
|
{ |
||||||
|
public IConfiguration _configuration; |
||||||
|
public AuthController(IConfiguration configuration) |
||||||
|
{ |
||||||
|
_configuration = configuration; |
||||||
|
} |
||||||
|
|
||||||
|
[HttpPost("login")] |
||||||
|
public async Task<IActionResult> Login(string username, string password) |
||||||
|
{ |
||||||
|
if (username == "" || password == "") |
||||||
|
{ |
||||||
|
return BadRequest("Invalid username or password"); |
||||||
|
} |
||||||
|
|
||||||
|
if (username == "test" && password == "test") |
||||||
|
{ |
||||||
|
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:secret"])); |
||||||
|
var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); |
||||||
|
|
||||||
|
var tokeOptions = new JwtSecurityToken( |
||||||
|
issuer: _configuration["Jwt:Issuer"], |
||||||
|
audience: _configuration["Jwt:Audience"], |
||||||
|
claims: new List<Claim>(), |
||||||
|
expires: DateTime.Now.AddDays(1), |
||||||
|
signingCredentials: signinCredentials |
||||||
|
); |
||||||
|
|
||||||
|
var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions); |
||||||
|
return Ok(new { Token = tokenString }); |
||||||
|
} |
||||||
|
|
||||||
|
return BadRequest("Invalid username or password"); |
||||||
|
} |
||||||
|
} |
Loading…
Reference in new issue