Authentication Controller

PHOTO EMBED

Fri Jun 23 2023 08:20:57 GMT+0000 (Coordinated Universal Time)

Saved by @cameron_v_r #c# #asp.net #identities

using Assignment3_Backend.Models;
using Assignment3_Backend.ViewModels;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Assignment3_Backend.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthenticationController : ControllerBase
{
private readonly UserManager<AppUser> _userManager;
    private readonly IUserClaimsPrincipalFactory<AppUser> _claimsPrincipalFactory;
        private readonly IRepository _repository;
        private readonly IConfiguration _configuration;

        public AuthenticationController(UserManager<AppUser> userManager, IUserClaimsPrincipalFactory<AppUser> claimsPrincipalFactory, IRepository repository, IConfiguration configuration)
                {
                _repository = repository;
                _userManager = userManager;
                _claimsPrincipalFactory = claimsPrincipalFactory;
                _configuration = configuration;
                }

                [HttpPost]
                [Route("Register")]
                public async Task<IActionResult> Register(UserViewModel uvm)
                    {
                    var user = await _userManager.FindByIdAsync(uvm.emailaddress);

                    if (user == null)
                    {
                    user = new AppUser
                    {
                    Id = Guid.NewGuid().ToString(),
                    UserName = uvm.emailaddress,
                    Email = uvm.emailaddress
                    };

                    var result = await _userManager.CreateAsync(user, uvm.password);

                    if (result.Errors.Count() > 0) return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
                    }
                    else
                    {
                    return Forbid("Account already exists.");
                    }

                    return Ok();
                    }

                    [HttpPost]
                    [Route("Login")]
                    public async Task<ActionResult> Login(UserViewModel uvm)
                        {
                        var user = await _userManager.FindByNameAsync(uvm.emailaddress);

                        if (user != null && await _userManager.CheckPasswordAsync(user, uvm.password))
                        {
                        try
                        {
                        var principal = await _claimsPrincipalFactory.CreateAsync(user);
                        return GenerateJWTToken(user);
                        }
                        catch (Exception)
                        {
                        return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
                        }
                        }
                        else
                        {
                        return NotFound("Does not exist");
                        }
                        }

                        [HttpGet]
                        private ActionResult GenerateJWTToken(AppUser user)
                        {
                        // Create JWT Token
                        var claims = new[]
                        {
                        new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                        new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
                        };

                        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Tokens:Key"]));
                        var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                        var token = new JwtSecurityToken(
                        _configuration["Tokens:Issuer"],
                        _configuration["Tokens:Audience"],
                        claims,
                        signingCredentials: credentials,
                        expires: DateTime.UtcNow.AddHours(3)
                        );

                        return Created("", new
                        {
                        token = new JwtSecurityTokenHandler().WriteToken(token),
                        user = user.UserName
                        });
                        }

                        }
                        }
content_copyCOPY