Skip to content

Mvc automatic setup

ignaciofuentes edited this page Dec 8, 2014 · 12 revisions

Preparation

  1. Do you have your Authentication Provider keys?
  2. Are you happy to use the default settings? (ie. default routes, etc?)

Installation: Overview

  1. This is all based on this MVC Sample.
  2. Add a route to a fake provider.
  3. Install the package(s).
  4. Create your custom code to handle what happens after you've returned to your website.
  5. Test
  6. Swap out the fake provider with a real one.
  7. WIN $$$.

Installation: Detailed

Add a 'Click me' link

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> Take note of the hardcoded route. (This can be customized later if you need to).

Install the NuGet package

Install-Package SimpleAuthentication.Mvc

This installs all you need.

Hard part - Custom code, time

This is the hard part. You need to create a class which inherits from SimpleAuthentication.Mvc.IAuthenticationCallbackProvider. 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 a simple class that says: Just return a View and you pass all the info to that view.

public class MyAuthenticationCallbackProvider : 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's another sample class that says: just redirect back to the home page.

public class MyAuthenticationCallbackProvider : IAuthenticationCallbackProvider
{
    public ActionResult Process(HttpContextBase context, AuthenticateCallbackData model)
    {
        return new RedirectResult("/", true);
    }

    public ActionResult OnRedirectToAuthenticationProviderError(HttpContextBase context, string errorMessage)
    {
        return new RedirectResult("/", true);
    }
}

Show me the User!

Now create a View called \Views\SimpeAuthentication\AuthenticateCallback.cshtml and render whatever data you need.

Nearly there ...

To leverage the new class you just made, you need to use Dependency Injection.

So this is how you can set it up using AutoFac

Install [AutoFac] (http://www.nuget.org/packages/Autofac/) and [AutoFac MVC 4 Integration] (http://www.nuget.org/packages/Autofac.Mvc4/)

var builder = new ContainerBuilder();

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

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

Blast off! Test the new code!

Test it! Run the web application and try logging in. You will get some fake data now showing :)

Lets keep it real, please.

Change to a real provider? Change the <a href> code to: <a href="/authentication/redirect/**providerName**>Click here to login to your "provider name"</a> So i just replaced FakeWhaver with a real provider name: Facebook, Google, Twitter or WindowsLive.

Open up your web.config file and add in your Facebook or Google public/private keys.

It really works!

Refresh the login page and test logging in :)