useAuth (original) (raw)
Create an auth provider
useAuth aims to support many authentication providers. We've designed an abstraction layer that hopefully makes this achievable.
As of v1.0.0 there's built-in support for Netlify Identity and Auth0. Consider this a proof-of-concept that the abstraction layer works :)
You can create a provider to contribute to useAuth
's codebase, or to make it work with your existing authentication infrastructure. It should be possible to make work with traditional cookie/session based authentication. 🤞
If you're fond of your auth service, please contribute. It would mean the world to me ❤️
What is an auth provider
An auth provider is a service that authenticates users. Like Auth0, Netlify Identity, AWS Cognito, Firebase Auth, and others.
useAuth
uses auth wrappers to interact with these services in a uniform way. Each wrapper is a class of this type:
export interface AuthProviderClass {
authorize(): void;
signup(): void;
logout(returnTo?: string): void;
handleLoginCallback(
dispatch: PayloadSender<AnyEventObject>
): Promise<boolean>;
checkSession(): Promise<{
user: Auth0UserProfile;
authResult: Auth0DecodedHash;
}>;
userId(user: AuthUser): string | null;
userRoles(user: AuthUser): string[] | null;
}
To maintain interoperability, useAuth
avoids interacting with services directly. If it can't fit in those methods, open a bug :)
Abstract implementation
You can use this as a starting point for your auth provider wrapper.
export class Auth0 implements AuthProviderClass {
private auth0: Auth0Client.WebAuth;
private dispatch: (eventName: string, eventData?: any) => void;
private customPropertyNamespace?: string;
constructor(params: AuthOptions) {
this.dispatch = params.dispatch;
this.customPropertyNamespace = params.customPropertyNamespace;
this.auth0 = new Auth0Client.WebAuth({
...(params as Auth0Options)
});
}
static addDefaultParams(params: ProviderOptions, callbackDomain: string) {
const vals = params as Auth0Options;
return {
redirectUri: `${callbackDomain}/auth0_callback`,
audience: `https://${vals.domain}/api/v2/`,
responseType: "token id_token",
scope: "openid profile email",
...vals
};
}
public authorize() {
}
public signup() {
}
public logout(returnTo?: string) {
}
public userId(user: Auth0UserProfile): string {
}
public userRoles(user: AuthUser): string[] | null {
}
public async handleLoginCallback(): Promise<boolean> {
}
public async checkSession(): Promise<{
user: Auth0UserProfile;
authResult: Auth0DecodedHash;
}> {
}
}
Examples
You can see the current list of implemented auth providers on GitHub
Use them to guide your implementation :)