使用CORS的MVC 5 OAuth

sab*_*ero 10 ajax asp.net-mvc cors oauth-2.0 google-oauth

我读了几篇关于一些类似问题的帖子,但我还没有做到这一点.

我正在对"Account/ExternalLogin"执行ajax,它生成ChallengeResult并启动使用OWIN进行身份验证的流程.

这是我的Startup班级:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在启用线路上的CORS支持app.UserCors(CorsOptinos.AllowAll); 并且我知道标题正被添加到响应中,因为我拦截了OnApplyRedirect事件,当我查找原点时,它被设置为'localhost:443001'并且标题'Access-Control-Allow -Origin'也设置为此值.

然而,当响应发送到客户端时,我有以下错误:

XMLHttpRequest无法加载 https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxxx 请求的资源上没有"Access-Control-Allow-Origin"标头.https://localhost:44301因此不允许原点访问.

我在这里失踪了什么.

我可以"手动"完成所有这些工作(从客户端直接请求谷歌......)但我真的想使用OWIN中间件.

Pra*_*ash 0

您正在从域向 google 发出请求https://localhost:44301。为了使其正常工作,“Access-Control-Allow-Origin”应该'https://localhost:44301'在列表中具有源域。因此,在这种情况下,谷歌需要在“Access-Control-Allow-Origin”中设置此域。

查看您收到的响应,谷歌似乎不允许来自您的域的跨源请求。为了解决这个问题,我相信您需要在谷歌https://developers.google.com上注册您的域名。