Created
October 6, 2016 14:43
-
-
Save KristianMariyanov/f555ccb3ea66a7c1db747e108814fc24 to your computer and use it in GitHub Desktop.
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.IO; | |
using System.Linq; | |
using System.Security.Claims; | |
using System.Security.Principal; | |
using System.Text; | |
using System.Threading.Tasks; | |
using LaptopListingSystem.Web.Authentication; | |
using LaptopListingSystem.Web.Data; | |
using LaptopListingSystem.Web.Models; | |
using Microsoft.AspNetCore.Authorization; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.AspNetCore.Identity; | |
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; | |
using Microsoft.AspNetCore.Mvc.Authorization; | |
using Microsoft.EntityFrameworkCore; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.Logging; | |
using Microsoft.Extensions.Options; | |
using Microsoft.IdentityModel.Tokens; | |
namespace LaptopListingSystem.Web | |
{ | |
public class Startup | |
{ | |
// TODO: Store SecretKey in more secure place | |
private const string SecretKey = "needtogetthisfromenvironment"; | |
private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey)); | |
public Startup(IHostingEnvironment env) | |
{ | |
var builder = new ConfigurationBuilder() | |
.SetBasePath(env.ContentRootPath) | |
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) | |
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); | |
if (env.IsEnvironment("Development")) | |
{ | |
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. | |
builder.AddApplicationInsightsSettings(developerMode: true); | |
} | |
builder.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) | |
{ | |
services.AddOptions(); | |
//var jwtAppSettingOptions = Configuration.GetSection(nameof(TokenProviderOptions)); | |
//// Configure JwtIssuerOptions | |
//services.Configure<TokenProviderOptions>(options => | |
//{ | |
// options.Issuer = jwtAppSettingOptions[nameof(TokenProviderOptions.Issuer)]; | |
// options.Audience = jwtAppSettingOptions[nameof(TokenProviderOptions.Audience)]; | |
// options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256); | |
//}); | |
// Add framework services. | |
services.AddApplicationInsightsTelemetry(Configuration); | |
services.AddDbContext<ApplicationDbContext>(options => | |
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); | |
services.AddIdentity<ApplicationUser, IdentityRole>() | |
.AddEntityFrameworkStores<ApplicationDbContext>() | |
.AddDefaultTokenProviders(); | |
services.AddMvc(); | |
} | |
// 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) | |
{ | |
var tokenProviderAppSettingOptions = Configuration.GetSection(nameof(TokenProviderOptions)); | |
loggerFactory.AddConsole(Configuration.GetSection("Logging")); | |
loggerFactory.AddDebug(); | |
var tokenValidationParameters = new TokenValidationParameters | |
{ | |
ValidateIssuer = true, | |
ValidIssuer = tokenProviderAppSettingOptions[nameof(TokenProviderOptions.Issuer)], | |
ValidateAudience = true, | |
ValidAudience = tokenProviderAppSettingOptions[nameof(TokenProviderOptions.Audience)], | |
ValidateIssuerSigningKey = true, | |
IssuerSigningKey = _signingKey, | |
ValidateLifetime = true, | |
ClockSkew = TimeSpan.Zero | |
}; | |
app.UseIdentity(); | |
app.UseSimpleTokenProvider(new TokenProviderOptions | |
{ | |
Path = "/api/jwt", | |
Audience = tokenProviderAppSettingOptions[nameof(TokenProviderOptions.Audience)], | |
Issuer = tokenProviderAppSettingOptions[nameof(TokenProviderOptions.Issuer)], | |
SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256), | |
IdentityResolver = GetIdentity | |
}); | |
app.UseJwtBearerAuthentication(new JwtBearerOptions | |
{ | |
AutomaticAuthenticate = true, | |
AutomaticChallenge = true, | |
TokenValidationParameters = tokenValidationParameters | |
}); | |
app.UseApplicationInsightsRequestTelemetry(); | |
app.UseApplicationInsightsExceptionTelemetry(); | |
app.Use(async (context, next) => | |
{ | |
await next(); | |
if (context.Response.StatusCode == 404 | |
&& !Path.HasExtension(context.Request.Path.Value)) | |
{ | |
context.Request.Path = "/index.html"; | |
await next(); | |
} | |
}); | |
app.UseStaticFiles(); | |
app.UseMvc(); | |
} | |
private async Task<ClaimsIdentity> GetIdentity(HttpContext context) | |
{ | |
var email = context.Request.Form["email"]; | |
var userManager = context.RequestServices.GetRequiredService<UserManager<ApplicationUser>>(); | |
var user = await userManager.FindByEmailAsync(email); | |
if (user != null) | |
{ | |
var password = context.Request.Form["password"]; | |
var isValidPassword = await userManager.CheckPasswordAsync(user, password); | |
if (isValidPassword) | |
{ | |
return new GenericIdentity(email, "Token"); | |
} | |
} | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment