首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ASP .NET核心CORS与谷歌重定向认证问题

ASP .NET核心CORS与谷歌重定向认证问题
EN

Stack Overflow用户
提问于 2022-03-15 19:23:30
回答 1查看 663关注 0票数 0

为了在我的web中实现谷歌身份验证,一直遵循这个教程,但是在客户端(使用React和axios来执行请求),这个CORS问题会中断身份验证过程,我很难解决这个问题:

CORS策略阻止从“https://accounts.google.com/o/oauth2/v2/auth?(etc)”(从“https://localhost:44320/Photo/b997d788-3812-41d0-a09d-1a597eee9bad'”重定向)访问“https://localhost:8080”:请求的资源上不存在“访问-控制-允许-原产地”标题。

这是Startup.cs文件:

代码语言:javascript
复制
namespace rvc
{
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddDefaultPolicy(builder =>
            {
                builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
            });
        });
        
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        }).AddCookie(options =>
        {
            options.LoginPath = "/account/google-login";
        }).AddGoogle(options =>
        {
            options.ClientId = "clientId";
            options.ClientSecret = "secret";
        });
        
        services.AddScoped<PhotoService>();
        services.AddScoped<TagService>();
        services.AddScoped(_ => new BlobServiceClient(Configuration.GetConnectionString("AzureBlobStorage")));
        services.AddDbContext<Data.DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddControllers().AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
        });
        services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "rvc", Version = "v1" }); });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "rvc v1"));
        }

        app.UseHttpsRedirection();

        if (env.IsProduction())
        {
            app.UseSpa(spa => { });

            app.UseFileServer(new FileServerOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(env.ContentRootPath, "client")),
                EnableDefaultFiles = true
            });
        }

        app.UseRouting();
        app.UseCors();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
    }
}
}

路由(“google-login”)被调用,但未到达Url.Action("GoogleResponse")。这些是Google身份验证方法:

代码语言:javascript
复制
namespace rvc.Controllers;

[AllowAnonymous, Route("account")]
public class AccountController : Controller
{ 
[Route("google-login")]
public IActionResult GoogleLogin()
{
    var properties = new AuthenticationProperties {RedirectUri = Url.Action("GoogleResponse")};
    return Challenge(properties, GoogleDefaults.AuthenticationScheme);
}

[Route("google-response")]
public async Task<IActionResult> GoogleResponse()
{
    var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);

    var claims = result.Principal?.Identities.FirstOrDefault()
        ?.Claims.Select(claim => new
    {
        claim.Issuer,
        claim.OriginalIssuer,
        claim.Type,
        claim.Value
    });

    return Json(claims);
}
}
EN

回答 1

Stack Overflow用户

发布于 2022-03-15 19:43:00

这可能是因为您使用重定向的服务器,这会触发CORS (即使从您的服务器允许它)。您必须以其他方式将重定向URL返回到前端,从前端应用程序捕获它,然后调用您需要调用的URL。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71487874

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档