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 post I will show you, “How could you expose authentication scheme information as part of your service? “

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

clip_image001

We are returning authentication scheme as 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.

clip_image003

In implementation

1. We are creating instance of current operation context.

2. If context is null means there is no authentication.

3. If it is not null then we are checking whether is anonymous.

4. If it is not anonymous then simply we are assigning Primary identity name.

For your reference your service would 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 browser.

clip_image005

One response to “Getting current Authentication information on WCF REST Service”

  1. […] Getting current Authentication information on WCF REST Service […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com