Last active
November 18, 2025 23:01
-
-
Save felipebastosweb/a928e897590ef6d9f6ee5079897da518 to your computer and use it in GitHub Desktop.
Código necessário para tornar uma aplicação Blazor Server em API Controller com Autenticação com JWT e CORS para mobile
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
| // Autenticação de Usuários com Identity | |
| builder.Services.AddDefaultIdentity<IdentityUser>( | |
| options => options.SignIn.RequireConfirmedAccount = true | |
| ) | |
| .AddEntityFrameworkStores<ApplicationDbContext>(); | |
| // API Controllers | |
| builder.Services.AddControllers(); | |
| // Configuração do JWT | |
| var jwtKey = builder.Configuration["Jwt:Key"] ?? "umaChaveSuperSecretaDePeloMenos32CaracteresParaProducao"; | |
| var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? "SeuProjeto.API"; | |
| var jwtAudience = builder.Configuration["Jwt:Audience"] ?? "SeuProjeto.Clientes"; | |
| // Autenticação com JWT | |
| builder.Services.AddAuthentication( | |
| options => { | |
| options.DefaultScheme = IdentityConstants.ApplicationScheme; | |
| options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; | |
| }) | |
| .AddJwtBearer(options => | |
| { | |
| options.TokenValidationParameters = new TokenValidationParameters | |
| { | |
| ValidateIssuer = true, | |
| ValidateAudience = true, | |
| ValidateLifetime = true, | |
| ValidateIssuerSigningKey = true, | |
| ValidIssuer = jwtIssuer, | |
| ValidAudience = jwtAudience, | |
| IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)) | |
| }; | |
| // Esta configuração é para evitar conflitos de JWT com SignalR/Blazor | |
| options.Events = new JwtBearerEvents | |
| { | |
| OnMessageReceived = context => | |
| { | |
| if (context.HttpContext.Request.Path.StartsWithSegments("/_blazor")) | |
| { | |
| return Task.CompletedTask; | |
| } | |
| return Task.CompletedTask; | |
| } | |
| }; | |
| }); | |
| // CORS para Mobile | |
| builder.Services.AddCors(options => | |
| { | |
| options.AddPolicy(name: "AllowSpecificOrigin", | |
| builder => | |
| { | |
| // Para permitir que o seu cliente mobile ou qualquer frontend acesse. | |
| // ATENÇÃO: Em produção, substitua "*" por domínios específicos (ex: "https://seuapp.com"). | |
| builder.AllowAnyOrigin() // Permite qualquer domínio | |
| .AllowAnyHeader() // Permite qualquer cabeçalho, incluindo Authorization | |
| .AllowAnyMethod(); // Permite GET, POST, etc. | |
| }); | |
| }); | |
| // ... | |
| // Ativa o CORS | |
| app.UseCors("AllowSpecificOrigin"); | |
| // Ativa a Autenticação e Autorização | |
| app.UseAuthentication(); | |
| app.UseAuthorization(); | |
| // Mapeia os Controllers da API já protegidos por JWT e CORS | |
| app.MapControllers(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment