Authentication
We follow the steps in Angular 1.x sample. I will create some facilities.- A Signin and Signup components.
- A
AuthService
to wrap HTTP authentiction service. - A
AppShowAuthed
directive to show or hide UI element against the authentiction status.
AuthService
.AuthService
In order to handle signin and signup request, create a service namedAuthService
in src/app/core folder to process it.@Injectable()
export class AuthService {
private currentUser$: BehaviorSubject<User> = new BehaviorSubject<User>(null);
private authenticated$: ReplaySubject<boolean> = new ReplaySubject<boolean>(1);
private desiredUrl: string = null;
constructor(
private api: ApiService,
private jwt: JWT,
private router: Router) {
}
attempAuth(type: string, credentials: any) {
const path = (type === 'signin') ? '/login' : '/signup';
const url = '/auth' + path;
this.api.post(url, credentials)
.map(res => res.json())
.subscribe(res => {
this.jwt.save(res.id_token);
// set Authorization header
this.setJwtHeader(res.id_token);
this.setState(res.user);
if (this.desiredUrl && !this.desiredUrl.startsWith('/signin')) {
const _targetUrl = this.desiredUrl;
this.desiredUrl = null;
this.router.navigateByUrl(_targetUrl);
} else {
this.router.navigate(['']);
}
});
}
logout() {
// reset the initial values
this.setState(null);
//this.desiredUrl = null;
this.jwt.destroy();
this.clearJwtHeader();
this.desiredUrl = null;
this.router.navigate(['']);
}
currentUser(): Observable<User> {
return this.currentUser$.distinctUntilChanged();
}
isAuthenticated(): Observable<boolean> {
return this.authenticated$.asObservable();
}
getDesiredUrl() {
return this.desiredUrl;
}
setDesiredUrl(url: string) {
this.desiredUrl = url;
}
private setState(state: User) {
if (state) {
this.currentUser$.next(state);
this.authenticated$.next(true);
} else {
this.currentUser$.next(null);
this.authenticated$.next(false);
}
}
private setJwtHeader(jwt: string) {
this.api.setHeaders({ Authorization: `Bearer ${jwt}` });
}
private clearJwtHeader() {
this.api.deleteHeader('Authorization');
}
}
JWT
utility and a Router
. attempAuth
method is use for handling signin and signup requests. It accpets two parameters, type
and credentials
data.If signin or signup is handled sucessfully, save the token value into localStorage by JWT service and set Http Header
Authenticiaton
in ApiService, then navigate to the desired URL.The
JWT
is just a simple class to fetch jwt token from localStorage and save jwt into localStorage.const JWT_KEY: string = 'id_token';
@Injectable()
export class JWT {
constructor(/*@Inject(APP_CONFIG) config: AppConfig*/) {
//this.jwtKey = config.jwtKey;
}
save(token) {
window.localStorage[JWT_KEY] = token;
}
get() {
return window.localStorage[JWT_KEY];
}
destroy() {
window.localStorage.removeItem(JWT_KEY);
}
}
AuthService
and JWT
in core.module.ts.@NgModule({
...
providers: [
...
AuthService,
JWT,
...
]
})
export class CoreModule {
}
Create Signin and Signup UI components
Generate signin and signup components viang g component
command.Execute the following commands in the project root folder.
ng g component signin
ng g module signin
ng g component signup
ng g module signup
Signin
The content ofSigninComponent
.import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { AuthService } from '../core/auth.service';
@Component({
selector: 'app-signin',
templateUrl: './signin.component.html',
styleUrls: ['./signin.component.css']
})
export class SigninComponent implements OnInit, OnDestroy {
data = {
username: '',
password: ''
};
sub: Subscription;
constructor(private authServcie: AuthService) { }
ngOnInit() { }
submit() {
console.log('signin with credentials:' + this.data);
this
.authServcie
.attempAuth('signin', this.data);
}
ngOnDestroy() {
//if (this.sub) { this.sub.unsubscribe(); }
}
}
AuthService
attempAuth method and set type parameter value to signin
.Lets have a look at the template file.
<div class="row">
<div class="offset-md-3 col-md-6">
<div class="card">
<div class="card-header">
<h1>{{'signin' }}</h1>
</div>
<div class="card-block">
<form #f="ngForm" id="form" name="form" class="form" (ngSubmit)="submit()" novalidate>
<div class="form-group" [class.has-danger]="username.invalid && !username.pristine">
<label class="form-control-label" for="username">{{'username'}}</label>
<input class="form-control" id="username" name="username" #username="ngModel" [(ngModel)]="data.username" required/>
<div class="form-control-feedback" *ngIf="username.invalid && !username.pristine">
<p *ngIf="username.errors.required">Username is required</p>
</div>
</div>
<div class="form-group" [class.has-danger]="password.invalid && !password.pristine">
<label class="form-control-label" for="password">{{'password'}}</label>
<input class="form-control" type="password" name="password" id="password" #password="ngModel" [(ngModel)]="data.password" required/>
<div class="form-control-feedback" *ngIf="password.invalid && !password.pristine">
<p ng-message="password.errors.required">Password is required</p>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success btn-lg" [disabled]="f.invalid || f.pending"> {{'signin'}}</button>
</div>
</form>
</div>
<div class="card-footer">
Not registered, <a [routerLink]="['', 'signup']">{{'signup'}}</a>
</div>
</div>
</div>
</div>
username
and password
are required fields, if the input value is invalid, the error messages will be displayed.Declare
SigninComponent
in signin.module.ts.import { NgModule } from '@angular/core';
import { SharedModule } from '../shared/shared.module';
import { SigninRoutingModule } from './signin-routing.module';
import { SigninComponent } from './signin.component';
@NgModule({
imports: [
SharedModule,
SigninRoutingModule
],
declarations: [SigninComponent]
})
export class SigninModule { }
signin-routing.module.ts
.import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SigninComponent } from './signin.component';
const routes: Routes = [
{ path: '', component: SigninComponent }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
providers: []
})
export class SigninRoutingModule { }
AppRoutingModule
.const routes: Routes = [
...
{ path: 'signin', loadChildren: 'app/signin/signin.module#SigninModule' },
...
];
Signup
The content ofSignupComponent
.import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { AuthService } from '../core/auth.service';
@Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit {
signupForm: FormGroup;
firstName: FormControl;
lastName: FormControl;
email: FormControl;
username: FormControl;
password: FormControl;
passwordConfirm: FormControl;
passwordGroup: FormGroup;
constructor(private authService: AuthService, private fb: FormBuilder) {
this.firstName = new FormControl('', [Validators.required]);
this.lastName = new FormControl('', [Validators.required]);
this.email = new FormControl('', [Validators.required, this.validateEmail]);
this.username = new FormControl('', [Validators.required, Validators.minLength(6), Validators.maxLength(20)]);
this.password = new FormControl('', [Validators.required, Validators.minLength(6), Validators.maxLength(20)]);
this.passwordConfirm = new FormControl('', [Validators.required, Validators.minLength(6), Validators.maxLength(20)]);
this.passwordGroup = fb.group(
{
password: this.password,
passwordConfirm: this.passwordConfirm
},
{ validator: this.passwordMatchValidator }
);
this.signupForm = fb.group({
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
username: this.username,
passwordGroup: this.passwordGroup
});
}
passwordMatchValidator(g: FormGroup) {
return g.get('password').value === g.get('passwordConfirm').value
? null : { 'mismatch': true };
}
validateEmail(c: FormControl) {
let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
return EMAIL_REGEXP.test(c.value) ? null : {
validateEmail: {
valid: false
}
};
}
ngOnInit() {
}
submit() {
console.log('saving signup form data@' + this.signupForm.value);
let value = this.signupForm.value;
let data = {
firstName: value.firstName,
lastName: value.lastName,
username: value.username,
password: value.passwordGroup.password
};
this.authService.attempAuth('signup', data);
}
}
There are serveral built-in validors in
Validators
, such as required, minLength, maxLength etc. Please note we create a custom validation method(
validateEmail
) for email control, it accpets a FormControl as parameter.Another custom validation method is
passwordMatchValidator
, it is designated for a composite components to check if password and passwordConfirm are matched.Let's have a look at the template file, src/app/signup.component.html.
<div class="row">
<div class="offset-md-3 col-md-6">
<div class="card">
<div class="card-header">
<h1>{{ 'signup' }}</h1>
</div>
<div class="card-block">
<form id="form" name="form" class="form" [formGroup]="signupForm" (ngSubmit)="submit()" novalidate>
<div class="row">
<div class="col-md-6">
<div class="form-group" [class.has-danger]="firstName.invalid && !firstName.pristine">
<label class="form-control-label" for="firstName">{{'firstName'}}</label>
<input class="form-control" id="firstName" name="firstName" [formControl]="firstName"/>
<div class="form-control-feedback" *ngIf="firstName.invalid && !firstName.pristine">
<p *ngIf="firstName.errors.required">FirstName is required</p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group" [class.has-danger]="lastName.invalid && !lastName.pristine">
<label class="form-control-label col-md-12" for="lastName">{{'lastName'}}</label>
<input class="form-control" id="lastName" name="lastName" [formControl]="lastName"/>
<div class="form-control-feedback" *ngIf="lastName.invalid && !lastName.pristine">
<p *ngIf="lastName.errors.required">LastName is required</p>
</div>
</div>
</div>
</div>
<div class="form-group" [class.has-danger]="email.invalid && !email.pristine">
<label class="form-control-label" for="email">{{'email'}}</label>
<input class="form-control" id="email" name="email" type="email" [formControl]="email"/>
{{email.errors|json}}
<div class="form-control-feedback" *ngIf="email.invalid && !email.pristine">
<p *ngIf="email.errors.required">email is required</p>
</div>
</div>
<div class="form-group" [class.has-danger]="username.invalid && !username.pristine">
<label class="form-control-label" for="username">{{'username'}}</label>
<input class="form-control" id="username" name="username" type="text" [formControl]="username"/>
<div class="form-control-feedback" *ngIf="username.invalid && !username.pristine">
<p *ngIf="username.errors.required">Username is required</p>
<p *ngIf="username.errors.minlength">Username is too short(at least 6 chars)</p>
<p *ngIf="username.errors.maxlength">Username is too long(at most 20 chars)</p>
</div>
</div>
<div class="row" [formGroup]="passwordGroup">
<div class="col-md-12">
<div class="form-group" [class.has-danger]="password.invalid && !password.pristine">
<label class="form-control-label" for="password">{{'password'}}</label>
<input class="form-control" type="password" name="password" id="password" [formControl]="password" />
<div class="form-control-feedback" *ngIf="password.invalid && !password.pristine">
<p *ngIf="password.errors.required">Password is required.</p>
<p *ngIf="password.errors.minlength||password.errors.maxlength">Password should be consist of 6 to 20 characters.</p>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group" [class.has-danger]="passwordConfirm.invalid && !passwordConfirm.pristine">
<label class="form-control-label" for="passwordConfirm">{{'passwordConfirm'}}</label>
<input class="form-control" type="password" name="passwordConfirm" id="passwordConfirm" [formControl]="passwordConfirm" />
<div class="form-control-feedback" *ngIf="passwordConfirm.invalid && !passwordConfirm.pristine">
<p *ngIf="passwordConfirm.errors.required">passwordConfirm is required.</p>
<p *ngIf="passwordConfirm.errors.minlength||passwordConfirm.errors.maxlength">passwordConfirm should be consist of 6 to 20 characters.</p>
</div>
</div>
</div>
<div class="col-md-12" [class.has-danger]="passwordGroup.invalid">
<div class="form-control-feedback" *ngIf="passwordGroup.invalid">
<p *ngIf="passwordGroup.hasError('mismatch')">Passwords are mismatched.</p>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success btn-lg" [disabled]="signupForm.invalid || signupForm.pending"> {{'SIGN UP'}}</button>
</div>
</form>
</div>
<div class="card-footer">
Already resgistered, <a [routerLink]="['','signin']">{{'signin'}}</a>
</div>
</div>
</div>
</div>
formGroup
and formControl
) to backing component class.Declare SignupComponent in src/app/signup.module.ts.
import { NgModule } from '@angular/core';
import { SharedModule } from '../shared/shared.module';
import { SignupRoutingModule } from './signup-routing.module';
import { SignupComponent } from './signup.component';
@NgModule({
imports: [
SharedModule,
SignupRoutingModule
],
declarations: [SignupComponent]
})
export class SignupModule { }
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SignupComponent } from './signup.component';
const routes: Routes = [
{ path: '', component: SignupComponent }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
providers: []
})
export class SignupRoutingModule { }
const routes: Routes = [
...
{ path: 'signup', loadChildren: 'app/signup/signup.module#SignupModule' },
...
<ul class="navbar-nav my-2 my-lg-0">
<li class="nav-item"><a class="btn btn-outline-success" [routerLink]="['/signin']" >{{'signin'}}</a></li>
<li class="nav-item"><a class="nav-link" [routerLink]="['/signup']" >{{'signup'}}</a>
</li>
</ul>
Email validator
In the SignupComponent, we used a method to validate email field value. We can use a standalone Email validator to implement it and thus validator can be resued in other case.Create a directive in src/app/shared folder.
import { Directive, forwardRef } from '@angular/core';
import { NG_VALIDATORS, FormControl } from '@angular/forms';
function validateEmailFactory(/* emailBlackList: EmailBlackList*/) {
return (c: FormControl) => {
let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
return EMAIL_REGEXP.test(c.value) ? null : {
validateEmail: {
valid: false
}
};
};
}
//http://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html
//http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/
@Directive({
selector: '[validateEmail][ngModel], [validateEmail][formControl], [validateEmail][formControlName]',
providers: [
{ provide: NG_VALIDATORS, useExisting: forwardRef(() => EmailValidatorDirective), multi: true }
]
})
export class EmailValidatorDirective {
validator: Function;
constructor(/*emailBlackList: EmailBlackList*/) {
this.validator = validateEmailFactory();
}
validate(c: FormControl) {
return this.validator(c);
}
}
shared.module.ts
....
import { EmailValidatorDirective } from './email-validator.directive';
@NgModule({
...
declarations: [
...
EmailValidatorDirective
],
exports: [
...
EmailValidatorDirective,
],
})
export class SharedModule { }
SignupModule
we have imported SharedModule
.Apply it in signup template.
<div class="form-group" [class.has-danger]="email.invalid && !email.pristine">
<label class="form-control-label" for="email">{{'email'}}</label>
<input class="form-control" id="email" name="email" type="email" [formControl]="email" validateEmail/>
{{email.errors|json}}
<div class="form-control-feedback" *ngIf="email.invalid && !email.pristine">
<p *ngIf="email.errors.required">email is required</p>
<p *ngIf="email.errors.validateEmail">Email is invalid</p>
</div>
</div>
validateEmail
method;. this.email = new FormControl('', [Validators.required]);
Remember authentication status
We have saved token in localStorage when the user is authenticated, but user return back to the application, the saved token should be reused and avoid to force user to login again.Create a method in
AuthService
to verify the token in localStorage. verifyAuth(): void {
// jwt token is not found in local storage.
if (this.jwt.get()) {
// set jwt header and try to refresh user info.
this.setJwtHeader(this.jwt.get());
this.api.get('/me').subscribe(
res => {
this.currentUser$.next(res);
this.authenticated$.next(true);
},
err => {
this.clearJwtHeader();
this.jwt.destroy();
this.currentUser$.next(null);
this.authenticated$.next(false);
}
);
}
}
AuthService
,
else if it is failed for some reason, such as token is expired, it will
clean token in localStorage and force you to be authenticated for
protected resource.Add the following codes in app.component.ts, it will
verifyAuth
in component lifecycle hook OnInit
when the application is started.export class AppComponent implements OnInit {
title = 'app works!';
constructor(private authService: AuthService) {
}
ngOnInit() {
this.authService.verifyAuth();
}
}
Protect resource when navigation
Some resource like edit post, new post etc, user authentication are required. When use click these links, it try to navigate to the target page, the application should stop it and force user to authenticate in the login page.Angular provides some hooks in routing stage, such as
CanActivate
, CanDeactivate
, CanLoad
, Resolve
etc.Create
CanActivate
service to check if user is authenticated.@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private authService: AuthService) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
console.log('route.log' + route.url);
console.log('state' + state.url);
this
.authService
.isAuthenticated()
.subscribe((auth) => {
if (!auth) {
this.authService.setDesiredUrl(state.url);
console.log('desiredUrl@' + state.url);
this
.router
.navigate(['', 'signin']);
}
});
return true;
}
}
PostsRoutingModule
.const routes: Routes = [
...
{ path: 'new', component: NewPostComponent, canActivate: [AuthGuard] },
{ path: 'edit/:id', component: EditPostComponent, canActivate: [AuthGuard] },
...
];
AuthGuard
, if user is not authenticated, the target URL will be remembered.this.authService.setDesiredUrl(state.url);
attempAuth
method, it will try to navigate to the desiredUrl.if (this.desiredUrl && !this.desiredUrl.startsWith('/signin')) {
const _targetUrl = this.desiredUrl;
this.desiredUrl = null;
this.router.navigateByUrl(_targetUrl);
} else {
this.router.navigate(['']);
}
Protect content in page
Some content fragment is sensitive for security and only show for authencatied user. Create a directive to show or hide content according to user's authencation status.In src/app/shared/ folder, create a directive named
show-authed.directive.ts
.import { Directive, ElementRef, Input, Renderer, HostBinding, Attribute, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { AuthService } from '../core/auth.service';
@Directive({
selector: '[appShowAuthed]'
})
export class ShowAuthedDirective implements OnInit, OnDestroy {
@Input() appShowAuthed: boolean;
sub: Subscription;
constructor(private authService: AuthService, private el: ElementRef, private renderer: Renderer) {
console.log('[appShowAuthed] value:' + this.appShowAuthed);
}
ngOnInit() {
console.log('[appShowAuthed] ngOnInit:');
this.sub = this.authService.currentUser().subscribe((res) => {
if (res) {
if (this.appShowAuthed) {
this.renderer.setElementStyle(this.el.nativeElement, 'display', 'inherit');
} else {
this.renderer.setElementStyle(this.el.nativeElement, 'display', 'none');
}
} else {
if (this.appShowAuthed) {
this.renderer.setElementStyle(this.el.nativeElement, 'display', 'none');
} else {
this.renderer.setElementStyle(this.el.nativeElement, 'display', 'inherit');
}
}
});
}
ngOnDestroy() {
console.log('[appShowAuthed] ngOnDestroy:');
if (this.sub) { this.sub.unsubscribe(); }
}
}
SharedModule
.import { ShowAuthedDirective } from './show-authed.directive';
@NgModule({
declarations: [
...
ShowAuthedDirective],
exports: [
...
ShowAuthedDirective]
}
})
export class SharedModule { }
<ul class="navbar-nav my-2 my-lg-0">
<li class="nav-item" [appShowAuthed]="false"><a class="btn btn-outline-success" [routerLink]="['/signin']" >{{'signin'}}</a></li>
<li class="nav-item" [appShowAuthed]="false"><a class="nav-link" [routerLink]="['/signup']" >{{'signup'}}</a>
</li>
<li class="nav-item" [appShowAuthed]="true"><button type="button" class="btn btn-outline-danger" (click)="logout()">{{'logout'}}</button>
</li>
</ul>
<div [appShowAuthed]="true">
<app-comment-form (saved)="saveComment($event)"></app-comment-form>
</div>
<div class="mx-auto my-2" [appShowAuthed]="false">
<a class="btn btn-lg btn-success" routerLink="/signin">SING IN</a>
</div>
评论