Tuesday, March 5, 2019

Integrate Google Oauth 2.O OpenId without Owin in sitecore asp.net mvc

Introduction:

I've sitecore 8.2.1 and content delivery web app is integrated with form based authentication. I enabled third party google login using OAuth2.0 open id without using .net OWIN or Sitecore OWIN setup. 
I just keep the whole flow simple with very minimal impact to the overall architecture. Made solution easy to decouple in future or reuse it across the different project.

The below problem statement is addressed while implementing this solution
  • Handle Session timeout for form based users and google logged in users differently
  • Handle log-off so that user is redirected to specific login page.
  • Handle CSRF Cross side anitorgery token using State property of api call.

Let's get started

I assume one understand to enable google oauth using developer console and well verse with the whole steps of how google oauth and api is enabled for us to proceed. If not I recommend to go through this using below links

It is two step implementation

  1. Create a separate login screen or existing screen for that matter. Assume there is a button say google login in it. On click of it , it will initiate google login screen and consent form etc.Google returns Authorization code.
  2. When user select his/her google account and give consent user is redirected to respective home or landing page. In this part access token is received based on Authorization code. Custom authorization can be checked against custom application database and accordingly user will be redirect to landing page. Mind it. The first redirection url is registered with google that is where we will write our login in controller action. 

Initiate Google Login process


Key take away

In order to work through different login mechanism the only way to handle session and log-off is to set a application level state flag.
Set something at very beginning of login initialization

HttpContext.Application.Add("google_logged_in_users"true);



Also very important once we get google access token and we verify google users to have access to our system. It is important to check @if (User.Identity.IsAuthenticated)


please note above code is just for reference and it is draft version. You can refine and refactor as per your needs.

Reference: