Created
August 7, 2016 19:12
-
-
Save eshapovalova/8ea7fd7265be9fa6e8c40fa808fc0eaa to your computer and use it in GitHub Desktop.
Custom Authentication Filter for Web API
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
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Net.Http.Headers; | |
| using System.Text; | |
| using System.Threading; | |
| using System.Threading.Tasks; | |
| using System.Web.Http.Filters; | |
| using System.Web.Http.Results; | |
| using System.Security.Principal; | |
| namespace WebApiApp.Filters | |
| { | |
| class CustomAuthenticationAttribute : Attribute, IAuthenticationFilter | |
| { | |
| public Task AuthenticateAsync(HttpAuthenticationContext context, | |
| CancellationToken cancellationToken) | |
| { | |
| context.Principal=null; | |
| AuthenticationHeaderValue authentication = context.Request.Headers.Authorization; | |
| if (authentication != null && authentication.Scheme == "Basic") | |
| { | |
| string[] authData = Encoding.ASCII.GetString(Convert.FromBase64String(authentication.Parameter)).Split(':'); | |
| string[] roles = new string[] { "user" }; | |
| string login = authData[0]; | |
| context.Principal = new GenericPrincipal(new GenericIdentity(login), roles); | |
| } | |
| if (context.Principal == null) | |
| { | |
| context.ErrorResult | |
| = new UnauthorizedResult(new AuthenticationHeaderValue[] { | |
| new AuthenticationHeaderValue("Basic") }, context.Request); | |
| } | |
| return Task.FromResult<object>(null); | |
| } | |
| public Task ChallengeAsync(HttpAuthenticationChallengeContext context, | |
| CancellationToken cancellationToken) | |
| { | |
| return Task.FromResult<object>(null); | |
| } | |
| public bool AllowMultiple | |
| { | |
| get { return false; } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment