Self-hosted WCF REST service and Basic authentication

后端 未结 3 1252
心在旅途
心在旅途 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: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:

    
      
        
          
        
      
      
        
          
          
          
            
          
        
      
    
    

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

    
      
        
          
            
          
        
      
    
    
    
        
          
            
          
        
        
    
    

提交回复
热议问题