Skip to content

Getting Started :: Simple Mvc Example

phillip-haydon edited this page Jan 16, 2013 · 2 revisions

ASP.NET Simple MVC Example

This is a simple and quick way to using the library to authenticate with a Provider.

This example doesn't use any Cross-Site Scripting prevention's - the advanced example does that (but requires a wee bit more code to setup).

Step 1 - Create some applications/account with your provider

Step 2 - Setup the providers.

A good place to do this is in the constructor for the Controller -or- use Dependency Injection (my recommendation).

private readonly AuthenticationService _authenticationService;

public AuthenticationController()
{
    var facebookProvider = new FacebookProvider("your facebookApiId",
                                                "Your facebook app secret",
                                                new Uri(
                                                    "http://localhost:1337/home/AuthenticateCallback?providerKey=facebook"));

    _authenticationService = new AuthenticationService();
    _authenticationService.AddProvider(facebookProvider);
}

Step 3 - Create a View which has the buttons/images/whatever.

This is some sample Razor code which shows a few images which are clickable.

<div id="container">
    <fieldset title="Login">
        <legend>Login:</legend>
        <a href="/Home/RedirectToAuthenticate?providerKey=Twitter"><img src="/Content/twitter_32.png"/></a>
        <a href="/Home/RedirectToAuthenticate?providerKey=Facebook"><img src="/Content/facebook_32.png" /></a>
        <a href="/Home/RedirectToFacebookMobile"><img src="/Content/facebook_mobile_32.png" /></a>
        <a href="/Home/RedirectToAuthenticate?providerKey=Google"><img src="/Content/google_32.png"/></a>
    </fieldset>
</div>

Step 4 - Redirect the client to an Authentication Provider (eg. Facebook, etc).

public RedirectResult RedirectToAuthenticate(string providerKey)
{
    var uri = _authenticationService.RedirectToAuthenticationProvider(providerKey);
    return Redirect(uri.AbsoluteUri);
}

Step 5 - Handle the callback from the Authentication Provider. (eg. Facebook, etc).

public class AuthenticateCallbackViewModel
{
    public IAuthenticatedClient AuthenticatedClient { get; set; }
    public Exception Exception { get; set; }
}

public ActionResult AuthenticateCallback(string providerKey)
{
    if (string.IsNullOrEmpty(providerKey))
    {
        throw new ArgumentNullException("providerKey");
    }

    var model = new AuthenticateCallbackViewModel();
    try
    {
        model.AuthenticatedClient = _authenticationService.CheckCallback(providerKey, Request.Params);
    }
    catch (Exception exception)
    {
        model.Exception = exception;
    }

    return View(model);
}