Last active
August 29, 2015 13:55
-
-
Save daanl/8717433 to your computer and use it in GitHub Desktop.
Nancy Owin Authentication
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
public class OwinAuthentication | |
{ | |
public static void Enable(IPipelines pipelines, OwinAuthenticationConfiguration configuration) | |
{ | |
if (pipelines == null) throw new ArgumentNullException("pipelines"); | |
if (configuration == null) throw new ArgumentNullException("configuration"); | |
pipelines.BeforeRequest.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration)); | |
} | |
private static Func<NancyContext, Response> GetLoadAuthenticationHook(OwinAuthenticationConfiguration configuration) | |
{ | |
if (configuration == null) throw new ArgumentNullException("configuration"); | |
return context => | |
{ | |
var userGuid = GetUserIdFromOwinContext(context, configuration); | |
if (userGuid != Guid.Empty) | |
{ | |
context.CurrentUser = configuration.UserMapper.GetUserFromIdentifier(userGuid, context); | |
} | |
return null; | |
}; | |
} | |
private static Guid GetUserIdFromOwinContext(NancyContext context, OwinAuthenticationConfiguration configuration) | |
{ | |
if (context == null) throw new ArgumentNullException("context"); | |
if (configuration == null) throw new ArgumentNullException("configuration"); | |
var env = TryGetFromDictionary<IDictionary<string, object>>(context.Items, NancyOwinHost.RequestEnvironmentKey); | |
if (env == null) throw new ArgumentNullException("context"); | |
var owinContext = new OwinContext(env); | |
if (owinContext.Authentication.User == null) | |
{ | |
return Guid.Empty; | |
} | |
var claim = owinContext.Authentication.User.Claims.FirstOrDefault(x => x.Type == configuration.ClaimType); | |
if (claim == null) | |
{ | |
return Guid.Empty; | |
} | |
Guid userId; | |
if (Guid.TryParse(claim.Value, out userId)) | |
{ | |
return userId; | |
} | |
return Guid.Empty; | |
} | |
private static T TryGetFromDictionary<T>(IDictionary<string, object> env, string key) | |
{ | |
object value; | |
if (env.TryGetValue(key, out value)) | |
{ | |
return (T)value; | |
} | |
return default(T); | |
} | |
} | |
public class OwinAuthenticationConfiguration | |
{ | |
public IUserMapper UserMapper { get; set; } | |
public string ClaimType { get; set; } | |
} | |
public interface IUserMapper | |
{ | |
IUserIdentity GetUserFromIdentifier(Guid userGuid, NancyContext context); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment