| | | 1 | | using ArturRios.Util.WebApi.Security.Configuration; |
| | | 2 | | using ArturRios.Util.WebApi.Security.Interfaces; |
| | | 3 | | using ArturRios.Util.WebApi.Security.Records; |
| | | 4 | | using Microsoft.AspNetCore.Http; |
| | | 5 | | using Microsoft.Extensions.DependencyInjection; |
| | | 6 | | |
| | | 7 | | namespace ArturRios.Util.WebApi.Security.Authentication; |
| | | 8 | | |
| | | 9 | | /// <summary>Validates a Google ID token via <see cref="IGoogleTokenVerifier"/> and resolves the app user by the token's |
| | | 10 | | /// <param name="verifier">Verifies the Google ID token against the configured client IDs.</param> |
| | | 11 | | /// <param name="options">Supplies the accepted Google client IDs (audiences).</param> |
| | 6 | 12 | | public class GoogleTokenValidator(IGoogleTokenVerifier verifier, AuthenticationOptions options) : ITokenValidator |
| | | 13 | | { |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public async Task<TokenValidationResult> ValidateAsync(string token, HttpContext context) |
| | 5 | 16 | | { |
| | 5 | 17 | | var payload = await verifier.VerifyAsync(token, options.GoogleClientIds); |
| | | 18 | | |
| | 5 | 19 | | if (payload is null) |
| | 1 | 20 | | { |
| | 1 | 21 | | return new TokenValidationResult(null, "Invalid Google token"); |
| | | 22 | | } |
| | | 23 | | |
| | 4 | 24 | | if (string.IsNullOrWhiteSpace(payload.Email)) |
| | 0 | 25 | | { |
| | 0 | 26 | | return new TokenValidationResult(null, "Google token has no email"); |
| | | 27 | | } |
| | | 28 | | |
| | 4 | 29 | | if (!payload.EmailVerified) |
| | 1 | 30 | | { |
| | 1 | 31 | | return new TokenValidationResult(null, "Google email not verified"); |
| | | 32 | | } |
| | | 33 | | |
| | 3 | 34 | | var provider = context.RequestServices.GetRequiredService<IAuthenticationProvider>(); |
| | 3 | 35 | | var user = provider.GetAuthenticatedUserByEmail(payload.Email); |
| | | 36 | | |
| | 3 | 37 | | return new TokenValidationResult(user, user is null ? "User not found" : null); |
| | 5 | 38 | | } |
| | | 39 | | } |