From 8e4e504fd826c1c7ff53904ebff6946d714ace2a Mon Sep 17 00:00:00 2001 From: Giovani Date: Sun, 5 May 2019 20:21:31 -0500 Subject: [PATCH] Finished most of the auth portion --- .../Controllers/StudentController.cs | 2 + BrightGlimmer.Api/Startup.cs | 26 +++++++++- BrightGlimmer.Api/appsettings.json | 3 ++ BrightGlimmer.Auth/BrightGlimmer.Auth.csproj | 2 + .../Controllers/UserController.cs | 49 +++++++++---------- BrightGlimmer.Auth/Startup.cs | 35 ++++++++++++- BrightGlimmer.Auth/appsettings.json | 3 ++ 7 files changed, 90 insertions(+), 30 deletions(-) diff --git a/BrightGlimmer.Api/Controllers/StudentController.cs b/BrightGlimmer.Api/Controllers/StudentController.cs index 2ab5703..cc6029e 100644 --- a/BrightGlimmer.Api/Controllers/StudentController.cs +++ b/BrightGlimmer.Api/Controllers/StudentController.cs @@ -3,10 +3,12 @@ using System.Threading.Tasks; using BrightGlimmer.Service.Commands; using BrightGlimmer.Service.Queries; using MediatR; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace BrightGlimmer.Api.Controllers { + [Authorize] [Route("api/[controller]")] [ApiController] public class StudentController : ControllerBase diff --git a/BrightGlimmer.Api/Startup.cs b/BrightGlimmer.Api/Startup.cs index ad651a4..fe63c60 100644 --- a/BrightGlimmer.Api/Startup.cs +++ b/BrightGlimmer.Api/Startup.cs @@ -4,12 +4,15 @@ using BrightGlimmer.Data.Repositories; using BrightGlimmer.Domain; using JsonNet.PrivateSettersContractResolvers; using MediatR; +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.Tokens; +using System.Text; namespace BrightGlimmer.Api { @@ -33,6 +36,26 @@ namespace BrightGlimmer.Api options.SerializerSettings.ContractResolver = new PrivateSetterContractResolver(); }); + /* Setup Jwt Authentication */ + var key = Encoding.UTF8.GetBytes(Configuration.GetSection("Keys")["JwtPrivateKey"]); /* TODO: Change to Azure Key Vault */ + services.AddAuthentication(x => + { + x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer(x => + { + x.RequireHttpsMetadata = false; + x.SaveToken = true; + x.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(key), + ValidateIssuer = false, /* TODO: Add validation for both issuer and audience */ + ValidateAudience = false + }; + }); + /* Setup MediatR */ services.AddMediatR(); services.AddMediatR(typeof(Cqrs.Cqrs).Assembly); // Registers handlers in services project @@ -43,7 +66,7 @@ namespace BrightGlimmer.Api /* Configure EF Core DbContext */ services.AddDbContext(options => options.UseLazyLoadingProxies() - .UseSqlite(Configuration.GetConnectionString("DefaultConnection"))); + .UseSqlite(Configuration.GetConnectionString("DefaultConnection"))); /* TODO: Change to Azure Key Vault */ services.AddTransient(); } @@ -60,6 +83,7 @@ namespace BrightGlimmer.Api } app.UseHttpsRedirection(); + app.UseAuthentication(); app.UseMvc(); // Makes sure that the database is in fact created diff --git a/BrightGlimmer.Api/appsettings.json b/BrightGlimmer.Api/appsettings.json index 36161fc..7eb94d4 100644 --- a/BrightGlimmer.Api/appsettings.json +++ b/BrightGlimmer.Api/appsettings.json @@ -9,5 +9,8 @@ }, "ConnectionStrings": { "DefaultConnection": "Filename=../BrightGlimmer.Data/bright_glimmer.db" + }, + "Keys": { + "JwtPrivateKey": "b48c0eb8-75ff-4c0e-91aa-470802ae852b" } } \ No newline at end of file diff --git a/BrightGlimmer.Auth/BrightGlimmer.Auth.csproj b/BrightGlimmer.Auth/BrightGlimmer.Auth.csproj index 29d06c1..64e8e0b 100644 --- a/BrightGlimmer.Auth/BrightGlimmer.Auth.csproj +++ b/BrightGlimmer.Auth/BrightGlimmer.Auth.csproj @@ -9,8 +9,10 @@ + + diff --git a/BrightGlimmer.Auth/Controllers/UserController.cs b/BrightGlimmer.Auth/Controllers/UserController.cs index 9356e7e..ff4aef9 100644 --- a/BrightGlimmer.Auth/Controllers/UserController.cs +++ b/BrightGlimmer.Auth/Controllers/UserController.cs @@ -1,8 +1,13 @@ using System; using System.Collections.Generic; +using System.IdentityModel.Tokens.Jwt; using System.Linq; +using System.Security.Claims; +using System.Text; using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using Microsoft.IdentityModel.Tokens; namespace BrightGlimmer.Auth.Controllers { @@ -10,36 +15,26 @@ namespace BrightGlimmer.Auth.Controllers [ApiController] public class UserController : ControllerBase { - // GET api/values + [AllowAnonymous] [HttpGet] - public ActionResult> Get() + public ActionResult Login(string username, string password) { - return new string[] { "value1", "value2" }; - } + /* TODO: Move token creation to service */ + var tokenHandler = new JwtSecurityTokenHandler(); + var key = Encoding.UTF8.GetBytes(Startup.Configuration.GetSection("Keys")["JwtPrivateKey"]); + var tokenDescriptor = new SecurityTokenDescriptor + { + Subject = new ClaimsIdentity(new Claim[] + { + new Claim(ClaimTypes.NameIdentifier, username) + }), + Expires = DateTime.UtcNow.AddDays(3), + SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) + }; + var tokenSecurity = tokenHandler.CreateToken(tokenDescriptor); + var token = tokenHandler.WriteToken(tokenSecurity); - // GET api/values/5 - [HttpGet("{id}")] - public ActionResult Get(int id) - { - return "value"; - } - - // POST api/values - [HttpPost] - public void Post([FromBody] string value) - { - } - - // PUT api/values/5 - [HttpPut("{id}")] - public void Put(int id, [FromBody] string value) - { - } - - // DELETE api/values/5 - [HttpDelete("{id}")] - public void Delete(int id) - { + return new JsonResult(token); } } } diff --git a/BrightGlimmer.Auth/Startup.cs b/BrightGlimmer.Auth/Startup.cs index 59ca676..fea6ab3 100644 --- a/BrightGlimmer.Auth/Startup.cs +++ b/BrightGlimmer.Auth/Startup.cs @@ -1,8 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text; using System.Threading.Tasks; using BrightGlimmer.Data; +using JsonNet.PrivateSettersContractResolvers; +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; @@ -12,6 +15,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; namespace BrightGlimmer.Auth { @@ -22,12 +26,38 @@ namespace BrightGlimmer.Auth Configuration = configuration; } - public IConfiguration Configuration { get; } + public static IConfiguration Configuration { get; private set; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); + services.AddMvc() + .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) + .AddJsonOptions(options => + { + // Allow private fields to deserialize + options.SerializerSettings.ContractResolver = new PrivateSetterContractResolver(); + }); + + /* Setup Jwt Authentication */ + var key = Encoding.UTF8.GetBytes(Configuration.GetSection("Keys")["JwtPrivateKey"]); /* TODO: Change to Azure Key Vault */ + services.AddAuthentication(x => + { + x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer(x => + { + x.RequireHttpsMetadata = false; + x.SaveToken = true; + x.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(key), + ValidateIssuer = false, /* TODO: Add validation for both issuer and audience */ + ValidateAudience = false + }; + }); /* Configure EF Core DbContext */ services.AddDbContext(options => options.UseLazyLoadingProxies() @@ -48,6 +78,7 @@ namespace BrightGlimmer.Auth } app.UseHttpsRedirection(); + app.UseAuthentication(); app.UseMvc(); // Makes sure that the database is in fact created diff --git a/BrightGlimmer.Auth/appsettings.json b/BrightGlimmer.Auth/appsettings.json index e7fe71f..a371f45 100644 --- a/BrightGlimmer.Auth/appsettings.json +++ b/BrightGlimmer.Auth/appsettings.json @@ -9,5 +9,8 @@ }, "ConnectionStrings": { "DefaultConnection": "Filename=../BrightGlimmer.Data/bright_glimmer_auth.db" + }, + "Keys": { + "JwtPrivateKey": "b48c0eb8-75ff-4c0e-91aa-470802ae852b" } }