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/Startup.cs | 47 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 42 insertions(+), 5 deletions(-) (limited to 'API/Startup.cs') 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