MVC 5 OAuth with CORS
Asked Answered
R

2

10

I read several post talking about some similar problems, but I don't get yet to do this to work.

I'm doing ajax to "Account/ExternalLogin" which generates the ChallengeResult and starts the flow for the authentication with OWIN.

This is my Startup class :

public partial class Startup
{
    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {            
        // Enable the application to use a cookie to store information for the signed in user
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login")
        });
        // Use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        app.UseCors(CorsOptions.AllowAll);
        var goath2 = new Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions
        {
            ClientId = "myclientid",
            ClientSecret = "mysecret",
            Provider = new Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationProvider
            {
                OnApplyRedirect = context =>
                {
                    string redirect = context.RedirectUri;

                    const string Origin = "Origin";
                    const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";

                    // origin is https://localhost:44301                        
                    var origin = context.Request.Headers.GetValues(Origin).First();


                    // header is present
                    var headerIsPresent = context.Response.Headers.ContainsKey(AccessControlAllowOrigin);
                    context.Response.Redirect(redirect);                        
                }
            }
        };

        app.UseGoogleAuthentication(goath2);
    }
}

I'm enabling CORS support whith the line app.UserCors(CorsOptinos.AllowAll); And I know the header is being added to the response because I intercept the OnApplyRedirectevent and when I look for the origin it is setted to 'localhost:443001' and the header 'Access-Control-Allow-Origin' is setted also to this value.

Nevertheless when the response is sent to the client I have the following error:

XMLHttpRequest cannot load https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxxx No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin https://localhost:44301 is therefore not allowed access.

What I'm missing here.

I could get a work around doing all this "manually" (requesting directly google from the client...) but I really want to use the OWIN middleware.

Rodrigorodrigue answered 8/12, 2014 at 18:52 Comment(0)
F
0

You are making request to google from https://localhost:44301 domain. In order that to work 'Access-Control-Allow-Origin' should have 'https://localhost:44301' origin domain in the list. So in this case it's google who need to set this domain in the 'Access-Control-Allow-Origin'.

Looking at the response you are getting it seems that google doesn't allow Cros origin request from your domain. To solve this I believe you need to register your domain on google https://developers.google.com.

Fidelafidelas answered 25/12, 2014 at 5:45 Comment(0)
C
0

-> Please follow my Steps :-

  • Create endpoint in your app. to handle authentication flow with google in Server-side.

  • Make AJAX request in your client-side to this endpoint to Google's OAuth2 endpoint.

  • Authentication flow with Google using OWIN middleware , in server-side endpoint and then after done authentication, return response to client.

  • create new endpoint :- AccountController:-

    [HttpGet]
    [Route("ExternalLogin")]
    public async Task<ActionResult> ExternalLogin()
    {
      var properties = new AuthenticationProperties
      {
          RedirectUri = Url.Action("ExternalLoginCallback")
      };
    
       return await Task.FromResult(Challenge(properties, "Google"));
     }
    
    [HttpGet]
    [Route("ExternalLoginCallback")]
    public async Task<ActionResult> ExternalLoginCallback()
    {
        // Handle the callback after successful authentication
       var loginInfo = await 
       AuthenticationManager.GetExternalLoginInfoAsync();
    
       // Process the loginInfo as needed and return response
       // You may redirect or return a JSON response indicating success
    
        return Json(new { success = true, loginInfo });
      }
    
  • Update your javascript code for new endpoint for AJAX request :-

        function initiateExternalLogin() {
          $.ajax({
          url: '/Account/ExternalLogin',
          type: 'GET',
          success: function(response) {
                // Handle success, if needed
                console.log(response);
            },
           error: function(xhr, status, error) {
           // Handle error, if needed
           console.error(xhr.responseText);
           }
          });
         }
    
  • please check authentication middleware is correctly set up in your Startup.cs file.

Cotidal answered 29/2 at 13:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.