Self-hosted WCF REST service and Basic authentication

后端 未结 3 1168
心在旅途
心在旅途 2021-02-08 05:27

I\'ve created a self-hosted WCF REST service (with some extra\'s from WCF REST Starter Kit Preview 2). This is all working fine.

I\'m now trying to add Basic authenticat

相关标签:
3条回答
  • 2021-02-08 06:00

    Unfortunately I have determined (by analysing the WCF reference source code and the help of the Fiddler tool for HTTP session sniffing) that this is a bug in the WCF stack.

    Using Fiddler, I noticed that my WCF service was behaving unlike any other web site which uses Basic authentication.

    To be clear, this is what SHOULD happen:

    1. Browser sends GET request with no knowledge that a password is even needed.
    2. Web server rejects request with a 401 Unauthorized status and includes a WWW-Authenticate header containing information about acceptable authentication methods.
    3. Browser prompts user to enter credentials.
    4. Browser resends GET request and includes appropriate Authentication header with the credentials.
    5. If the credentials were correct, the web server responds with 200 OK and the web page. If the credentials were wrong, the web server responds with 401 Unauthorized and includes the same WWW-Authenticate header that it did in Step #2.

    What was ACTUALLY happening with my WCF service was this:

    1. Browser sends GET request with no knowledge that a password is even needed.
    2. WCF notices there is no Authentication header in the request and blindly rejects request with a 401 Unauthorized status and includes a WWW-Authenticate header. All normal so far.
    3. Browser prompts user for credentials. Still normal.
    4. Browser resends GET request including the appropriate Authentication header.
    5. If the credentials were correct, the web server responds with 200 OK. All is fine. If the credentials were wrong however, WCF responds with 403 Forbidden and does not include any additional headers such as WWW-Authenticate.

    When the browser gets the 403 Forbidden status it does not perceive this to be a failed authentication attempt. This status code is intended to inform the browser that the URL it tried to access is off limits. It doesn't relate to authentication in any way. This has the terrible side affect that when the user types their username/password incorrectly (and the server rejects with 403) then the web browser doesn't reprompt the user to type their credentials again. In fact the web browser believes authentication has succeeded and so stores those credentials for the rest of the session!

    With this in mind, I sought clarification:

    The RFC 2617 (http://www.faqs.org/rfcs/rfc2617.html#ixzz0eboUfnrl) does not mention anywhere the use of the 403 Forbidden status code. In fact, what it actually has to say on the matter is the following:

    If the origin server does not wish to accept the credentials sent with a request, it SHOULD return a 401 (Unauthorized) response. The response MUST include a WWW-Authenticate header field containing at least one (possibly new) challenge applicable to the requested resource.

    WCF does neither of these. It neither correctly sends an 401 Unauthorized status code. Nor does it include a WWW-Authenticate header.

    Now to find the smoking gun within the WCF source code:

    I discovered that in the HttpRequestContext class is a method called ProcessAuthentication, which contains the following (excerpt):

    if (!authenticationSucceeded) 
    {
       SendResponseAndClose(HttpStatusCode.Forbidden);
    }
    

    I defend Microsoft on a lot of things but this is indefensible.

    Fortunately, I have got it working to an "acceptable" level. It just means that if the user accidently enters their username/password incorrectly then the only way to get another attempt is to fully close their web browser and restart it to retry. All because WCF is not responding to the failed authentication attempt with a 401 Unauthorized and a WWW-Authenticate header as per the specification.

    0 讨论(0)
  • 2021-02-08 06:18

    I've found the solution based in this link and this.

    The first is to override the method Validate in a class called CustomUserNameValidator wich inherits from System.IdentityModel.Selectors.UserNamePasswordValidator:

    Imports System.IdentityModel.Selectors
    Imports System.ServiceModel
    Imports System.Net
    
    Public Class CustomUserNameValidator
        Inherits UserNamePasswordValidator
    
    Public Overrides Sub Validate(userName As String, password As String)
        If Nothing = userName OrElse Nothing = password Then
            Throw New ArgumentNullException()
        End If
    
        If Not (userName = "user" AndAlso password = "password") Then
            Dim exep As New AddressAccessDeniedException("Incorrect user or password")
            exep.Data("HttpStatusCode") = HttpStatusCode.Unauthorized
            Throw exep
        End If
    End Sub
    End Class
    

    The trick was change the attribute of the exception "HttpStatusCode" to HttpStatusCode.Unauthorized

    The second is create the serviceBehavior in the App.config as follows:

    <behaviors>
      <endpointBehaviors>
        <behavior name="HttpEnableBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="SimpleServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Service.CustomUserNameValidator, Service"/>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    

    Finally we must to specify the configuration for the webHttpBinding and apply it to the endpoint:

    <bindings>
      <webHttpBinding>
        <binding name="basicAuthBinding">
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Basic" realm=""/>
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
    
    <service behaviorConfiguration="SimpleServiceBehavior" name="Service.webService">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8000/webService" />
          </baseAddresses>
        </host>
        <endpoint address="http://localhost:8000/webService/restful" binding="webHttpBinding" bindingConfiguration="basicAuthBinding" contract="Service.IwebService" behaviorConfiguration="HttpEnableBehavior"/>
    </service>
    
    0 讨论(0)
  • 2021-02-08 06:20

    Yes you can provide Basic authentication for REST based WCF services. However there are several steps which you must follow to have a complete and secure solution and thus far most responses are fragments of all the pieces needed.

    1. Configure your self-hosted service to have a SSL certificate bound to the port which you are hosting your WCF service on. This is very different than applying a SSL cert when using managed hosting through something like IIS. You have to apply the SSL certificate using a command line utility. You DO NOT want to use Basic Authentication on a REST service without using SSL because the credentials in the header on not secure. Here are (2) detailed posts that I wrote on exactly how to do this. Your question is too big to have all the details on a forum post, so that is why I am providing the links with comprehensive details and step by step instructions:

      Applying and Using a SSL Certificate With A Self-Hosted WCF Service

      Creating a WCF RESTful Service And Secure It Using HTTPS Over SSL

    2. Configure your service to use Basic authentication. This is a multi-part solution as well. 1st is configuring your service to use Basic authentication. The second is to create a 'customUserNamePasswordValidatorType' and inspect the credentials to authenticate the client. I see the last post eluded to this, however it did not use HTTPS and is only 1 very small part of the solution; be careful of guidance that does not provided an end-to-end solution inclusive of configuration and security. The last step is to look at the security context to provide authorization at the method level if needed. The following post I wrote takes you step-by-step on how to configure, authenticate, and authorize your clients.

      RESTful Services: Authenticating Clients Using Basic Authentication

    This is the end-to-end solution needed for using Basic Authentication with self-hosted WCF services.

    0 讨论(0)
提交回复
热议问题