Created
March 1, 2016 22:40
-
-
Save nukedbit/11efe0ab31dc8a3536f9 to your computer and use it in GitHub Desktop.
BlogAuthenticationFilterAttribute
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
public class BlogAuthenticationFilterAttribute : Attribute, IAuthenticationFilter | |
{ | |
private readonly Rights? _rights; | |
public BlogAuthenticationFilterAttribute(Rights rights) | |
{ | |
_rights = rights; | |
} | |
public BlogAuthenticationFilterAttribute() | |
{ | |
_rights = null; | |
} | |
public bool AllowMultiple { get; } = false; | |
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) | |
{ | |
var request = context.Request; | |
if (!string.IsNullOrEmpty(request.Headers.Authorization?.Parameter)) | |
{ | |
string token = | |
request.Headers.Authorization.Parameter; | |
var tokenCache = (ITokenCache)context.Request.GetDependencyScope().GetService(typeof(ITokenCache)); | |
var securityService = (ISecurityService)context.Request.GetDependencyScope().GetService(typeof(ISecurityService)); | |
if (tokenCache.IsValidToken(token)) | |
{ | |
var model = tokenCache.Get(token); | |
if (_rights.HasValue && !await securityService.IsAuthorizedTo(_rights.Value, model.Username)) | |
{ | |
context.ErrorResult = new UnauthorizedResult( | |
new AuthenticationHeaderValue[0], | |
context.Request); | |
return; | |
} | |
var claims = new List<Claim> | |
{ | |
new Claim(ClaimTypes.Hash, token) | |
}; | |
var id = new ClaimsIdentity(claims, "Basic"); | |
var principal = new ClaimsPrincipal(new[] { id }); | |
context.Principal = principal; | |
} | |
} | |
else | |
{ | |
context.ErrorResult = new UnauthorizedResult( | |
new AuthenticationHeaderValue[0], | |
context.Request); | |
} | |
} | |
public async Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken) | |
{ | |
var result = await context.Result.ExecuteAsync(cancellationToken); | |
if (result.StatusCode == HttpStatusCode.Unauthorized) | |
{ | |
// TODO: fix missing token | |
result.Headers.WwwAuthenticate.Add( | |
new AuthenticationHeaderValue( | |
"Basic", "")); | |
} | |
context.Result = new ResponseMessageResult(result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment