Finished most of the auth portion

This commit is contained in:
2019-05-05 20:21:31 -05:00
parent 23e518d225
commit 8e4e504fd8
7 changed files with 90 additions and 30 deletions

View File

@@ -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

View File

@@ -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<BgContext>(options => options.UseLazyLoadingProxies()
.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))); /* TODO: Change to Azure Key Vault */
services.AddTransient<BgContext, BgContext>();
}
@@ -60,6 +83,7 @@ namespace BrightGlimmer.Api
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseMvc();
// Makes sure that the database is in fact created

View File

@@ -9,5 +9,8 @@
},
"ConnectionStrings": {
"DefaultConnection": "Filename=../BrightGlimmer.Data/bright_glimmer.db"
},
"Keys": {
"JwtPrivateKey": "b48c0eb8-75ff-4c0e-91aa-470802ae852b"
}
}

View File

@@ -9,8 +9,10 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="JsonNet.PrivateSettersContractResolvers" Version="1.0.0" />
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
</ItemGroup>
<ItemGroup>

View File

@@ -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<IEnumerable<string>> 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<string> 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);
}
}
}

View File

@@ -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<AuthContext>(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

View File

@@ -9,5 +9,8 @@
},
"ConnectionStrings": {
"DefaultConnection": "Filename=../BrightGlimmer.Data/bright_glimmer_auth.db"
},
"Keys": {
"JwtPrivateKey": "b48c0eb8-75ff-4c0e-91aa-470802ae852b"
}
}