简体   繁体   中英

WCF Basic Authentication not using on IIS

I have a Rest WCF Service Using the following Configuration

<service behaviorConfiguration="webBehaviour" name="AOS.BrokerAPI.WCFService.BrokerAPIService">
    <endpoint address="mex" binding="mexHttpBinding" name="mex" contract="IMetadataExchange" />
    <endpoint address="brokerapi" binding="webHttpBinding" bindingConfiguration="webHttpBinding"
      name="web" contract="AOS.BrokerAPI.WCFService.IBrokerAPIService" behaviorConfiguration="EndPointBehaviour"/>
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8733/Design_Time_Addresses/AOS.BrokerAPI.WCFService/BrokerAPIService/" />
        <add baseAddress="https://localhost:8732/Design_Time_Addresses/AOS.BrokerAPI.WCFService/BrokerAPIService/" />
      </baseAddresses>
    </host>
  </service>
</services>


<behavior name="webBehaviour">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"
        httpGetBinding="" />
      <serviceDiscovery />
      <!--<serviceAuthenticationManager serviceAuthenticationManagerType=""/>-->
      <serviceCredentials>
        <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="AOS.BrokerAPI.WCFService.Security.Account,AOS.BrokerAPI.WCFService" />
        <!--<serviceCertificate findValue="CN=Dev Certification Authority" x509FindType="FindBySubjectDistinguishedName" storeLocation="LocalMachine"/>-->
      </serviceCredentials>
    </behavior>

When I run the application from my localhost it uses my custom username and password verification class but when I move it to IIS it fails to login.

I enabled Basic authentication and disabled anonymous authentication. Is there something else I might be missing?

Here is the code for the Authentication class, this works perfectly on my localhost when using Visual Studio

public class Account : UserNamePasswordValidator
{
    public override void Validate(string userName, string password)
    {
        //log the user in or return a webexception
        if (null == userName || null == password)
        {
            throw new ArgumentNullException();
        }

        var user = DB.GetUser(userName);
        //usernme  = test, password = Password1

        if (!AOS.BrokerAPI.Domain.Security.PasswordStorage.VerifyPassword(password, user.Password))
            throw new SecurityTokenException("Unknown Username or Incorrect Password");
    }
}

I have enabled Logging for the Authentication class, but the code never hits it.

After spending hours google, I have found a solution though I cannot use it, the idea is to create an authorization extension to IIS and set it to your webconfig and enable it, that way IIS will use that instead of basic authentication.

Just for anyone who maybe looking for a solution to this problem, my solution was to host the application is a web application (asp.net MVC in my case) and used and HttpModule to handle the authentication and authorization

using

public class CustomAuthenticationModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
    }

    public void context_AuthenticateRequest(object sender, EventArgs e)
    {
        HttpApplication application = (HttpApplication)sender;
        if (!SecuirtyHelper.Authenticate(application.Context))
        {
            application.Context.Response.Status = "01 Unauthorized";
            application.Context.Response.StatusCode = 401;
            application.Context.Response.AddHeader("WWW-Authenticate", "Basic realm=localhost");
           // application.Context.Response.ContentType = "application/json";
            application.CompleteRequest();
        }
    }

    public void Dispose()
    {

    }
}

This will allow for authentication using custom authentication. In the Authenticate method you would have to check if your request is secure, if there is an authorization header and try to validate user's cridentials

public static bool Authenticate(HttpContext context)
    {
        if (!HttpContext.Current.Request.IsSecureConnection)
            return false;

        if (!HttpContext.Current.Request.Headers.AllKeys.Contains("Authorization"))
            return false;

        string authHeader = HttpContext.Current.Request.Headers["Authorization"];

        IPrincipal principal;
        if (TryGetPrincipal(authHeader, out principal))
        {
            HttpContext.Current.User = principal;
            return true;
        }
        return false;
    }

private static bool TryGetPrincipal(string authHeader, out IPrincipal principal)
    {
        var creds = ParseAuthHeader(authHeader);
        if (creds != null && TryGetPrincipal(creds, out principal))
            return true;

        principal = null;
        return false;
    }

That should be all that is required for custom authentication on WCF using basic authentication.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM