0

I have a Web Api controller which (partially) looks like this:

public class VehicleController : ApiController
{
    [Authorize]
    public VehicleModel Get(VehicleRequest request)
    {
        return VehicleLogic.Get(request);
    }
}

A custom membership provider has been configured as follows:

<system.web>
    <membership defaultProvider="CustMembership">
        <providers>
            <clear/>
            <add name="CustMembership"
                type="blah.Auth.CustMembership"
                enablePasswordRetrieval="false"
                enablePasswordReset="false"
                requiresQuestionAndAnswer="false"
                requiresUniqueEmail="false"
                minRequiredPasswordLength="6"
                minRequiredNonalphanumericCharacters="0"
                passwordAttemptWindow="10"
                applicationName="/" />
        </providers>
    </membership>
    ...
</system.web>


public class CustMembership : MembershipProvider
{
    ...
    public override bool ValidateUser(string username, string password)
    {
        using (var context = new Entities())
        {
            var user = context.UserAccounts.SingleOrDefault(x => x.Username == username);
            if (user != null)
            {
                var hash = user.Hash;
                var salt = user.Salt;
                var saltedPassword = $"{salt}{password}{salt}";
                var check = getSha256(saltedPassword);
                if (check == hash)
                {
                    _Name = username;
                    return true;
                }
            }
        }
        return false;
    }
    ...
}

However, when I make a call to the method from Postman, a 401 is returned and the provider code is never called. If I place a break-point at the start of the ValidateUser method, it is never hit.

If I remove the [Authorize] attribute, all works as I would expect.

It's as if a provider is being used, but not the one I am expecting.

The same code works fine in other projects.

What am I missing?

CompanyDroneFromSector7G
  • 4,291
  • 13
  • 54
  • 97

1 Answers1

0

The way I understand the Authorize attribute is that, if you call a method without authentication, you would get a 401 (which matches with the result you are getting)

https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api

Using the [Authorize] Attribute

Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated. If not, it returns HTTP status code 401 (Unauthorized), without invoking the action.

From the way I understand this, you would need to have a way to "authenticate" the user first. Then, for the subsequent calls the Authorize attribute will allow the authorised request to proceed.

Subbu
  • 2,130
  • 1
  • 19
  • 28