Getting current Authentication information on WCF REST Service


Sometime you may have a requirement to tell your client what type of authentication scheme you are applying on your WCF REST service. In this article I will show you, "How can you expose authentication scheme information as part of your service?".

To start with let us create a Self Hosted WCF REST Service. Besides other resources [OperationContracts] of your REST Service add a function to return Authentication type as a string in a Service Contract.

WCF1.gif

We are returning an authentication scheme as a string.

If you don't have any other functions than GetAuthenticationType() then your service contract would look like below:

IService1.cs

using System.ServiceModel;
using System.ServiceModel.Web;
namespace WcfService13
{
    
    [ServiceContract]
    public interface IService1
    {             
 
        [OperationContract]
        [WebGet(UriTemplate = "/GetAuthenticationType")]
        string GetAuthenticationType();       
             
    }
 
}


Now we need to implement the service to return the authentication scheme.

WCF2.gif

In the implementation:

  1. We are creating an instance of a current operation context.
  2. If the context is null then that means there is no authentication.
  3. If it is not null then we are checking whether it is anonymous.
  4. If it is not anonymous then we are simply assigning the primary identity name.

For your reference your service would be like below:
Service1.svc.cs

using System.ServiceModel;

namespace WcfService13
{
    public class Service1 : IService1
    {      
       public string GetAuthenticationType()
        {
            ServiceSecurityContext context = OperationContext.Current.ServiceSecurityContext;
            string authenticationType = "Oh!There is no Authentication on my REST Service";
            if (context != null)
            {
                if (context.IsAnonymous)
                {
                    authenticationType = "Anonymous Authentication";
                }
                else
                {
                    authenticationType = context.PrimaryIdentity.Name;
                }
            }
             return authenticationType;
         }   
       
    }
}


Since we have created a self-hosted WCF REST Service, press F5 to call the webGet method from the browser.

WCF3.gif

Up Next
    Ebook Download
    View all
    Learn
    View all