|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.IdentityModel.Tokens.Jwt; |
| 4 | +using System.Linq; |
| 5 | +using System.Security.Claims; |
| 6 | +using System.Text; |
| 7 | +using BackendAPI.Models; |
| 8 | +using Microsoft.AspNetCore.Authorization; |
| 9 | +using Microsoft.AspNetCore.Mvc; |
| 10 | +using Microsoft.Extensions.Configuration; |
| 11 | +using Microsoft.IdentityModel.Tokens; |
| 12 | + |
| 13 | +// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 |
| 14 | + |
| 15 | +namespace BackendAPI.Controllers |
| 16 | +{ |
| 17 | + [AllowAnonymous] |
| 18 | + [Route("api/[controller]")] |
| 19 | + public class AuthenticateController : Controller |
| 20 | + { |
| 21 | + private DataBaseContext data_context; |
| 22 | + public AuthenticateController(IConfiguration configuration, DataBaseContext data_context) |
| 23 | + { |
| 24 | + Configuration = configuration; |
| 25 | + this.data_context = data_context; |
| 26 | + } |
| 27 | + |
| 28 | + public IConfiguration Configuration { get; } |
| 29 | + |
| 30 | + public IActionResult Post() |
| 31 | + { |
| 32 | + |
| 33 | + var authorizationHeader = Request.Headers["Authorization"].First(); |
| 34 | + var key = authorizationHeader.Split(' ')[1]; |
| 35 | + var credentials = Encoding.UTF8.GetString(Convert.FromBase64String(key)).Split(':'); |
| 36 | + var serverSecret = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:ServerSecret"])); |
| 37 | + |
| 38 | + Users user = this.data_context.User.Where(u => u.Email == credentials[0] && u.Password == credentials[1]).FirstOrDefault(); |
| 39 | + |
| 40 | + if (user != null) |
| 41 | + { |
| 42 | + var result = new |
| 43 | + { |
| 44 | + token = GenerateToken(serverSecret, user) |
| 45 | + }; |
| 46 | + return Ok(result);//status code |
| 47 | + } |
| 48 | + return BadRequest("Invalid Email/Password");//status code |
| 49 | + } |
| 50 | + |
| 51 | + private string GenerateToken(SecurityKey key, Users user) |
| 52 | + { |
| 53 | + var now = DateTime.UtcNow; |
| 54 | + var issuer = Configuration["JWT:Issuer"]; |
| 55 | + var audience = Configuration["JWT:Audience"]; |
| 56 | + var identity = new ClaimsIdentity(new Claim[] |
| 57 | + { |
| 58 | + new Claim(ClaimTypes.Email, user.Email), |
| 59 | + new Claim(ClaimTypes.Role, user.Role) |
| 60 | + }); |
| 61 | + var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); |
| 62 | + var handler = new JwtSecurityTokenHandler(); |
| 63 | + var token = handler.CreateJwtSecurityToken(issuer, audience, identity, |
| 64 | + now, now.Add(TimeSpan.FromHours(100)), now, signingCredentials); |
| 65 | + var encodedJwt = handler.WriteToken(token); |
| 66 | + return encodedJwt; |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments