From 09aeb13a95ab573b05813ba563c322e854540c3e Mon Sep 17 00:00:00 2001 From: Syndamia Date: Fri, 11 Dec 2020 20:45:15 +0200 Subject: Implemented very basic and rough autorization for user --- API/Controllers/UserController.cs | 11 +++++++++ API/Service/UserService.cs | 40 ++++++++++++++++++++++++++++++++- API/Startup.cs | 47 ++++++++++++++++++++++++++++++++++----- 3 files changed, 92 insertions(+), 6 deletions(-) (limited to 'API') diff --git a/API/Controllers/UserController.cs b/API/Controllers/UserController.cs index fdb1c44..8c7a3c3 100644 --- a/API/Controllers/UserController.cs +++ b/API/Controllers/UserController.cs @@ -4,6 +4,8 @@ using API.Service; using AutoMapper; using Microsoft.AspNetCore.Mvc; using Data.Models.DTOs; +using Microsoft.AspNetCore.Authorization; + namespace API.Controllers { @@ -18,6 +20,14 @@ namespace API.Controllers this._service = new UserService(context, mapper); } + [HttpPost] + [Route("login")] + public async Task Login([FromBody] UserDTO userDTO) + { + return await this._service.LoginUser(userDTO); + } + + //Create [HttpPost] public async Task Create([FromBody] UserDTO userDTO) @@ -26,6 +36,7 @@ namespace API.Controllers } //Read + [Authorize] [HttpGet] public async Task GetById(int id) { diff --git a/API/Service/UserService.cs b/API/Service/UserService.cs index 3c3b390..5d59f61 100644 --- a/API/Service/UserService.cs +++ b/API/Service/UserService.cs @@ -5,6 +5,12 @@ using Data.Models.Classes; using Data.Models.DTOs; using Microsoft.AspNetCore.Mvc; +using System.IdentityModel.Tokens.Jwt; +using Microsoft.IdentityModel.Tokens; +using System.Security.Claims; +using System; +using System.Text; + namespace API.Service { public class UserService @@ -12,12 +18,44 @@ namespace API.Service private readonly UserDbRepository _userDbRepository; private readonly IMapper _userMapper; + private static Random rnd = new Random(); // FOR TESTING PURPOSES ONLY + public UserService(DevHiveContext context, IMapper mapper) { this._userDbRepository = new UserDbRepository(context); this._userMapper = mapper; } - + + public async Task LoginUser(UserDTO userDTO) + { + if (userDTO == null) + return new NotFoundObjectResult("User does not exist!"); + + User user = this._userMapper.Map(userDTO); + + + + + // Key generation + var key = Encoding.ASCII.GetBytes(")H@McQfTB?E(H+Mb8x/A?D(Gr4u7x!A%WnZr4t7weThWmZq4KbPeShVm*G-KaPdSz%C*F-Ja6w9z$C&F"); //Startup.Configuration.GetSection("AppSettings").GetValue("Secret", "bruh")); + + var tokenHandler = new JwtSecurityTokenHandler(); + var tokenDescriptor = new SecurityTokenDescriptor + { + Subject = new ClaimsIdentity(new Claim[] + { + new Claim(ClaimTypes.Name, user.Id.ToString()) + }), + Expires = DateTime.UtcNow.AddDays(7), + SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) + }; + var token = tokenHandler.CreateToken(tokenDescriptor); + var tokenString = tokenHandler.WriteToken(token); + + return new OkObjectResult(tokenString); + } + + public async Task CreateUser(UserDTO userDTO) { if (this._userDbRepository.DoesUsernameExist(userDTO.UserName)) diff --git a/API/Startup.cs b/API/Startup.cs index f373f7a..f5aeaad 100644 --- a/API/Startup.cs +++ b/API/Startup.cs @@ -11,6 +11,11 @@ using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using Data.Models.Classes; +using Microsoft.IdentityModel.Tokens; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using System.Text; +using System.Threading.Tasks; + namespace API { public class Startup @@ -28,13 +33,10 @@ namespace API services.AddControllers(); services.AddDbContext(options => - options.UseNpgsql(Configuration.GetConnectionString("DEV"))) - .AddAuthentication() - .AddJwtBearer(); + options.UseNpgsql(Configuration.GetConnectionString("DEV"))); services.AddIdentity() .AddEntityFrameworkStores(); - services.AddAuthentication(); services.Configure(options => { @@ -43,7 +45,42 @@ namespace API options.Password.RequiredLength = 5; }); - services.AddSwaggerGen(c => + // configure jwt authentication + var key = Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings").GetValue("Secret", ")H@McQfTB?E(H+Mb8x/A?D(Gr4u7x!A%WnZr4t7weThWmZq4KbPeShVm*G-KaPdSz%C*F-Ja6w9z$C&F")); + services.AddAuthentication(x => + { + x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer(x => + { + x.Events = new JwtBearerEvents + { + OnTokenValidated = context => + { + // var userService = context.HttpContext.RequestServices.GetRequiredService(); + // var userId = int.Parse(context.Principal.Identity.Name); + // var user = userService.GetById(userId); + // if (user == null) + // { + // // return unauthorized if user no longer exists + // context.Fail("Unauthorized"); + // } + return Task.CompletedTask; + } + }; + x.RequireHttpsMetadata = false; + x.SaveToken = true; + x.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(key), + ValidateIssuer = false, + ValidateAudience = false + }; + }); + + services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" }); }); -- cgit v1.2.3