Skip to content

Instantly share code, notes, and snippets.

@ojhp
Created March 15, 2016 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ojhp/dfd40295d8e3e73d3681 to your computer and use it in GitHub Desktop.
Save ojhp/dfd40295d8e3e73d3681 to your computer and use it in GitHub Desktop.
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