| | | 1 | | using ArturRios.Util.WebApi.Security.Interfaces; |
| | | 2 | | using ArturRios.Util.WebApi.Security.Records; |
| | | 3 | | using Google.Apis.Auth; |
| | | 4 | | |
| | | 5 | | namespace ArturRios.Util.WebApi.Security.Authentication; |
| | | 6 | | |
| | | 7 | | /// <summary>Default <see cref="IGoogleTokenVerifier"/> backed by <see cref="GoogleJsonWebSignature"/>, which fetches an |
| | | 8 | | public class GoogleTokenVerifier : IGoogleTokenVerifier |
| | | 9 | | { |
| | | 10 | | /// <inheritdoc /> |
| | | 11 | | public async Task<GoogleTokenPayload?> VerifyAsync(string token, IEnumerable<string> audiences) |
| | | 12 | | { |
| | 7 | 13 | | if (string.IsNullOrWhiteSpace(token)) |
| | | 14 | | { |
| | 2 | 15 | | return null; |
| | | 16 | | } |
| | | 17 | | |
| | | 18 | | try |
| | | 19 | | { |
| | 5 | 20 | | var settings = new GoogleJsonWebSignature.ValidationSettings { Audience = audiences }; |
| | 5 | 21 | | var payload = await GoogleJsonWebSignature.ValidateAsync(token, settings); |
| | | 22 | | |
| | 0 | 23 | | return new GoogleTokenPayload(payload.Email ?? string.Empty, payload.Subject ?? string.Empty, payload.EmailV |
| | | 24 | | } |
| | | 25 | | // A token that is not a well-formed JWS at all - bad base64url, a segment that is not JSON - makes |
| | | 26 | | // GoogleJsonWebSignature throw the decoder's own exception instead of InvalidJwtException. Any such |
| | | 27 | | // token is just not a valid Google token, so it is a 401, not a 500. Failures fetching Google's keys |
| | | 28 | | // (HttpRequestException) still propagate: those are the server's problem, not the caller's. |
| | 5 | 29 | | catch (Exception exception) when (exception is InvalidJwtException or FormatException or ArgumentException |
| | 5 | 30 | | or Newtonsoft.Json.JsonException) |
| | | 31 | | { |
| | 5 | 32 | | return null; |
| | | 33 | | } |
| | 7 | 34 | | } |
| | | 35 | | } |