Skip to content

Instantly share code, notes, and snippets.

@eshapovalova
Created August 7, 2016 19:12
Show Gist options
  • Select an option

  • Save eshapovalova/8ea7fd7265be9fa6e8c40fa808fc0eaa to your computer and use it in GitHub Desktop.

Select an option

Save eshapovalova/8ea7fd7265be9fa6e8c40fa808fc0eaa to your computer and use it in GitHub Desktop.
Custom Authentication Filter for Web API
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