How to implement WebServiceHost Authentication?

后端 未结 3 1312
萌比男神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:42

    The answer provided by I4V worked like a charm, converted to VB and copied below in case anyone else needs it in future after spending many hours hunting the web.

    The Line to call it is as per the code provided by I4V.

    Dim varWebService = New AuthenticatedWebServiceHost(GetType(MyWebService), New Uri("http://0.0.0.0/"))
    

    VB.Net Code

    Imports System.IdentityModel.Selectors
    Imports System.ServiceModel
    Imports System.ServiceModel.Description
    Imports System.ServiceModel.Security
    Imports System.ServiceModel.Web
    
    Public Class AuthenticatedWebServiceHost
        Inherits WebServiceHost
    
        Public Sub New(ByVal type As Type, ByVal url As Uri)
            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.Transport.ClientCredentialType = HttpClientCredentialType.Basic
            MyBase.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom
            MyBase.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = New CustomUserNamePasswordValidator()
            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 Throw New SecurityAccessDeniedException()
            End Sub
        End Class
    End Class
    

提交回复
热议问题