Skip to content
AceneKASDI edited this page Apr 24, 2020 · 1 revision

Welcome to the BlogCreator4Engineer wiki!

Angular CLI

Service creation

            ng g s 'service'

Component creation

            ng generate component 'component'

Adding Auth Guard Angular 9 on our application

Auth Guard

The auth guard is an angular route guard that's used to prevent unauthorized users from accessing restricted routes, it does this by implementing the CanActivate interface which allows the guard to decide if a route can be activated with the canActivate() method. If the method returns true the route is activated (allowed to proceed), otherwise if the method returns false the route is blocked.

  • Steps :

To ckeck if a JWT is expired we have to use an angular component angular-jwt :

    npm install --save @auth0/angular-jwt

To implement the route Guard, we have to create Guard service and override canActivate method :

    ng g guard security/auth

On rooting module we have to activat authGuard on some routes like bellow :

    import { AuthGuardService as AuthGuard } from './security/auth.guard';
    :
    :
    const routes: Routes = [
    :
    { path: 'login', component: LoginComponent, canActivate: [AuthGuard] }

According to related process we will allow or reject access to requested route.

Http interceptors service

Most interceptors transform the outgoing request before passing it to the next interceptor in the chain, by calling next.handle(transformedReq). An interceptor may transform the response event stream as well, by applying additional RxJS operators on the stream returned by next.handle().

In our case we use the interceptors to potentially add headers (Authorizations, content-type...)

    We have to import the HttpClientModule only in your AppModule as imports

and as provider :

    {
            provide: HTTP_INTERCEPTORS,
            useClass: HttpInterceptorService,
            multi: true
    }

Using HashLocationStrategy on production

On production when reload the page we will have the 404 error
because : With client-side SPAs we have two strategies we can 
use to implement client-side routing, one is called the HashLocationStrategy 
and the other is called the PathLocationStrategy which is activated by default.
On PRODUCTION we will see the '#' character on URLs

REDIRECTION to https

For redirecting http trafic to https in production environment, we have to add an .htaccess with to following code inside :

    <IfModule mod_rewrite.c>

        RewriteEngine On
            # -- REDIRECTION to https:
            RewriteCond %{HTTPS} !on
            RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
            # --
    </IfModule>

Set code coverage

    > npm install --save-dev karma karma-coverage codecov