Добавил Google auth

This commit is contained in:
Sergey Karmanov 2023-12-24 04:58:01 +03:00
parent b5477d529f
commit ac987781fa
Signed by: serega404
GPG Key ID: B6AD49C8C835460C
2 changed files with 78 additions and 2 deletions

View File

@ -1,6 +1,9 @@
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims; using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.Google; using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
@ -141,6 +144,73 @@ public class UsersController : ControllerBase
return Ok(new { userWr.Id, Token = token }); return Ok(new { userWr.Id, Token = token });
} }
[AllowAnonymous]
[HttpGet("signin-google")]
public IActionResult SignInWithGoogle()
{
var properties = new AuthenticationProperties { RedirectUri = Url.Action("SignInWithGoogleCallback") };
return Challenge(properties, GoogleDefaults.AuthenticationScheme);
}
[AllowAnonymous]
[HttpGet("signin-google-callback")]
public async Task<IActionResult> SignInWithGoogleCallback()
{
var result = await HttpContext.AuthenticateAsync(GoogleDefaults.AuthenticationScheme);
if (result?.Succeeded != true)
{
return BadRequest("Ошибка аутентификации Google");
}
// Извлеките информацию о пользователе из результата аутентификации
var claims = result.Principal!.Identities
.FirstOrDefault(y => y.AuthenticationType == GoogleDefaults.AuthenticationScheme)?
.Claims;
var email = claims?.FirstOrDefault(x => x.Type == ClaimTypes.Email)!.Value;
var name = claims?.FirstOrDefault(x => x.Type == ClaimTypes.Name)!.Value;
var user = await _userManager.FindByEmailAsync(email!);
var role = "спикер";
if(user is null)
{
user = new User
{
Fio = name!,
Specialities = string.Empty,
TelegramBotUrl = string.Empty,
AvatarUrl = $"https://www.gravatar.com/avatar/{BitConverter.ToString(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(email!))).Replace("-", "").ToLowerInvariant()}?d=identicon",
UserName = name,
Email = email
};
var createResult = await _userManager.CreateAsync(user);
if (!createResult.Succeeded)
return BadRequest(createResult.Errors);
await AddUerToRole(user, role);
}
var token = GetToken(user, role);
// Здесь вы можете создать JWT или другой токен для аутентификации в вашем приложении
// и отправить его пользователю.
return Ok(new {
Token = token,
User = user
});
}
[Authorize] [Authorize]
[HttpGet] [HttpGet]
public async Task<IActionResult> GetUserData(string id) public async Task<IActionResult> GetUserData(string id)

View File

@ -7,6 +7,7 @@ using Microsoft.Extensions.FileProviders;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Authentication.Google;
TypeAdapterConfig<PutMeetingDto, Meeting>.NewConfig().Map(d => d.SpeackerImage, s => s.SpeackerImage.JoinFileNames()); TypeAdapterConfig<PutMeetingDto, Meeting>.NewConfig().Map(d => d.SpeackerImage, s => s.SpeackerImage.JoinFileNames());
@ -34,14 +35,19 @@ builder.Services.AddIdentity<User, IdentityRole>()
builder.Services.AddAuthentication(opt => { builder.Services.AddAuthentication(opt => {
opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; opt.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
}) })
.AddJwtBearer(options => .AddJwtBearer(options =>
{ {
var bearerOptions = new BearerAccessTokenOptions(); var bearerOptions = new BearerAccessTokenOptions();
options.RequireHttpsMetadata = bearerOptions.RequiredHttpsMetadata; options.RequireHttpsMetadata = bearerOptions.RequiredHttpsMetadata;
options.TokenValidationParameters = bearerOptions.TokenValidationParameters; options.TokenValidationParameters = bearerOptions.TokenValidationParameters;
}); })
.AddGoogle(options =>
{
options.ClientId = builder.Configuration["Google:ClientId"]!;
options.ClientSecret = builder.Configuration["Google:ClientSecret"]!;
});;