Created
November 18, 2025 23:03
-
-
Save felipebastosweb/f2bb428c4f166d17dbdb94344c35d1bc to your computer and use it in GitHub Desktop.
Código de exemplo que registra um usuário na API, faz login e acessa endpoints restritos
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ... Seção HTML/Razor Markup Omitida ... | |
| @code { | |
| // Modelo de credenciais (usado para Login/Registro) | |
| private SeuProjeto.Controllers.AuthController.CredenciaisModel model = new(); | |
| private List<SeuProjeto.Controllers.GamesController.Game> _games = new(); | |
| private string? _authMessage; // Mensagem de feedback de autenticação | |
| private bool _authSuccess; | |
| private bool _isLoading; | |
| private string? _fetchMessage; // Mensagem de feedback da API protegida | |
| // Armazena o Token JWT recebido no login | |
| private string? _jwtToken; | |
| // Classe auxiliar para deserializar a resposta do Token do AuthController | |
| public class TokenResponse | |
| { | |
| public string Message { get; set; } = string.Empty; | |
| public string Token { get; set; } = string.Empty; | |
| public int ExpiresInMinutes { get; set; } | |
| } | |
| /// <summary> | |
| /// Processa a resposta do servidor após tentar Login ou Registro. | |
| /// </summary> | |
| private async Task ProcessAuthResponse(HttpResponseMessage response) | |
| { | |
| if (response.IsSuccessStatusCode) | |
| { | |
| var tokenResponse = await response.Content.ReadFromJsonAsync<TokenResponse>(); | |
| if (tokenResponse?.Token != null) | |
| { | |
| _jwtToken = tokenResponse.Token; // Armazena o Token | |
| _authMessage = $"Login/Registro bem-sucedido. Token JWT recebido, válido por {tokenResponse.ExpiresInMinutes} minutos."; | |
| _authSuccess = true; | |
| } | |
| else | |
| { | |
| _authMessage = "Sucesso, mas o token não foi recebido."; | |
| _authSuccess = false; | |
| } | |
| } | |
| else | |
| { | |
| // Tenta ler a mensagem de erro do body para feedback ao usuário | |
| var errorContent = await response.Content.ReadAsStringAsync(); | |
| try | |
| { | |
| // Tenta deserializar JSON para obter a mensagem de erro detalhada | |
| using var doc = JsonDocument.Parse(errorContent); | |
| var message = doc.RootElement.TryGetProperty("Message", out var msgElement) ? msgElement.GetString() : response.ReasonPhrase; | |
| _authMessage = $"Falha na autenticação: {message}"; | |
| } | |
| catch (JsonException) | |
| { | |
| _authMessage = $"Falha na autenticação: {response.ReasonPhrase} (Detalhes: {errorContent})"; | |
| } | |
| _authSuccess = false; | |
| } | |
| } | |
| /// <summary> | |
| /// Lida com a requisição de registro de usuário. | |
| /// </summary> | |
| private async Task HandleRegister() | |
| { | |
| _isLoading = true; | |
| _authMessage = null; | |
| _fetchMessage = null; | |
| _games.Clear(); | |
| _jwtToken = null; // Limpa token anterior | |
| try | |
| { | |
| var response = await HttpClient.PostAsJsonAsync("/api/auth/register", model); | |
| await ProcessAuthResponse(response); | |
| } | |
| catch (Exception ex) | |
| { | |
| _authMessage = $"Ocorreu um erro: {ex.Message}"; | |
| _authSuccess = false; | |
| } | |
| finally | |
| { | |
| _isLoading = false; | |
| } | |
| } | |
| /// <summary> | |
| /// Lida com a requisição de login e armazena o token JWT. | |
| /// </summary> | |
| private async Task HandleLogin() | |
| { | |
| _isLoading = true; | |
| _authMessage = null; | |
| _fetchMessage = null; | |
| _games.Clear(); | |
| _jwtToken = null; // Limpa token anterior | |
| try | |
| { | |
| // Envia credenciais e recebe o Token JWT | |
| var response = await HttpClient.PostAsJsonAsync("/api/auth/login", model); | |
| await ProcessAuthResponse(response); | |
| } | |
| catch (Exception ex) | |
| { | |
| _authMessage = $"Ocorreu um erro: {ex.Message}"; | |
| _authSuccess = false; | |
| } | |
| finally | |
| { | |
| _isLoading = false; | |
| } | |
| } | |
| /// <summary> | |
| /// Simula o Logout no fluxo JWT (apenas descarta o token localmente). | |
| /// </summary> | |
| private void HandleLogout() | |
| { | |
| _jwtToken = null; | |
| _games.Clear(); | |
| _fetchMessage = null; | |
| _authMessage = "Token JWT descartado. Você não pode mais acessar a API de jogos."; | |
| _authSuccess = false; | |
| StateHasChanged(); | |
| } | |
| /// <summary> | |
| /// Faz a chamada para a API protegida, anexando o token JWT. | |
| /// </summary> | |
| private async Task FetchGames() | |
| { | |
| _isLoading = true; | |
| _fetchMessage = null; | |
| _games.Clear(); | |
| // ** CENÁRIO 1: USUÁRIO SEM TOKEN ** | |
| if (string.IsNullOrEmpty(_jwtToken)) | |
| { | |
| _fetchMessage = "Não é possível consultar: Não há Token JWT armazenado. Por favor, faça o login."; | |
| _isLoading = false; | |
| return; | |
| } | |
| try | |
| { | |
| // ** CENÁRIO 2: USUÁRIO COM TOKEN - ANEXA O TOKEN ** | |
| // Prepara a requisição para adicionar o cabeçalho Authorization | |
| var request = new HttpRequestMessage(HttpMethod.Get, "/api/games"); | |
| // CRUCIAL: Adiciona o cabeçalho "Bearer <Token>" | |
| request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _jwtToken); | |
| var response = await HttpClient.SendAsync(request); | |
| if (response.IsSuccessStatusCode) | |
| { | |
| _games = (await response.Content.ReadFromJsonAsync<List<SeuProjeto.Controllers.GamesController.Game>>()) ?? new List<SeuProjeto.Controllers.GamesController.Game>(); | |
| _fetchMessage = $"Consulta bem-sucedida! {(_games.Any() ? "" : "Nenhum jogo encontrado.")}"; | |
| } | |
| else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized || response.StatusCode == System.Net.HttpStatusCode.Forbidden) | |
| { | |
| // Se o token expirou ou é inválido, o servidor retorna 401 | |
| _fetchMessage = "Não Autorizado! O Token JWT expirou ou é inválido. Por favor, faça o login novamente."; | |
| _jwtToken = null; // Limpa o token inválido para forçar um novo login | |
| } | |
| else | |
| { | |
| _fetchMessage = $"Erro na consulta: {response.StatusCode} - {response.ReasonPhrase}"; | |
| } | |
| } | |
| catch (Exception ex) | |
| { | |
| _fetchMessage = $"Ocorreu um erro na conexão: {ex.Message}"; | |
| } | |
| finally | |
| { | |
| _isLoading = false; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment