[英]405 when authenticating using Google Auth, Angular 4, ASP.Net Core 2
我正在嘗試使用ASP.NET中間件來使用Google OAuth進行身份驗證。 我理解我遇到的問題是由於CORS問題,但我似乎無法解決它們。
我的Startup類配置如下:
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控制器中:
// 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);
}
調用此函數的我的打字稿角度代碼:
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后發生上述響應。
嘗試使用this.document.location.href甚至window.location.href重定向到您的google身份驗證頁面,而不是向您的.net核心控制器操作發出http請求。
@Injectable()
export class LoginService {
//...
constructor(@Inject(DOCUMENT) private document: Document,...)
login() {
this.document.location.href 'https://www.mywebsite.com/account/signInWithGoogle';
}
}
這是控制器動作中的樣子:
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-angular-application-served-by-asp-net-core/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.