feat: подключил ms sso
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
using Microsoft.Identity.Client;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Security.Cryptography;
|
||||
@@ -29,15 +30,76 @@ public class AuthService : IAuthService
|
||||
_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
|
||||
// For now, create/find a demo user
|
||||
throw new NotImplementedException(
|
||||
"Microsoft Entra ID integration not yet configured. Use /api/v1/auth/login/dev in Development mode.");
|
||||
var tenantId = _config["AzureAd:TenantId"];
|
||||
var clientId = _config["AzureAd:ClientId"];
|
||||
var clientSecret = _config["AzureAd:ClientSecret"];
|
||||
|
||||
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}");
|
||||
}
|
||||
|
||||
// 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<AuthResponse> DevLoginAsync(string email, string? displayName, UserRole role)
|
||||
public async Task<AuthResult> DevLoginAsync(string email, string? displayName, UserRole role)
|
||||
{
|
||||
var user = await _db.Users.FirstOrDefaultAsync(u => u.Email == email);
|
||||
|
||||
@@ -72,14 +134,17 @@ public class AuthService : IAuthService
|
||||
var accessToken = GenerateAccessToken(user);
|
||||
var refreshToken = await GenerateRefreshTokenAsync(user.Id);
|
||||
|
||||
return new AuthResponse(
|
||||
accessToken,
|
||||
DateTime.UtcNow.AddMinutes(GetAccessTokenExpiration()),
|
||||
user.ToAuthDto()
|
||||
return new AuthResult(
|
||||
new AuthResponse(
|
||||
accessToken,
|
||||
DateTime.UtcNow.AddMinutes(GetAccessTokenExpiration()),
|
||||
user.ToAuthDto()
|
||||
),
|
||||
refreshToken
|
||||
);
|
||||
}
|
||||
|
||||
public async Task<AuthResponse> RefreshTokenAsync(string refreshToken)
|
||||
public async Task<AuthResult> RefreshTokenAsync(string refreshToken)
|
||||
{
|
||||
var token = await _db.RefreshTokens
|
||||
.Include(rt => rt.User)
|
||||
@@ -97,10 +162,13 @@ public class AuthService : IAuthService
|
||||
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
return new AuthResponse(
|
||||
accessToken,
|
||||
DateTime.UtcNow.AddMinutes(GetAccessTokenExpiration()),
|
||||
token.User.ToAuthDto()
|
||||
return new AuthResult(
|
||||
new AuthResponse(
|
||||
accessToken,
|
||||
DateTime.UtcNow.AddMinutes(GetAccessTokenExpiration()),
|
||||
token.User.ToAuthDto()
|
||||
),
|
||||
newRefreshToken
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,8 +8,10 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Identity.Client" Version="4.84.0" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" 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>
|
||||
|
||||
Reference in New Issue
Block a user