npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

ng-api-auth

v1.0.0

Published

Angular library for authentication with Spring Boot (JWT, refresh tokens, guards, interceptors, ready-to-use components)

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 /login com returnUrl em 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 de authGuard para 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.