Ajith
Ajith

Reputation: 1535

C# Web Api with OAuth and Basic authentication

I have an Asp.net web api, which is configured with OAuth. Now I have new client who cannot use Oauth but wants to use Basic Authentication with the same endpoint url.

Haven't found any ways to do this yet. Any help on this is appreciated. Thanks in Advance

Upvotes: 1

Views: 3286

Answers (1)

Riste Golaboski
Riste Golaboski

Reputation: 46

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        if ((Thread.CurrentPrincipal.Identity.Name?.Length ?? 0) <= 0)
        {
            AuthenticationHeaderValue auth = actionContext.Request.Headers.Authorization;
            if (string.Compare(auth.Scheme, "Basic", StringComparison.OrdinalIgnoreCase) == 0)
            {
                string credentials = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(auth.Parameter));
                int separatorIndex = credentials.IndexOf(':');
                if (separatorIndex >= 0)
                {
                    string userName = credentials.Substring(0, separatorIndex);
                    string password = credentials.Substring(separatorIndex + 1);
                    var userManager = new MembershipUserManager();
                    var user = userManager.FindAsync(userName, password).Result;
                    if (user != null)
                        Thread.CurrentPrincipal = actionContext.ControllerContext.RequestContext.Principal = new GenericPrincipal(new GenericIdentity(userName, "Basic"), System.Web.Security.Roles.Provider.GetRolesForUser(userName));
                }
            }
        }
        return base.IsAuthorized(actionContext);
    }
}

Use this code once you have set up the token auth (Oauth) and this would work for both: This attribute should be used everywhere (ditch the Authorize) [contains roles] and would verify the Basic auth, whereas the base.IsAuthorized(actionContext); would verify the token approach (Oauth).

MembershipUserManager is a custom class I've created to make this work with Membership, I'm guessing you'd use Identity User Manager.

Upvotes: 2

Related Questions