Created
January 24, 2018 14:11
-
-
Save doeringp/133b80cf916a6bdbeb26336b2eef4635 to your computer and use it in GitHub Desktop.
Challenge authentication using a custom middleware (no mvc).
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 Microsoft.AspNetCore.Authentication; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.Extensions.DependencyInjection; | |
using System.IdentityModel.Tokens.Jwt; | |
namespace AspNetCoreAuthTest | |
{ | |
public class Startup | |
{ | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); | |
// Configure authentication providers. | |
services | |
.AddAuthentication(options => | |
{ | |
options.DefaultScheme = "Cookies"; | |
options.DefaultChallengeScheme = "facebook"; | |
}) | |
.AddCookie("Cookies") | |
.AddFacebook("facebook", options => | |
{ | |
// Set your own app id and secret here. | |
options.AppId = "xxx"; | |
options.AppSecret = "xxx"; | |
}); | |
} | |
public void Configure(IApplicationBuilder app, IHostingEnvironment env) | |
{ | |
app.UseDeveloperExceptionPage(); | |
app.UseAuthentication(); | |
app.Use(async (context, next) => | |
{ | |
if (context.User.Identity.IsAuthenticated) | |
{ | |
await next.Invoke(); | |
} | |
else | |
{ | |
// Challenge authentication if the user is not authenticated. | |
await context.ChallengeAsync(); | |
} | |
}); | |
app.Run(async (context) => | |
{ | |
await context.Response.WriteAsync("Hello World!"); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment