Created
March 15, 2016 16:53
-
-
Save ojhp/dfd40295d8e3e73d3681 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
namespace SampleApi.Middleware | |
{ | |
using System; | |
using System.Net; | |
using System.Threading.Tasks; | |
using Microsoft.AspNet.Builder; | |
using Microsoft.AspNet.Http; | |
using Microsoft.Extensions.Logging; | |
public class AuthenticationExceptionHandlerMiddleware | |
{ | |
public const string SuccessMarkerKey = "auth:success"; | |
private readonly RequestDelegate next; | |
private readonly ILogger<AuthenticationExceptionHandlerMiddleware> logger; | |
public AuthenticationExceptionHandlerMiddleware( | |
RequestDelegate next, | |
ILogger<AuthenticationExceptionHandlerMiddleware> logger) | |
{ | |
if (next == null) | |
{ | |
throw new ArgumentNullException(nameof(next)); | |
} | |
if (logger == null) | |
{ | |
throw new ArgumentNullException(nameof(logger)); | |
} | |
this.next = next; | |
this.logger = logger; | |
} | |
public async Task Invoke(HttpContext context) | |
{ | |
// Set success marker to false | |
context.Items[SuccessMarkerKey] = false; | |
try | |
{ | |
// Run rest of pipeline | |
await this.next.Invoke(context); | |
} | |
catch (Exception e) | |
{ | |
// Rethrow exception if authentication succeeded or the response has already started (can't help now) | |
var authenticationSucceeded = context.Items[SuccessMarkerKey] as bool? ?? false; | |
if (authenticationSucceeded || context.Response.HasStarted) | |
{ | |
throw; | |
} | |
// Authentication failed, return 401 | |
this.logger.LogError("Authentication failed with exception", e); | |
context.Response.Headers.Clear(); | |
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment