feat: подключил ms sso
This commit is contained in:
@@ -58,7 +58,7 @@ docker run --rm --name universe-postgres \
|
|||||||
-e POSTGRES_USER=postgres \
|
-e POSTGRES_USER=postgres \
|
||||||
-e POSTGRES_PASSWORD=postgres \
|
-e POSTGRES_PASSWORD=postgres \
|
||||||
-p 5432:5432 \
|
-p 5432:5432 \
|
||||||
postgres:16
|
postgres:18
|
||||||
```
|
```
|
||||||
|
|
||||||
2) Применить миграции (первый раз потребуется `dotnet-ef`):
|
2) Применить миграции (первый раз потребуется `dotnet-ef`):
|
||||||
|
|||||||
@@ -17,7 +17,8 @@ public class AuthController : ControllerBase
|
|||||||
public async Task<ActionResult<AuthResponse>> LoginMicrosoft([FromBody] LoginMicrosoftRequest request)
|
public async Task<ActionResult<AuthResponse>> LoginMicrosoft([FromBody] LoginMicrosoftRequest request)
|
||||||
{
|
{
|
||||||
var result = await _auth.LoginWithMicrosoftAsync(request.AuthorizationCode);
|
var result = await _auth.LoginWithMicrosoftAsync(request.AuthorizationCode);
|
||||||
return Ok(result);
|
SetRefreshTokenCookie(result.RefreshToken);
|
||||||
|
return Ok(result.Response);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("login/dev")]
|
[HttpPost("login/dev")]
|
||||||
@@ -26,8 +27,8 @@ public class AuthController : ControllerBase
|
|||||||
if (!HttpContext.RequestServices.GetRequiredService<IWebHostEnvironment>().IsDevelopment())
|
if (!HttpContext.RequestServices.GetRequiredService<IWebHostEnvironment>().IsDevelopment())
|
||||||
return NotFound();
|
return NotFound();
|
||||||
var result = await _auth.DevLoginAsync(request.Email, request.DisplayName, request.Role);
|
var result = await _auth.DevLoginAsync(request.Email, request.DisplayName, request.Role);
|
||||||
SetRefreshTokenCookie(result.AccessToken); // simplified: set cookie logic
|
SetRefreshTokenCookie(result.RefreshToken);
|
||||||
return Ok(result);
|
return Ok(result.Response);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("refresh")]
|
[HttpPost("refresh")]
|
||||||
@@ -36,7 +37,8 @@ public class AuthController : ControllerBase
|
|||||||
var refreshToken = Request.Cookies["refreshToken"];
|
var refreshToken = Request.Cookies["refreshToken"];
|
||||||
if (string.IsNullOrEmpty(refreshToken)) return Unauthorized();
|
if (string.IsNullOrEmpty(refreshToken)) return Unauthorized();
|
||||||
var result = await _auth.RefreshTokenAsync(refreshToken);
|
var result = await _auth.RefreshTokenAsync(refreshToken);
|
||||||
return Ok(result);
|
SetRefreshTokenCookie(result.RefreshToken);
|
||||||
|
return Ok(result.Response);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Authorize]
|
[Authorize]
|
||||||
|
|||||||
@@ -10,11 +10,13 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.0" />
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.7" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.0">
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.0">
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
|
<PackageReference Include="Microsoft.Identity.Web" Version="4.9.0" />
|
||||||
|
<PackageReference Include="Microsoft.Identity.Web.MicrosoftGraph" Version="4.9.0" />
|
||||||
<PackageReference Include="Microsoft.OpenApi" Version="2.4.1" />
|
<PackageReference Include="Microsoft.OpenApi" Version="2.4.1" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.1.7" />
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.1.7" />
|
||||||
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
|
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"Logging": {
|
"Logging": {
|
||||||
"LogLevel": {
|
"LogLevel": {
|
||||||
"Default": "Information",
|
"Default": "Information",
|
||||||
"Microsoft.AspNetCore": "Warning"
|
"Microsoft.AspNetCore": "Information"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ using UniVerse.Domain.Enums;
|
|||||||
namespace UniVerse.Application.DTOs.Auth;
|
namespace UniVerse.Application.DTOs.Auth;
|
||||||
|
|
||||||
public record AuthResponse(string AccessToken, DateTime ExpiresAt, UserAuthDto User);
|
public record AuthResponse(string AccessToken, DateTime ExpiresAt, UserAuthDto User);
|
||||||
|
public record AuthResult(AuthResponse Response, string RefreshToken);
|
||||||
|
|
||||||
public record UserAuthDto(int Id, string Email, string? DisplayName, UserRole Role);
|
public record UserAuthDto(int Id, string Email, string? DisplayName, UserRole Role);
|
||||||
|
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ namespace UniVerse.Application.Interfaces;
|
|||||||
|
|
||||||
public interface IAuthService
|
public interface IAuthService
|
||||||
{
|
{
|
||||||
Task<AuthResponse> LoginWithMicrosoftAsync(string authorizationCode);
|
Task<AuthResult> LoginWithMicrosoftAsync(string authorizationCode);
|
||||||
Task<AuthResponse> DevLoginAsync(string email, string? displayName, Domain.Enums.UserRole role);
|
Task<AuthResult> DevLoginAsync(string email, string? displayName, Domain.Enums.UserRole role);
|
||||||
Task<AuthResponse> RefreshTokenAsync(string refreshToken);
|
Task<AuthResult> RefreshTokenAsync(string refreshToken);
|
||||||
Task RevokeRefreshTokenAsync(string refreshToken);
|
Task RevokeRefreshTokenAsync(string refreshToken);
|
||||||
Task<UserDto> GetCurrentUserAsync(int userId);
|
Task<UserDto> GetCurrentUserAsync(int userId);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace UniVerse.Domain.Exceptions;
|
||||||
|
|
||||||
|
public class UnauthorizedException : Exception
|
||||||
|
{
|
||||||
|
public UnauthorizedException() : base() { }
|
||||||
|
public UnauthorizedException(string message) : base(message) { }
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using Microsoft.Identity.Client;
|
||||||
using System.IdentityModel.Tokens.Jwt;
|
using System.IdentityModel.Tokens.Jwt;
|
||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
@@ -29,15 +30,76 @@ public class AuthService : IAuthService
|
|||||||
_gamification = gamification;
|
_gamification = gamification;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<AuthResponse> LoginWithMicrosoftAsync(string authorizationCode)
|
public async Task<AuthResult> LoginWithMicrosoftAsync(string authorizationCode)
|
||||||
{
|
{
|
||||||
// Stub: in production, exchange authorizationCode with Microsoft Entra ID
|
var tenantId = _config["AzureAd:TenantId"];
|
||||||
// For now, create/find a demo user
|
var clientId = _config["AzureAd:ClientId"];
|
||||||
throw new NotImplementedException(
|
var clientSecret = _config["AzureAd:ClientSecret"];
|
||||||
"Microsoft Entra ID integration not yet configured. Use /api/v1/auth/login/dev in Development mode.");
|
|
||||||
|
var app = ConfidentialClientApplicationBuilder.Create(clientId)
|
||||||
|
.WithClientSecret(clientSecret)
|
||||||
|
.WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
|
||||||
|
.WithRedirectUri(_config["AzureAd:RedirectUri"] ?? "http://localhost:5173/auth/callback")
|
||||||
|
.Build();
|
||||||
|
|
||||||
|
AuthenticationResult result;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
result = await app.AcquireTokenByAuthorizationCode(new[] { "User.Read" }, authorizationCode)
|
||||||
|
.ExecuteAsync();
|
||||||
|
}
|
||||||
|
catch (MsalException ex)
|
||||||
|
{
|
||||||
|
throw new UnauthorizedException($"Microsoft authentication failed: {ex.Message}");
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<AuthResponse> DevLoginAsync(string email, string? displayName, UserRole role)
|
// Parse claims directly from the ID token provided by Microsoft
|
||||||
|
var handler = new JwtSecurityTokenHandler();
|
||||||
|
var idToken = handler.ReadJwtToken(result.IdToken);
|
||||||
|
|
||||||
|
var email = idToken.Claims.FirstOrDefault(c => c.Type == "preferred_username" || c.Type == "email" || c.Type == ClaimTypes.Upn)?.Value;
|
||||||
|
var name = idToken.Claims.FirstOrDefault(c => c.Type == "name")?.Value;
|
||||||
|
|
||||||
|
if (string.IsNullOrEmpty(email))
|
||||||
|
throw new UnauthorizedException("Email not found in Microsoft token claims.");
|
||||||
|
|
||||||
|
// Automatically provision user
|
||||||
|
var user = await _db.Users.FirstOrDefaultAsync(u => u.Email == email);
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
user = new User
|
||||||
|
{
|
||||||
|
Email = email,
|
||||||
|
DisplayName = name ?? email.Split('@')[0],
|
||||||
|
Role = UserRole.Student, // Default role
|
||||||
|
IsActive = true
|
||||||
|
};
|
||||||
|
_db.Users.Add(user);
|
||||||
|
await _db.SaveChangesAsync();
|
||||||
|
|
||||||
|
// Create corresponding profile
|
||||||
|
_db.StudentProfiles.Add(new StudentProfile { UserId = user.Id });
|
||||||
|
await _db.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
else if (!user.IsActive)
|
||||||
|
{
|
||||||
|
throw new ForbiddenException("Account is deactivated.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var accessToken = GenerateAccessToken(user);
|
||||||
|
var refreshToken = await GenerateRefreshTokenAsync(user.Id);
|
||||||
|
|
||||||
|
return new AuthResult(
|
||||||
|
new AuthResponse(
|
||||||
|
accessToken,
|
||||||
|
DateTime.UtcNow.AddMinutes(GetAccessTokenExpiration()),
|
||||||
|
user.ToAuthDto()
|
||||||
|
),
|
||||||
|
refreshToken
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<AuthResult> DevLoginAsync(string email, string? displayName, UserRole role)
|
||||||
{
|
{
|
||||||
var user = await _db.Users.FirstOrDefaultAsync(u => u.Email == email);
|
var user = await _db.Users.FirstOrDefaultAsync(u => u.Email == email);
|
||||||
|
|
||||||
@@ -72,14 +134,17 @@ public class AuthService : IAuthService
|
|||||||
var accessToken = GenerateAccessToken(user);
|
var accessToken = GenerateAccessToken(user);
|
||||||
var refreshToken = await GenerateRefreshTokenAsync(user.Id);
|
var refreshToken = await GenerateRefreshTokenAsync(user.Id);
|
||||||
|
|
||||||
return new AuthResponse(
|
return new AuthResult(
|
||||||
|
new AuthResponse(
|
||||||
accessToken,
|
accessToken,
|
||||||
DateTime.UtcNow.AddMinutes(GetAccessTokenExpiration()),
|
DateTime.UtcNow.AddMinutes(GetAccessTokenExpiration()),
|
||||||
user.ToAuthDto()
|
user.ToAuthDto()
|
||||||
|
),
|
||||||
|
refreshToken
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<AuthResponse> RefreshTokenAsync(string refreshToken)
|
public async Task<AuthResult> RefreshTokenAsync(string refreshToken)
|
||||||
{
|
{
|
||||||
var token = await _db.RefreshTokens
|
var token = await _db.RefreshTokens
|
||||||
.Include(rt => rt.User)
|
.Include(rt => rt.User)
|
||||||
@@ -97,10 +162,13 @@ public class AuthService : IAuthService
|
|||||||
|
|
||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
|
|
||||||
return new AuthResponse(
|
return new AuthResult(
|
||||||
|
new AuthResponse(
|
||||||
accessToken,
|
accessToken,
|
||||||
DateTime.UtcNow.AddMinutes(GetAccessTokenExpiration()),
|
DateTime.UtcNow.AddMinutes(GetAccessTokenExpiration()),
|
||||||
token.User.ToAuthDto()
|
token.User.ToAuthDto()
|
||||||
|
),
|
||||||
|
newRefreshToken
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,8 +8,10 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Identity.Client" Version="4.84.0" />
|
||||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.0" />
|
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.0" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.0" />
|
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.0" />
|
||||||
|
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.18.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
Reference in New Issue
Block a user