У меня есть проблема с реализацией аутентификации 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 ... gin-attemp
Google Oauth и Asp.net Core: не может выполнить логику после успешной попытки входа в систему ⇐ C#
Место общения программистов C#
1750356791
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()
}
});
});
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79672020/google-oauth-and-asp-net-core-cant-execute-logic-after-successful-login-attemp[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия