Last active
April 1, 2017 21:08
-
-
Save hlaueriksson/0144c69bb6c78a8ecb8a8874a7aa1a29 to your computer and use it in GitHub Desktop.
2017-03-31-secure-and-explore-aspnet-core-web-apis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"Logging": { | |
"IncludeScopes": false, | |
"LogLevel": { | |
"Default": "Warning" | |
} | |
}, | |
"TokenOptions": { | |
"Audience": "http://localhost:50480", | |
"Issuer": "ConductOfCode", | |
"SigningKey": "cc4435685b40b2e9ddcb357fd79423b2d8e293b897d86f5336cb61c5fd31c9a3" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IdentityModel.Tokens.Jwt; | |
using ConductOfCode.Extensions; | |
using ConductOfCode.Models; | |
using ConductOfCode.Options; | |
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.Extensions.Options; | |
namespace ConductOfCode.Controllers | |
{ | |
[Route("api/[controller]")] | |
public class AuthenticationController : Controller | |
{ | |
private TokenOptions Options { get; } | |
public AuthenticationController(IOptions<TokenOptions> options) | |
{ | |
Options = options.Value; | |
} | |
[HttpPost("[action]")] | |
public TokenResponse Token([FromBody]TokenRequest request) | |
{ | |
// TODO: Authenticate request | |
var token = new JwtSecurityToken( | |
audience: Options.Audience, | |
issuer: Options.Issuer, | |
expires: Options.GetExpiration(), | |
signingCredentials: Options.GetSigningCredentials()); | |
return new TokenResponse | |
{ | |
token_type = Options.Type, | |
access_token = new JwtSecurityTokenHandler().WriteToken(token), | |
expires_in = (int)Options.ValidFor.TotalSeconds | |
}; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using ConductOfCode.Models; | |
using Microsoft.AspNetCore.Authorization; | |
using Microsoft.AspNetCore.Mvc; | |
using Swashbuckle.AspNetCore.SwaggerGen; | |
namespace ConductOfCode.Controllers | |
{ | |
[Authorize] | |
[Route("api/[controller]")] | |
public class StackController : Controller | |
{ | |
private Stack<Item> Stack { get; } | |
public StackController(Stack<Item> stack) | |
{ | |
Stack = stack; | |
} | |
/// <summary>Gets the number of elements contained in the Stack.</summary> | |
/// <returns>The number of elements contained in the Stack.</returns> | |
[HttpGet("[action]")] | |
[SwaggerResponse(200, typeof(int))] | |
public int Count() | |
{ | |
return Stack.Count; | |
} | |
/// <summary>Removes all objects from the Stack.</summary> | |
[HttpDelete("[action]")] | |
[SwaggerResponse(200, typeof(void))] | |
public void Clear() | |
{ | |
Stack.Clear(); | |
} | |
/// <summary>Determines whether an element is in the Stack.</summary> | |
/// <returns>true if <paramref name="item" /> is found in the Stack; otherwise, false.</returns> | |
/// <param name="item">The object to locate in the Stack.</param> | |
[HttpPost("[action]")] | |
[SwaggerResponse(200, typeof(bool))] | |
public bool Contains([FromBody] Item item) | |
{ | |
return Stack.Any(x => x.Value == item.Value); | |
} | |
/// <summary>Returns the object at the top of the Stack without removing it.</summary> | |
/// <returns>The object at the top of the Stack.</returns> | |
[HttpGet("[action]")] | |
[SwaggerResponse(200, typeof(Item))] | |
[SwaggerResponse(400, typeof(Error))] | |
public IActionResult Peek() | |
{ | |
try | |
{ | |
return Ok(Stack.Peek()); | |
} | |
catch (InvalidOperationException ex) | |
{ | |
return BadRequest(new Error(ex)); | |
} | |
} | |
/// <summary>Removes and returns the object at the top of the Stack.</summary> | |
/// <returns>The object removed from the top of the Stack.</returns> | |
[HttpGet("[action]")] | |
[SwaggerResponse(200, typeof(Item))] | |
[SwaggerResponse(400, typeof(Error))] | |
public IActionResult Pop() | |
{ | |
try | |
{ | |
return Ok(Stack.Pop()); | |
} | |
catch (InvalidOperationException ex) | |
{ | |
return BadRequest(new Error(ex)); | |
} | |
} | |
/// <summary>Inserts an object at the top of the Stack.</summary> | |
/// <param name="item">The object to push onto the Stack.</param> | |
[HttpPost("[action]")] | |
[SwaggerResponse(200, typeof(void))] | |
public void Push([FromBody] Item item) | |
{ | |
Stack.Push(item); | |
} | |
/// <summary>Copies the Stack to a new array.</summary> | |
/// <returns>A new array containing copies of the elements of the Stack.</returns> | |
[HttpGet("[action]")] | |
[SwaggerResponse(200, typeof(Item[]))] | |
public Item[] ToArray() | |
{ | |
return Stack.ToArray(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using ConductOfCode.Extensions; | |
using ConductOfCode.Models; | |
using ConductOfCode.Options; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.Logging; | |
using Swashbuckle.AspNetCore.Swagger; | |
namespace ConductOfCode | |
{ | |
public class Startup | |
{ | |
public Startup(IHostingEnvironment env) | |
{ | |
var builder = new ConfigurationBuilder() | |
.SetBasePath(env.ContentRootPath) | |
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) | |
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) | |
.AddEnvironmentVariables(); | |
Configuration = builder.Build(); | |
} | |
public IConfigurationRoot Configuration { get; } | |
// This method gets called by the runtime. Use this method to add services to the container. | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
// Add framework services. | |
services.AddMvc(); | |
services.AddSingleton(new Stack<Item>()); | |
services.AddOptions(); | |
services.Configure<TokenOptions>(Configuration.GetSection(nameof(TokenOptions))); | |
services.AddSwaggerGen(c => | |
{ | |
c.SwaggerDoc("v1", new Info { Title = "ConductOfCode", Version = "v1" }); | |
}); | |
} | |
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. | |
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) | |
{ | |
loggerFactory.AddConsole(Configuration.GetSection("Logging")); | |
loggerFactory.AddDebug(); | |
app.UseSwagger(); | |
app.UseSwaggerUI(c => | |
{ | |
c.SwaggerEndpoint("/swagger/v1/swagger.json", "ConductOfCode"); | |
c.InjectOnCompleteJavaScript("/swagger-ui/authorization1.js"); | |
//c.InjectOnCompleteJavaScript("https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"); // https://cdnjs.com/libraries/crypto-js | |
//c.InjectOnCompleteJavaScript("/swagger-ui/authorization2.js"); | |
}); | |
app.UseStaticFiles(); | |
var options = Configuration.GetSection(nameof(TokenOptions)).Get<TokenOptions>(); | |
app.UseJwtBearerAuthentication(new JwtBearerOptions | |
{ | |
TokenValidationParameters = | |
{ | |
ValidAudience = options.Audience, | |
ValidIssuer = options.Issuer, | |
IssuerSigningKey = options.GetSymmetricSecurityKey() | |
} | |
}); | |
app.UseMvc(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace ConductOfCode.Models | |
{ | |
public class TokenRequest | |
{ | |
public string Username { get; set; } | |
public string Password { get; set; } | |
} | |
public class TokenResponse | |
{ | |
public string token_type { get; set; } | |
public string access_token { get; set; } | |
public int expires_in { get; set; } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace ConductOfCode.Options | |
{ | |
public class TokenOptions | |
{ | |
public string Type { get; set; } = "Bearer"; | |
public TimeSpan ValidFor { get; set; } = TimeSpan.FromHours(1); | |
public string Audience { get; set; } | |
public string Issuer { get; set; } | |
public string SigningKey { get; set; } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Text; | |
using ConductOfCode.Models; | |
using ConductOfCode.Options; | |
using Microsoft.IdentityModel.Tokens; | |
namespace ConductOfCode.Extensions | |
{ | |
public static class TokenOptionsExtensions | |
{ | |
public static DateTime GetExpiration(this TokenOptions options) => DateTime.UtcNow.Add(options.ValidFor); | |
public static SigningCredentials GetSigningCredentials(this TokenOptions options) => new SigningCredentials(options.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256); | |
public static SymmetricSecurityKey GetSymmetricSecurityKey(this TokenOptions options) => new SymmetricSecurityKey(options.GetSigningKeyBytes()); | |
private static byte[] GetSigningKeyBytes(this TokenOptions options) => Encoding.ASCII.GetBytes(options.SigningKey); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment