Last active
September 5, 2019 07:52
-
-
Save Gimly/74bd82e0f8990646a8b3751c43efbf81 to your computer and use it in GitHub Desktop.
Add authentication with JwtBearer to a .Net Core 2.0 Web API
This file contains hidden or 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 System.Threading.Tasks; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.AspNetCore.SpaServices.Webpack; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.AspNetCore.Authentication.JwtBearer; | |
using Microsoft.AspNetCore.Http; | |
namespace demo-app | |
{ | |
public class Startup | |
{ | |
public Startup(IHostingEnvironment env, IConfiguration configuration) | |
{ | |
Configuration = configuration; | |
Environment = env; | |
} | |
public IConfiguration Configuration { get; } | |
public IHostingEnvironment Environment { get; } | |
// This method gets called by the runtime. Use this method to add services to the container. | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddMvc(); | |
services.AddAuthentication(options => | |
{ | |
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; | |
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; | |
}).AddJwtBearer(o => | |
{ | |
o.Authority = Configuration["Jwt:Authority"]; | |
o.Audience = Configuration["Jwt:Audience"]; | |
o.Events = new JwtBearerEvents() | |
{ | |
OnAuthenticationFailed = c => | |
{ | |
c.NoResult(); | |
c.Response.StatusCode = 500; | |
c.Response.ContentType = "text/plain"; | |
if (Environment.IsDevelopment()) | |
{ | |
return c.Response.WriteAsync(c.Exception.ToString()); | |
} | |
return c.Response.WriteAsync("An error occured processing your authentication."); | |
} | |
}; | |
}); | |
} | |
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. | |
public void Configure(IApplicationBuilder app, IHostingEnvironment env) | |
{ | |
if (env.IsDevelopment()) | |
{ | |
app.UseDeveloperExceptionPage(); | |
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions | |
{ | |
HotModuleReplacement = true | |
}); | |
} | |
else | |
{ | |
app.UseExceptionHandler("/Home/Error"); | |
} | |
app.UseStaticFiles(); | |
app.UseAuthentication(); | |
app.UseMvc(routes => | |
{ | |
routes.MapRoute( | |
name: "default", | |
template: "{controller=Home}/{action=Index}/{id?}"); | |
routes.MapSpaFallbackRoute( | |
name: "spa-fallback", | |
defaults: new { controller = "Home", action = "Index" }); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment