1

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

4
  • Possible duplicate of ASP.net Web API RESTful web service + Basic authentication Commented Mar 23, 2018 at 14:48
  • Thanks for the reply. This is not duplicate. Checked the link. Here the question is how to use OAuth/Basic authentication based on request. Commented Mar 23, 2018 at 15:56
  • I don't think the 2 can be integrated. The only way I can think of that might work would be to have a web page the requires basic authentication, which can then get a bearer token and use the bearer token to authenticate with the main app. Commented Mar 23, 2018 at 16:09
  • @MoD Any sample code that can help Commented Mar 23, 2018 at 16:17

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Riste Golaboski. I will try this and update here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.