ng-api-auth
v1.0.0
Published
Angular library for authentication with Spring Boot (JWT, refresh tokens, guards, interceptors, ready-to-use components)
Maintainers
Readme
ng-api-auth
Biblioteca Angular completa para autenticação com Spring Boot usando JWT.
✨ Funcionalidades
| Recurso | Descrição |
|---|---|
| AuthService | Login, registro, logout, refresh automático de tokens |
| authInterceptor | Injeta Bearer em todas as requests; renova token em 401 |
| Guards funcionais | authGuard, roleGuard, guestGuard, canMatchAuthGuard |
| LoginComponent | Formulário de login pronto com validação e toggle de senha |
| RegisterComponent | Formulário de cadastro com indicador de força de senha |
| Standalone & NgModule | Suporta as duas abordagens do Angular |
| TypeScript completo | Todos os tipos exportados |
📦 Instalação
npm install ng-api-auth⚡ Início Rápido
Standalone App (Angular 16+)
// app.config.ts
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideSpringAuth, authInterceptor } from 'ng-api-auth';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(withInterceptors([authInterceptor])),
...provideSpringAuth({
apiUrl: 'http://localhost:8080/api',
}),
],
};NgModule App
// app.module.ts
import { SpringAuthModule } from 'ng-api-auth';
@NgModule({
imports: [
SpringAuthModule.forRoot({ apiUrl: 'http://localhost:8080/api' }),
],
})
export class AppModule {}🛣️ Protegendo Rotas
import { authGuard, roleGuard, guestGuard, canMatchAuthGuard } from 'ng-api-auth';
const routes: Routes = [
{ path: 'login', canActivate: [guestGuard], component: LoginPageComponent },
{ path: 'dashboard', canActivate: [authGuard], component: DashboardComponent },
{
path: 'admin',
canActivate: [authGuard, roleGuard],
data: { roles: ['ADMIN'] },
component: AdminComponent,
},
{
path: 'app',
canMatch: [canMatchAuthGuard],
loadChildren: () => import('./features/app.routes'),
},
];- authGuard: redireciona para
/logincomreturnUrlem query params quando o usuário não está autenticado. - roleGuard: exige que o usuário tenha todos os roles indicados em
data.roles(AND). Use junto deauthGuardpara rotas que exigem login e papel específico.
🖼️ Componentes Prontos
<!-- Login -->
<spring-login
title="Portal"
subtitle="Entre com suas credenciais"
[showRegisterLink]="true"
(loginSuccess)="onSuccess($event)"
(loginError)="onError($event)"
/>
<!-- Registro -->
<spring-register
[showName]="true"
redirectAfterRegister="/dashboard"
(registerSuccess)="onSuccess($event)"
/>Inputs do <spring-login>
| Input | Tipo | Padrão | Descrição |
|---|---|---|---|
| title | string | 'Bem-vindo de volta' | Título do card |
| subtitle | string | 'Entre com suas credenciais para continuar' | Subtítulo |
| redirectAfterLogin | string | null | null | Rota após login |
| showRegisterLink | boolean | true | Exibir link de cadastro |
| registerPath | string | '/register' | Rota do cadastro |
Outputs do <spring-login>
| Output | Tipo | Descrição |
|---|---|---|
| loginSuccess | EventEmitter<AuthResponse> | Login bem-sucedido |
| loginError | EventEmitter<unknown> | Erro no login |
| registerClick | EventEmitter<void> | Clique em "criar conta" |
Inputs do <spring-register>
| Input | Tipo | Padrão | Descrição |
|---|---|---|---|
| title | string | 'Criar conta' | Título do card |
| subtitle | string | 'Preencha os dados para se cadastrar' | Subtítulo |
| showName | boolean | true | Exibir campos nome e sobrenome |
| showLoginLink | boolean | true | Exibir link para login |
| loginPath | string | '/login' | Rota do login |
| redirectAfterRegister | string | null | null | Rota após cadastro |
Outputs do <spring-register>
| Output | Tipo | Descrição |
|---|---|---|
| registerSuccess | EventEmitter<unknown> | Cadastro bem-sucedido |
| registerError | EventEmitter<unknown> | Erro no cadastro |
| loginClick | EventEmitter<void> | Clique em "Entrar" |
🔧 AuthService API
import { AuthService } from 'ng-api-auth';
constructor(private auth: AuthService) {}
// Observables
auth.state$ // AuthState completo
auth.isAuthenticated$ // boolean
auth.user$ // AuthUser | null
auth.loading$ // boolean
auth.error$ // string | null
// Métodos
auth.login({ username, password }) // Observable<AuthResponse>
auth.register({ username, email, ... }) // Observable<AuthResponse>
auth.logout() // void (redireciona)
auth.refreshToken() // Observable<string>
auth.fetchProfile() // Observable<AuthUser>
// Helpers
auth.isAuthenticated() // boolean (síncrono)
auth.hasRole('ADMIN') // boolean
auth.hasAnyRole('ADMIN', 'MANAGER') // boolean
auth.getAccessToken() // string | null
auth.getRefreshToken() // string | null
auth.decodeToken(token) // TokenPayload | null
auth.isTokenExpired(token) // boolean⚙️ Configuração Completa
provideSpringAuth({
apiUrl: 'http://localhost:8080/api',
endpoints: {
login: '/auth/login',
register: '/auth/register',
refresh: '/auth/refresh',
logout: '/auth/logout',
me: '/auth/me',
},
storageKeys: {
accessToken: 'access_token',
refreshToken: 'refresh_token',
user: 'auth_user',
},
autoRefresh: true, // renova token silenciosamente ao carregar
logoutRedirect: '/login', // rota após logout
loginSuccessRedirect: '/dashboard', // rota padrão após login
});🌿 Endpoints Spring Boot esperados
| Método | Endpoint | Body | Retorno |
|---|---|---|---|
| POST | /api/auth/login | { username, password } | AuthResponse |
| POST | /api/auth/register | RegisterRequest | AuthResponse |
| POST | /api/auth/refresh | { refreshToken } | AuthResponse |
| POST | /api/auth/logout | { refreshToken } | 204 No Content |
| GET | /api/auth/me | — | AuthUser |
Formato de AuthResponse
{
"accessToken": "eyJhbGciOiJIUzI1NiJ9...",
"refreshToken": "550e8400-e29b-41d4-a716-...",
"tokenType": "Bearer",
"expiresIn": 3600,
"username": "joao.silva",
"email": "[email protected]",
"roles": ["USER", "ADMIN"]
}📁 Estrutura do Projeto
src/
├── lib/
│ ├── models/
│ │ ├── auth.models.ts # Interfaces e tipos
│ │ └── auth.tokens.ts # InjectionToken
│ ├── services/
│ │ └── auth.service.ts # Serviço principal
│ ├── interceptors/
│ │ └── auth.interceptor.ts # Interceptor JWT
│ ├── guards/
│ │ └── auth.guard.ts # Guards funcionais
│ ├── components/
│ │ ├── login/ # LoginComponent
│ │ └── register/ # RegisterComponent
│ └── spring-auth.module.ts # NgModule + provideSpringAuth()
└── public-api.ts # Barrel de exports📜 Licença
MIT — veja LICENSE.
