Login and Register in Angular
An Auth service sends the credentials to the API, keeps the signed-in user in a signal and the token in localStorage, and signs out by forgetting both. Sign-in and register pages show the API's errors, and the header shows who's signed in. Hiding buttons is for convenience; the API is what keeps data safe.
Journeyman · Angular · Updated
After this lesson you can
- Sign in, register and sign out from an Angular service that keeps the user in a signal and the token in localStorage
- Build sign-in and register pages that show the API's errors, and show who's signed in
Key takeaways
- One
Authservice keeps the user in a private signal and the token inlocalStorage, so a reload doesn't sign the user out. tapsaves the API's result as it goes by, and the component that subscribes still gets the result.- Signing out just forgets the user and the token: the API keeps no list of signed-in users.
- Show the API's errors in plain words: a
401at sign-in means the user name and password don't match, and the API's own message is inerror.error. - Hiding a button, such as Delete for users who aren't admins, is for convenience. The API's
[Authorize]is what keeps the data safe.
The categories API from the last lesson has users now. The Angular app needs a way to sign in, and somewhere to keep the token the API sends back.
The Auth service
One service owns everything about the signed-in user, like the Cart service owned the cart. ng generate service auth, then:
import { HttpClient } from '@angular/common/http';
import { computed, inject, Service, signal } from '@angular/core';
import { Observable, tap } from 'rxjs';
export interface Credentials {
userName: string;
password: string;
}
export interface AuthResult {
token: string;
userName: string;
role: string;
}
const storageKey = 'northwind.auth';
@Service()
export class Auth {
private readonly http = inject(HttpClient);
private readonly current = signal<AuthResult | null>(this.load());
readonly user = this.current.asReadonly();
readonly isSignedIn = computed(() => this.current() !== null);
readonly isAdmin = computed(() => this.current()?.role === 'Admin');
get token(): string | null {
return this.current()?.token ?? null;
}
login(credentials: Credentials): Observable<AuthResult> {
return this.http.post<AuthResult>('/api/auth/login', credentials).pipe(tap(result => this.save(result)));
}
register(credentials: Credentials): Observable<AuthResult> {
return this.http.post<AuthResult>('/api/auth/register', credentials).pipe(tap(result => this.save(result)));
}
logout() {
localStorage.removeItem(storageKey);
this.current.set(null);
}
private save(result: AuthResult) {
localStorage.setItem(storageKey, JSON.stringify(result));
this.current.set(result);
}
private load(): AuthResult | null {
const saved = localStorage.getItem(storageKey);
return saved ? JSON.parse(saved) : null;
}
}
currentis a private signal: the user and token from the API, ornullwhen nobody's signed in. Components readuser,isSignedInandisAdmin, and can't change them.tapis an RxJS operator that does something with each value and passes it on unchanged: here, it saves the result as it goes by. The component that subscribes still gets the result.localStoragekeeps the result in the browser, so a reload, or coming back tomorrow, doesn't sign you out.load()reads it back when the service starts.logoutjust forgets the token. The API keeps no list of signed-in users, so there's nothing to tell it.
A word on localStorage: any JavaScript on your page can read it. That's why an app must never show text from users as HTML, which Angular's {{ }} already prevents for you. Many big sites go further, and keep the token in an httpOnly cookie, which JavaScript can't read at all. For your own apps, localStorage is the usual start.
The sign-in page
A page for /login, with a form:
import { Component, inject, signal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { Auth } from './auth';
@Component({
imports: [FormsModule, RouterLink],
selector: 'app-login',
template: `
<h1>Sign in</h1>
<form (ngSubmit)="signIn()" style="max-width: 20rem">
<input class="form-control mb-2" name="userName" placeholder="User name" [(ngModel)]="userName">
<input class="form-control mb-2" name="password" type="password" placeholder="Password" [(ngModel)]="password">
@if (error()) {
<p class="text-danger">{{ error() }}</p>
}
<button class="btn btn-primary" [disabled]="busy()">Sign in</button>
</form>
<p class="mt-3">New here? <a routerLink="/register">Register</a></p>
`,
})
export class Login {
private readonly auth = inject(Auth);
private readonly router = inject(Router);
protected readonly userName = signal('');
protected readonly password = signal('');
protected readonly error = signal('');
protected readonly busy = signal(false);
protected signIn() {
this.error.set('');
this.busy.set(true);
this.auth.login({ userName: this.userName(), password: this.password() }).subscribe({
next: () => this.router.navigateByUrl('/'),
error: (error: HttpErrorResponse) => {
this.error.set(error.status === 401
? "That user name and password don't match."
: `Sorry, signing in failed (${error.status}).`);
this.busy.set(false);
},
});
}
}
(ngSubmit)runssignIn()when the form is submitted, by the button or by Enter in a box. Inside a form, eachngModelbox needs aname.busydisables the button while the request is on its way, so a double click doesn't sign in twice.- A 401 means the user name or password is wrong; anything else is a problem on the way, so the message says so.
- After signing in,
navigateByUrl('/')goes to the home page.
The register page
Registering is the same shape. The API's own message, such as The user name ada is taken., is in error.error, the body of the error response, so the page can show it:
import { Component, inject, signal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { Auth } from './auth';
@Component({
imports: [FormsModule],
selector: 'app-register',
template: `
<h1>Register</h1>
<form (ngSubmit)="register()" style="max-width: 20rem">
<input class="form-control mb-2" name="userName" placeholder="User name" [(ngModel)]="userName">
<input class="form-control mb-2" name="password" type="password" placeholder="Password (8 or more characters)" [(ngModel)]="password">
@if (error()) {
<p class="text-danger">{{ error() }}</p>
}
<button class="btn btn-primary">Register</button>
</form>
`,
})
export class Register {
private readonly auth = inject(Auth);
private readonly router = inject(Router);
protected readonly userName = signal('');
protected readonly password = signal('');
protected readonly error = signal('');
protected register() {
this.auth.register({ userName: this.userName(), password: this.password() }).subscribe({
next: () => this.router.navigateByUrl('/'),
error: (error: HttpErrorResponse) => this.error.set(
error.status === 400 || error.status === 409 ? error.error : `Sorry, registering failed (${error.status}).`),
});
}
}
The API signs a new user straight in, so after registering, Auth holds the user and the token, as after signing in.
Add both pages to the routes: { path: 'login', component: Login, title: 'Sign in' } and { path: 'register', component: Register, title: 'Register' }, before '**'.
Who's signed in
The header shows who's signed in, with a Sign out button, or a Sign in link:
import { Component, inject } from '@angular/core';
import { Router, RouterLink } from '@angular/router';
import { Auth } from './auth';
@Component({
imports: [RouterLink],
selector: 'app-user-menu',
template: `
@if (auth.user(); as user) {
<span class="me-2">Signed in as {{ user.userName }}</span>
<button class="btn btn-outline-secondary btn-sm" (click)="signOut()">Sign out</button>
} @else {
<a class="btn btn-outline-primary btn-sm" routerLink="/login">Sign in</a>
}
`,
})
export class UserMenu {
protected readonly auth = inject(Auth);
private readonly router = inject(Router);
protected signOut() {
this.auth.logout();
this.router.navigateByUrl('/');
}
}
Put <app-user-menu /> in the site header. Because user is a signal, the menu changes the moment someone signs in or out, wherever it is on the page.
Showing only what the user may do
Other pages can ask Auth too. Show the Delete button only to admins:
@if (auth.isAdmin()) {
<button class="btn btn-outline-danger btn-sm" (click)="remove(category)">Delete</button>
}
That's for convenience, not security. Anyone can open the browser's developer tools, change the page, or call the API with Insomnia. What keeps the categories safe is the API's [Authorize(Roles = "Admin")]: the app just doesn't offer buttons that would fail.
Try it
Start the API and the app (with the proxy from HttpClient in Angular), and open http://localhost:4200/register. Register a new user: the header says Signed in as your name. Reload the page: you're still signed in, because the token is in localStorage. (In the browser's developer tools, Application → Local Storage shows it.) Sign out, then sign in with a wrong password, and the page says the user name and password don't match.
The app can sign in, but it doesn't send the token with its requests yet, so adding a category still fails with 401. That's the next lesson.
Do it: keep the signed-in user through a reload
The Auth service keeps the API's answer in localStorage, so a reload doesn't sign the user out. Write its three helpers as plain JavaScript functions.
The values they work with:
result: the API's answer to a sign-in, an object:{ token: 'abc.def.ghi', userName: 'ada', role: 'User' }.storageKey: the name it's kept under inlocalStorage,'northwind.auth'(the starter sets it).
For example:
saveUser({ token: 'abc.def.ghi', userName: 'ada', role: 'User' });
const user = loadUser();
| Step | What happens |
|---|---|
saveUser(...) |
localStorage holds the text {"token":"abc.def.ghi","userName":"ada","role":"User"} under 'northwind.auth' |
loadUser() |
reads that text back, and turns it into an object again |
So loadUser() returns the object { token: 'abc.def.ghi', userName: 'ada', role: 'User' }.
Your job: write three functions.
saveUser(result)storesresultunderstorageKey, as JSON text.loadUser()returns the saved object, ornullwhen nothing is saved.logout()removes the saved user, soloadUser()returnsnullagain.
Practiced live on the lesson page: write the JavaScript right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
One Auth service talks to the API, keeps the user in a signal and the token in localStorage, and forgets both to sign out. Pages show the API's errors in plain words, and the header always says who's signed in, while the API keeps the real rules.