Before we can begin to access authentication state, the Corbado.load()
call has to resolve.
Find more here.
One-time access to Authentication State
If you want to access user state once, you can simply call Corbado.sessionToken
,
Corbado.user
or Corbado.isAuthenticated
to get the current user state.
import {Component, OnInit} from '@angular/core';
import Corbado from '@corbado/web-js';
import {RouterOutlet} from "@angular/router";
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent implements OnInit {
constructor() {
}
async ngOnInit() {
await Corbado.load({
projectId: "pro-0552933888880246188",
darkMode: 'off',
});
}
async someApiCall() {
if (Corbado.isAuthenticated) {
const resp = await fetch('https://acme.com/api', {
headers: {
Authorization: `Bearer ${Corbado.sessionToken}`
}
})
}
}
}
Subscribing to Authentication State
If you want to synchronize user state to your own state, you can subscribe to the authStateChanges
and userChanges
observables.
import {Component, OnDestroy, OnInit} from '@angular/core';
import Corbado from '@corbado/web-js';
import {RouterOutlet} from "@angular/router";
import {Subscription} from "rxjs";
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent implements OnInit, OnDestroy {
userId: string | undefined = undefined
private userSubscription: Subscription | undefined;
constructor() {
}
async ngOnInit() {
await Corbado.load({
projectId: "pro-XXX",
darkMode: 'off',
});
this.userSubscription = Corbado.userChanges.subscribe(next => {
this.userId = next?.sub;
});
}
ngOnDestroy() {
if (this.userSubscription) {
this.userSubscription.unsubscribe();
}
}
}
We can now render the userId
in the template.
Logout
You can log out the user by calling Corbado.logout
.
import {Component, OnInit} from '@angular/core';
import Corbado from '@corbado/web-js';
import {RouterOutlet} from "@angular/router";
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent implements OnInit {
constructor() {
}
async ngOnInit() {
await Corbado.load({
projectId: "pro-XXX",
darkMode: 'off',
});
}
logout() {
void Corbado.logout();
}
}
Now call the logout
function in your template.
<button (click)="logout()">Logout</button>