ng5plus-auth
Angular 5+ authentication service. This service is used with Angular router.
Installation
$ npm install --save ng5plus-auth
Dependencies
- angular router @angular/router
- ng5plus-cookies (npm i ng5plus-cookies)
Integration
1. app.module.ts
;;; const api_base_url = 'http://localhost:4444/api'; const auth_urls = afterGoodLogin: '/{loggedUserRole}' // {loggedUserRole} -> 'admin' | 'customer' afterBadLogin: '/login' afterLogout: '/login'; const cookie_options = // domain: 'localhost', path: '/' expires: 3 // expire in 3 days // expires: new Date('2018-10-31T03:24:00'), secure: false httpOnly: false sameSite: 'strict'; @
Notice: {loggedUserRole} is like variable which is replaced with user's role: admin, customer, ... User's role have to be returned by API.
2. app-routes.module.ts
// modules;; // components;;;;; // services; // routesconst routes: Routes = path: '' component: HomeComponent path: 'login' component: LoginComponent canActivate: AutologinService path: 'admin' component: AdminComponent canActivate: IsLoggedService HasRoleService path: 'customer' component: CustomerComponent canActivate: IsLoggedService HasRoleService path: '404' component: NotfoundComponent path: '**' redirectTo: '/404' ; @ {}
Methods
login(creds: Credentials): Observable
Login with const creds = {username: 'xxxx', password: 'yyyy'} and redirect to URL defined by auth_urls.afterGoodLogin.
Required 'creds' properties are:
interface Credentials username: string; password: string;
logout(): void
Logout and re.
getLoggedUserInfo(): LoggedUser
Get logged user info. This object is returned by API and stored into cookie auth_loggedUser.
Required user object properties are:
interface LoggedUser first_name: string; last_name: string; address?: string; city?: string; country?: string; phone?: string; email: string; website?: string; misc?: any; username: string; password?: string; role: string; is_active?: boolean; jwt_token?: string;
so API response should return those fields.
getJWTtoken(): string
Take JWT token from 'auth_jwtToken' cookie. This token is fetched from API and stored in 'auth_jwtToken' cookie.
API response
In order to work properly this service requires following JSON response or simmilar:
Method Implementation
login({username: , password: })
/pages/login/login.html
Username Password Login {{err.message}}
/pages/login/login.ts
;;; @ implements OnInit loginFG: FormGroup; err: Error; { } { thisloginFG = thisfb; } { const creds = thisloginFGvalue; // {username: , password: } thisauthService ; }
logout()
/pages/admin/admin.html
Logout
/pages/admin/admin.ts
;; @ implements OnInit loggedUser: any; { thisloggedUser = authService; } { } { console; thisauthService; }
Protections
Route Gurads
To protect angular routes from unauthorized access this service uses canActivate route guards:
- IsLoggedService check if user is logged with valid username:password.
- HasRoleService check if user has appropriate role, e.g. role must me contained in URL string, for example: /admin/dashboard is valid for 'admin' role but /customer/dashboard is not valid for 'admin' role. This guard must be applied after IsLoggedService guard.
- AutologinService check if user is already logged. If yes then automatically redirect to URL defined by auth_urls.afterGoodLogin. This guard should be applied only on login page e.g. /login angular route.
API HTTP Request protections
To protect each API request use JWT Token from 'auth_jwtToken' cookie and use it in HTTP header 'Authorization: JWT ' as HTTP interceptor for each API request.
Example
This npm package is integrated in ng5plus-startup so it is full integration example and shows how to use it regularly.
Licence
Created by Saša Mikodanić under MIT licence.