Getting current Authentication information on WCF REST Service

In this article I will show you, how can you expose authentication scheme information as part of your 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.
 
 
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
  1. using System.ServiceModel;  
  2. using System.ServiceModel.Web;  
  3. namespace WcfService13  
  4. {  
  5.     [ServiceContract]  
  6.     public interface IService1  
  7.     {  
  8.         [OperationContract]  
  9.         [WebGet(UriTemplate = "/GetAuthenticationType")]  
  10.         string GetAuthenticationType();              
  11.     }  
  12. }  
Now we need to implement the service to return the authentication scheme.
 
 
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
  1. using System.ServiceModel;  
  2.   
  3. namespace WcfService13  
  4. {  
  5.     public class Service1 : IService1  
  6.     {        
  7.        public string GetAuthenticationType()  
  8.         {  
  9.             ServiceSecurityContext context = OperationContext.Current.ServiceSecurityContext;  
  10.             string authenticationType = "Oh!There is no Authentication on my REST Service";  
  11.             if (context != null)  
  12.             {  
  13.                 if (context.IsAnonymous)  
  14.                 {  
  15.                     authenticationType = "Anonymous Authentication";  
  16.                 }  
  17.                 else  
  18.                 {  
  19.                     authenticationType = context.PrimaryIdentity.Name;  
  20.                 }  
  21.             }  
  22.              return authenticationType;  
  23.          }   
  24.     }  
  25. }  
Since we have created a self-hosted WCF REST Service, press F5 to call the webGet method from the browser.