加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Getting started with Angular 2: part 5

发布时间:2020-12-17 09:32:38 所属栏目:安全 来源:网络整理
导读:Authenticiaton 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 aut

Authenticiaton

We follow the steps in Angular 1.x sample. I will create some facilities.

  1. A Signin and Signup components.
  2. A AuthService to wrap HTTP authentiction service.
  3. A AppShowAuthed directive to show or hide UI element against the authentiction status.

Lets start with creating AuthService.

AuthService

In order to handle signin and signup request,create a service named AuthService 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');
  }
}

In the constructor method,we inject the ApiService we had created in the last post,and a 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);
  }

}

Do not forget to register 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 via ng 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 of SigninComponent.

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(); }
  }

}

It is easy to understand,just call 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>

In Signup component,we use template driven form to process form submission.

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 { }

Defind routing rule in 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 { }

Mount signin routing in AppRoutingModule.

const routes: Routes = [
  ...
  { path: 'signin',loadChildren: 'app/signin/signin.module#SigninModule' },...
];

Signup

The content of SignupComponent.

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.minLength(6),Validators.maxLength(20)]);
    this.password = new FormControl('',Validators.maxLength(20)]);
    this.passwordConfirm = new FormControl('',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);
  }

}

Unlikes SigninComponent,we use programatic approach to setup signup form,declare form controls,and set the validators.

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,'signin']">{{'signin'}}</a>
      </div>
    </div>
  </div>
</div>

Like Signin template file,it is simple and stupid,the different we use property binding(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 { }

And define signup routing rules in src/app/signup/signup-routing.module.ts.

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)],providers: []
})
export class SignupRoutingModule { }

And mount it in src/app/app-routing.module.ts.

const routes: Routes = [
	...
	{ path: 'signup',loadChildren: 'app/signup/signup.module#SignupModule' },...

Make sure the links of signin and siginup are added in NavbarComponent.

<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>

If your project is running,you can try signin and signup in browers.

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);
  }

}

Declare it in shared.module.ts.

...
import { EmailValidatorDirective } from './email-validator.directive';


@NgModule({
	...
  declarations: [
	...
    EmailValidatorDirective
  ],exports: [
    ...
    EmailValidatorDirective,],})
export class SharedModule { }

In 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>

Remove the declaration of email control in SignupComponent and 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);
        }
      );
    }
  }

If the token is existed,refresh the user info and store them in 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;
  }
}

Apply it in PostsRoutingModule.

const routes: Routes = [
  ...
  { path: 'new',component: NewPostComponent,canActivate: [AuthGuard] },{ path: 'edit/:id',component: EditPostComponent,...
];

In the AuthGuard,if user is not authenticated,the target URL will be remembered.

this.authService.setDesiredUrl(state.url);

And when user is authenticated sucessfully via 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,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,'none');
        }

      } else {
        if (this.appShowAuthed) {
          this.renderer.setElementStyle(this.el.nativeElement,'none');
        } else {
          this.renderer.setElementStyle(this.el.nativeElement,'inherit');
        }
      }
    });
  }

  ngOnDestroy() {
    console.log('[appShowAuthed] ngOnDestroy:');
    if (this.sub) { this.sub.unsubscribe(); }
  }

}

Declare it in SharedModule.

import { ShowAuthedDirective } from './show-authed.directive';

@NgModule({
  declarations: [
    ...
	ShowAuthedDirective],exports: [
	...
	ShowAuthedDirective]
  }
})
export class SharedModule { }

Now change the navbar,show login and sign up link when user is not authencatied,and show a logout link when user is authencated.

<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>

And the post details page,use a login button instead of the comment form when user is not authencated.

<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>

Now the authentication flow is done.

Source codes

Check out the source codes from Github and play yourself.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读