Google Oauth и ASP .NET: не может выполнить логику после успешной попытки входа в системуC#

Место общения программистов C#
Ответить
Anonymous
 Google Oauth и ASP .NET: не может выполнить логику после успешной попытки входа в систему

Сообщение Anonymous »

У меня есть проблема с реализацией аутентификации Google. В моем приложении мы аутентифицируем пользователей, выпустив им JWT, но подпись с Google также важен, поэтому я попытался реализовать какой -либо обмен токенами. Пользователь видит пустую страницу, и больше ничего не происходит. Контроллер: < /p>
[Route("api")]
[ApiController]
public class GoogleController : ControllerBase
{
[AllowAnonymous]
[HttpGet("google")]
public async Task Login()
{
await HttpContext.ChallengeAsync(GoogleDefaults.AuthenticationScheme,
new AuthenticationProperties
{
RedirectUri = Url.Action("GoogleResponse")
});
}

[AllowAnonymous]
[HttpGet("GoogleResponse")]
public async Task GoogleResponse()
{
var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
throw new NotImplementedException();
}
}
< /code>
Program.cs:
using myApp.Infrastructure.Extensions;
using myApp.WebAPI.Extensions;
using myApp.Application.Extensions;
using System.Net;
using System.Net.Security;
using myApp.WebAPI.MiddleWares;
using Microsoft.AspNetCore.HttpOverrides;
using myApp.WebAPI.Extensions;

var builder = WebApplication.CreateBuilder(args);
//builder.WebHost.UseUrls("http://0.0.0.0:5234");

// Add services to the container.

System.Net.ServicePointManager.ServerCertificateValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => true;

builder.Services.AddScoped();
builder.Services.AddMvc();
builder.Services.AddInfrastructure(builder.Configuration);
builder.Services.AddApplication();
builder.AddPresentation(builder.Configuration);

var app = builder.Build();

app.UseForwardedHeaders(new()
{
ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost,
KnownNetworks = { },
KnownProxies = { }
});

//Configure the HTTP request pipeline.
app.UseMiddleware();

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

app.Run();
< /code>
And this is a class that stores the configuration:
public static class WebApplicationBuilderExtensions
{
public static void AddPresentation(this WebApplicationBuilder builder, IConfiguration configuration)
{
var authenticationSettings = new AuthenticationSettings();
builder.Services.AddSingleton();
builder.Services.AddSingleton(authenticationSettings);
configuration.GetSection("Authentication").Bind(authenticationSettings);
builder.Services.AddAuthentication()
.AddCookie("Cookies")
.AddGoogle("Google", options =>
{
options.ClientId = builder.Configuration["GoogleKeys:ClientId"];
options.ClientSecret = builder.Configuration["GoogleKeys:ClientSecret"];
options.SignInScheme = "Cookies";
});

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
// Add login policy to Swagger (so the Login button is visible)
options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
Scheme = "Bearer"
});

// Add reference, so that token is injected into the header of a request scheme
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "bearerAuth"
}
},
new List()
}
});
});
}
}


Подробнее здесь: https://stackoverflow.com/questions/796 ... in-attempt
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»