Last active
November 18, 2025 23:28
-
-
Save felipebastosweb/efd5f3f045e8d5d16c00e05e383b211f to your computer and use it in GitHub Desktop.
Pelo fato do Program habilitar JWT, Identity e CORS automaticamente [Authorize] exige essa autenticação
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
| using Microsoft.AspNetCore.Identity; | |
| using Microsoft.AspNetCore.Mvc; | |
| using Microsoft.Extensions.Configuration; | |
| using Microsoft.IdentityModel.Tokens; | |
| using System.IdentityModel.Tokens.Jwt; | |
| using System.Security.Claims; | |
| using System.Text; | |
| namespace SeuProjeto.Controllers | |
| { | |
| // Define a rota base para este controller como 'api/auth' | |
| [Route("api/[controller]")] | |
| [ApiController] | |
| public class AuthController : ControllerBase | |
| { | |
| private readonly UserManager<IdentityUser> _userManager; | |
| private readonly IConfiguration _configuration; // Injeção de dependência para configuração | |
| public AuthController(UserManager<IdentityUser> userManager, IConfiguration configuration) | |
| { | |
| _userManager = userManager; | |
| _configuration = configuration; | |
| } | |
| // Modelo simplificado para entrada de credenciais | |
| public class CredenciaisModel | |
| { | |
| public string Email { get; set; } = string.Empty; | |
| public string Password { get; set; } = string.Empty; | |
| } | |
| // Método auxiliar para gerar o Token JWT | |
| private string GenerateJwtToken(IdentityUser user) | |
| { | |
| var jwtKey = _configuration["Jwt:Key"] ?? "umaChaveSuperSecretaDePeloMenos32CaracteresParaProducao"; | |
| var jwtIssuer = _configuration["Jwt:Issuer"] ?? "SeuProjeto.API"; | |
| var jwtAudience = _configuration["Jwt:Audience"] ?? "SeuProjeto.Clientes"; | |
| var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)); | |
| var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); | |
| var claims = new[] | |
| { | |
| // Adiciona claims importantes, como o nome de usuário (Sub) e o ID (NameIdentifier) | |
| new Claim(JwtRegisteredClaimNames.Sub, user.UserName ?? user.Email), | |
| new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), | |
| new Claim(ClaimTypes.NameIdentifier, user.Id), | |
| new Claim(ClaimTypes.Name, user.UserName) | |
| }; | |
| var token = new JwtSecurityToken( | |
| issuer: jwtIssuer, | |
| audience: jwtAudience, | |
| claims: claims, | |
| expires: DateTime.Now.AddMinutes(30), // Token expira em 30 minutos | |
| signingCredentials: credentials); | |
| return new JwtSecurityTokenHandler().WriteToken(token); | |
| } | |
| // POST: api/auth/register | |
| [HttpPost("register")] | |
| public async Task<IActionResult> Register([FromBody] CredenciaisModel model) | |
| { | |
| if (string.IsNullOrEmpty(model.Email) || string.IsNullOrEmpty(model.Password)) | |
| { | |
| return BadRequest(new { Message = "Email e Senha são obrigatórios." }); | |
| } | |
| var user = new IdentityUser { UserName = model.Email, Email = model.Email }; | |
| var result = await _userManager.CreateAsync(user, model.Password); | |
| if (result.Succeeded) | |
| { | |
| // Após o registro, não faz login com cookie. Retorna o token para o cliente. | |
| var token = GenerateJwtToken(user); | |
| return Ok(new { Message = "Registro bem-sucedido.", Token = token, ExpiresInMinutes = 30 }); | |
| } | |
| return BadRequest(new { Errors = result.Errors.Select(e => e.Description) }); | |
| } | |
| // POST: api/auth/login | |
| [HttpPost("login")] | |
| public async Task<IActionResult> Login([FromBody] CredenciaisModel model) | |
| { | |
| if (string.IsNullOrEmpty(model.Email) || string.IsNullOrEmpty(model.Password)) | |
| { | |
| return BadRequest(new { Message = "Email e Senha são obrigatórios." }); | |
| } | |
| var user = await _userManager.FindByEmailAsync(model.Email); | |
| if (user != null && await _userManager.CheckPasswordAsync(user, model.Password)) | |
| { | |
| // Credenciais válidas. Gera o Token JWT. | |
| var token = GenerateJwtToken(user); | |
| // Retorna o token e a informação de expiração para o cliente mobile/Blazor. | |
| return Ok(new { Message = "Login bem-sucedido.", Token = token, ExpiresInMinutes = 30 }); | |
| } | |
| // Credenciais inválidas (401 - Unauthorized) | |
| return Unauthorized(new { Message = "Credenciais inválidas." }); | |
| } | |
| // POST: api/auth/logout - Inútil para JWT, pois o cliente apenas descarta o token. | |
| [HttpPost("logout")] | |
| public IActionResult Logout() | |
| { | |
| // Retorna sucesso e instrui o cliente a descartar o token JWT. | |
| return Ok(new { Message = "Sessão encerrada. Descarte o token JWT." }); | |
| } | |
| } | |
| } |
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
| using Microsoft.AspNetCore.Authorization; | |
| using Microsoft.AspNetCore.Mvc; | |
| namespace SeuProjeto.Controllers | |
| { | |
| // Define a rota base para este controller como 'api/games' | |
| [Route("api/[controller]")] | |
| [ApiController] | |
| // O atributo [Authorize] agora força a validação do Token JWT. | |
| // Se o token estiver faltando, for inválido ou expirado, o servidor retorna 401 Unauthorized. | |
| [Authorize] | |
| public class GamesController : ControllerBase | |
| { | |
| // Modelo para a lista de jogos | |
| public class Game | |
| { | |
| public int Id { get; set; } | |
| public string Title { get; set; } = string.Empty; | |
| public string Genre { get; set; } = string.Empty; | |
| } | |
| // GET: api/games | |
| [HttpGet] | |
| public ActionResult<IEnumerable<Game>> GetGames() | |
| { | |
| // O nome do usuário é extraído das Claims (informações) dentro do Token JWT. | |
| // O servidor não precisa ir ao banco de dados para buscar o usuário. | |
| var userName = User.Identity?.Name ?? "Usuário Desconhecido (Sem Claim)"; | |
| return Ok(new List<Game> | |
| { | |
| new Game { Id = 1, Title = $"Jogo 1 (Acessado por {userName})", Genre = "Ação" }, | |
| new Game { Id = 2, Title = "Jogo 2", Genre = "RPG" }, | |
| new Game { Id = 3, Title = "Jogo 3", Genre = "Estratégia" } | |
| }); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment