On my last post I mentioned that the live sample that showed how to authenticate with OpenId stopped working with the Google provider (for whatever reason). So this week I have been catching up with writing ASP.NET applications using OWIN and the social authentication middleware.
So here is the live sample updated to use the Google OAuth 2.0 middleware: http://samples.federicosilva.net/Samples/Authentication
Getting started with OWIN turned out to be more complicated than I anticipated. There are obscure extension methods scattered in what seems random assemblies, limited documentation and the project template comes with tons of code with little explanation of what is happening and is dependent on EntityFramework (!?). Reverse engineering and scavenge for information in StackOverflow was not a pleasant user experience.
But after distilling all the code that comes in the template, the minimal controller to authenticate and get information from an external provider looks like this (after enabling the middleware in app start):
public class AuthController : Controller
{
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider)
{
return new AuthChallengeActionResult(provider, Url.Action("ExternalLoginCallback"));
}
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback()
{
var authenticationManager = HttpContext.GetOwinContext().Authentication;
var loginInfo = await authenticationManager.GetExternalLoginInfoAsync();
if (loginInfo != null)
{
TempData.Add("email", loginInfo.Email);
TempData.Add("name", loginInfo.DefaultUserName);
}
return RedirectToAction("Authentication", "Samples");
}
}
The only other custom thing is the challenge action result, which just wraps a call to IAuthenticationManager.Challenge:
public class AuthChallengeActionResult : HttpUnauthorizedResult
{
public AuthChallengeActionResult(string provider, string redirectUri)
{
LoginProvider = provider;
RedirectUri = redirectUri;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
Federico
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.