Authenticating Users To Your Site Using OAuth/OpenID Provider in ASP.NET MVC

Do you want to allow users to login to your site via an OAuth or OpenID provider such as facebook, twitter or google? I’ll show you how to do this easily using SimpleAuthentication.

SimpleAuthentication is an ASP.NET library that makes it really simple for developers to add Social Authentication code to an ASP.NET application. The library only deals with authentication , once you get the user details for the person logging in, you can do whatever you want with that (such as, create a new user or update an existing user). You can take advantage of the Glimpse plugin so you can see what magic is happening under the hood if you need to debug. You can install it via Nuget, and it supports MVC3, MVC 4 or NancyFx project types.

Follow the steps below to add it to your MVC 4 application:
1. Install the Nuget Package for MVC 4.

Open the package manager console and enter “Install-Package SimpleAuthentication.MVC”

Install-Package SimpleAuthentication.MVC

2 Create a class which inherits from SimpleAuthentication.Mvc.IAuthenticationCallbackProvider. This class contains two methods: Process and OnRedirectToAuthenticationProviderError which you will implement. The Process method is executed when the authentication request from the OAuth/OpenID provider is successful and the other method is executed when there is an error.This class handles your own custom logic when you’ve finished authenticating and want to do something with the user data. For example, do you want to create a new account? Check if the user already exists? Add the user details to a Session? etc.
Here’s an example that just returns a view:

public class SampleMvcAutoAuthenticationCallbackProvider : IAuthenticationCallbackProvider
{
    public ActionResult Process(HttpContextBase context, AuthenticateCallbackData model)
    {
        return new ViewResult
        {
            ViewName = "AuthenticateCallback",
            ViewData = new ViewDataDictionary(new AuthenticateCallbackViewModel
            {
                AuthenticatedClient = model.AuthenticatedClient,
                Exception = model.Exception,
                ReturnUrl = model.ReturnUrl
            })
        };
    }

    public ActionResult OnRedirectToAuthenticationProviderError(HttpContextBase context, string errorMessage)
    {
        return new ViewResult
        {
            ViewName = "AuthenticateCallback",
            ViewData = new ViewDataDictionary(new IndexViewModel
            {
                ErrorMessage = errorMessage
            })
        };
    }
}

Here is another sample that stores the user information to the session using claims and WIF Session Authentication:

public ActionResult Process(HttpContextBase context, AuthenticateCallbackData model)
{
    //FormsAuthentication.SetAuthCookie(model.AuthenticatedClient.UserInformation.UserName, false);
    var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, model.AuthenticatedClient.UserInformation.UserName, ClaimValueTypes.String,
                      model.AuthenticatedClient.ProviderName),
            new Claim(ClaimTypes.Email, "email@email.com", ClaimValueTypes.Email,
                      model.AuthenticatedClient.ProviderName)
        };
    var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Custom"));

    //create the session token
    var sessionToken = new SessionSecurityToken(claimsPrincipal);
    FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionToken);

    //validate return url using Url.IsLocal()
    return new RedirectResult("/Fixture/Auth", true);
}

public ActionResult OnRedirectToAuthenticationProviderError(HttpContextBase context, string errorMessage)
{
    return new ViewResult
    {
        ViewName = "AuthenticateCallback",
        ViewData = new ViewDataDictionary(new IndexViewModel
        {
            ErrorMessage = errorMessage
        })
    };
}

3 Create a view called ViewsSimpeAuthenticationAuthenticateCallback.cshtml and render whatever data you need.

4 To leverage the new class you just made, you need to use Dependency Injection. Install and configure AutoFac and AutoFac For MVC 4 Integration
Here’s a sample code:

~ Global.asax ~

var builder = new ContainerBuilder();

builder.RegisterType<SampleMvcAutoAuthenticationCallbackProvider>().As<IAuthenticationCallbackProvider>();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterControllers(typeof(SimpleAuthenticationController).Assembly);

var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

5 Add a route that starts the login process. This can be a simple anchor tag or a button, etc. <a href="/authentication/redirect/fakeWhatever">Click me to login with FakeyFake</a>.

6 Add your Provider AppId and Secret Key to the config section in web.config. Then Change all links from /authentication/redirect/fakeWhatever to /authentication/redirect/[provider name].

You can find a sample code which demonstrate using it in an MVC 4 application Here

Advertisements

2 thoughts on “Authenticating Users To Your Site Using OAuth/OpenID Provider in ASP.NET MVC

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 )

Google+ photo

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

Connecting to %s