How to implement WebServiceHost Authentication?

后端 未结 3 1292
萌比男神i
萌比男神i 2020-12-21 18:59

I\'m aware that the authentication on the webservicehost class does not adhere fully to authentication standards (returns 403 forbidden rather than prompting for another set

3条回答
  •  生来不讨喜
    2020-12-21 19:39

    Shaydo, you are the best! Thank you! That is what I searched for for weeks! I expanded the vb Code in order to use it with https: VB.NET:

    Public Class AuthenticatedWebServiceHost
       Inherits WebServiceHost
        Public Sub New(ByVal type As Type, ByVal url As Uri, MyThumbprint As String)
            Dim desc As IDictionary(Of String, ContractDescription) = Nothing
            MyBase.InitializeDescription(type, New UriSchemeKeyedCollection())
            MyBase.CreateDescription(desc)
            Dim val = desc.Values.First()
            Dim binding As WebHttpBinding = New WebHttpBinding()
            'binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly
            binding.Security.Mode = BasicHttpsSecurityMode.TransportWithMessageCredential
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic
            MyBase.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom
            MyBase.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = New CustomUserNamePasswordValidator()
            MyBase.Credentials.ClientCertificate.SetCertificate(System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine, System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.X509FindType.FindByThumbprint, MyThumbprint)
            MyBase.AddServiceEndpoint(val.ContractType, binding, url)
        End Sub
    
        Public Shared ReadOnly Property UserName As String
            Get
                If OperationContext.Current Is Nothing Then Return Nothing
                If OperationContext.Current.ServiceSecurityContext Is Nothing Then Return Nothing
                If OperationContext.Current.ServiceSecurityContext.PrimaryIdentity Is Nothing Then Return Nothing
                Return OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name
            End Get
        End Property
    
        Public Class CustomUserNamePasswordValidator
            Inherits UserNamePasswordValidator
            Public Overrides Sub Validate(ByVal userName As String, ByVal password As String)
                If userName <> password Then
                    Console.WriteLine("Error: Access denied")
                    Throw New SecurityAccessDeniedException()
                End If
            End Sub
        End Class
    End Class
    

提交回复
热议问题