使用Google Auth,Angular 4,ASP.Net Core 2进行身份验证时为405 [英] 405 when authenticating using Google Auth, Angular 4, ASP.Net Core 2

查看:61
本文介绍了使用Google Auth,Angular 4,ASP.Net Core 2进行身份验证时为405的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ASP.NET中间件来使用Google OAuth进行身份验证.我了解我遇到的问题是由于CORS问题引起的,但我似乎无法解决.

I'm trying to use ASP.NET middleware to authenticate using Google OAuth. I understand the problem I am getting is due to CORS issues but I cannot seem to resolve them.

我的启动类配置如下:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
         {
             options.AddPolicy("CorsPolicy",
                builder => builder
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowAnyOrigin()
                .AllowCredentials()
                );
      ......
       services.AddGoogle(o =>
            {
                o.ClientId = Configuration["Authentication:Google:ClientId"];
                o.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
                o.AuthorizationEndpoint += "?prompt=consent"; // Hack so we always get a refresh token, it only comes on the first authorization response
                o.AccessType = "offline";
                o.SaveTokens = true;
                o.Events = new OAuthEvents()
                {
                    OnRemoteFailure = ctx =>
                        {
                            ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message));
                            ctx.HandleResponse();
                            return Task.FromResult(0);
                        }
                };
                o.ClaimActions.MapJsonSubKey("urn:google:image", "image", "url");
                o.ClaimActions.Remove(ClaimTypes.GivenName);
            });
...........
 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();

        //if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors("CorsPolicy");

        app.Use(async (context, next) =>
            {
                await next();
                // Serve index file and allow Angular to take over routing if (NotFound)
                if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
                {
                    context.Request.Path = "/index.html";
                    await next();
                }

            });

        app.UseAuthentication();

        app.UseDefaultFiles();
        app.UseStaticFiles();

        app.UseMvc();
    }

在我的Auth Controller中:

In my Auth Controller:

// POST: api/auth/ExternalLogin
    [HttpPost("loginexternal")]
    [AllowAnonymous]
    public async Task<IActionResult> LoginExternal([FromBody]string provider)
    {
        // Clear the existing external cookie to ensure a clean login process
        await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

        // Request a redirect to the external login provider to link a login for the current user
        var redirectUrl = Url.Action(nameof(ExternalLoginCallback));
        var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
        return new ChallengeResult(provider, properties);
    }

我的打字稿角码调用此函数:

My typescript angular code which calls this function:

 loginExternal() {

    const headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json' });


    return this.http.post(this.baseUrl + '/auth/loginexternal', '"Google"', { headers: headers })
        .map((res: any) => {
            localStorage.setItem('auth_token', res.auth_token);
            this.loggedIn = true;
            this._authNavStatusSource.next(true);
            return true;
        })
        .catch(this.handleError);
}

这是回应

在我的LoginExternal操作中执行ChallengeResult之后,就会发生上述响应.

The above response occures after the ChallengeResult is executed in my LoginExternal action.

推荐答案

尝试使用this.document.location.href甚至window.location.href重定向到您的Google身份验证页面,而不是向您的.net发出http请求核心控制器动作.

Try to use this.document.location.href or even window.location.href to redirect to your google authentication page instead of making http request to your .net core controller action.

@Injectable()
export class LoginService {
    //...

    constructor(@Inject(DOCUMENT) private document: Document,...)

    login() {
        this.document.location.href 'https://www.mywebsite.com/account/signInWithGoogle';
    }
}

这是控制器动作中的样子:

Here’s how that looks like in a controller action:

public class AccountController : Controller
{
    private readonly SignInManager<IdentityUser> _signInManager;
    private readonly UserManager<IdentityUser> _userManager;
    public AccountController(SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager)
    {
        _signInManager = signInManager;
        _userManager = userManager;
    }

    public IActionResult SignInWithGoogle()
    {
        var authenticationProperties = _signInManager.ConfigureExternalAuthenticationProperties("Google", Url.Action(nameof(HandleExternalLogin)));
        return Challenge(authenticationProperties, "Google");
    }

    ...

指南: https://www.blinkingcaret.com/2018/10/10/sign-in-with-an-external-login-provider-in-an-角度应用程序由asp-net-core/

这篇关于使用Google Auth,Angular 4,ASP.Net Core 2进行身份验证时为405的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆