احراز هویت و اعتبارسنجی کاربران در برنامههای Angular - قسمت سوم - ورود به سیستم
نویسنده: وحید نصیری
تاریخ: ۱۳۹۶/۰۹/۲۷ ۸:۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
>ng g m Dashboard -m app.module --routing >ng g c Dashboard/ProtectedPage
import { DashboardModule } from "./dashboard/dashboard.module";
@NgModule({
imports: [
//...
DashboardModule,
AppRoutingModule
]
})
export class AppModule { } import { ProtectedPageComponent } from "./protected-page/protected-page.component";
const routes: Routes = [
{ path: "protectedPage", component: ProtectedPageComponent }
]; export class LoginComponent implements OnInit {
model: Credentials = { username: "", password: "", rememberMe: false };
error = "";
returnUrl: string; constructor(
private authService: AuthService,
private router: Router,
private route: ActivatedRoute) { }
ngOnInit() {
// reset the login status
this.authService.logout(false);
// get the return url from route parameters
this.returnUrl = this.route.snapshot.queryParams["returnUrl"];
} submitForm(form: NgForm) {
this.error = "";
this.authService.login(this.model)
.subscribe(isLoggedIn => {
if (isLoggedIn) {
if (this.returnUrl) {
this.router.navigate([this.returnUrl]);
} else {
this.router.navigate(["/protectedPage"]);
}
}
},
(error: HttpErrorResponse) => {
console.log("Login error", error);
if (error.status === 401) {
this.error = "Invalid User name or Password. Please try again.";
} else {
this.error = `${error.statusText}: ${error.message}`;
}
});
} <div class="panel panel-default">
<div class="panel-heading">
<h2 class="panel-title">Login</h2>
</div>
<div class="panel-body">
<form #form="ngForm" (submit)="submitForm(form)" novalidate>
<div class="form-group" [class.has-error]="username.invalid && username.touched">
<label for="username">User name</label>
<input id="username" type="text" required name="username" [(ngModel)]="model.username"
#username="ngModel" class="form-control" placeholder="User name">
<div *ngIf="username.invalid && username.touched">
<div class="alert alert-danger" *ngIf="username.errors['required']">
Name is required.
</div>
</div>
</div>
<div class="form-group" [class.has-error]="password.invalid && password.touched">
<label for="password">Password</label>
<input id="password" type="password" required name="password" [(ngModel)]="model.password"
#password="ngModel" class="form-control" placeholder="Password">
<div *ngIf="password.invalid && password.touched">
<div class="alert alert-danger" *ngIf="password.errors['required']">
Password is required.
</div>
</div>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="rememberMe" [(ngModel)]="model.rememberMe"> Remember me
</label>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" [disabled]="form.invalid ">Login</button>
</div>
<div *ngIf="error" class="alert alert-danger " role="alert ">
{{error}}
</div>
</form>
</div>
</div>
export class HeaderComponent implements OnInit, OnDestroy {
title = "Angular.Jwt.Core";
isLoggedIn: boolean;
subscription: Subscription;
displayName: string;
constructor(private authService: AuthService) { } ngOnInit() {
this.subscription = this.authService.authStatus$.subscribe(status => {
this.isLoggedIn = status;
if (status) {
this.displayName = this.authService.getDisplayName();
}
});
} ngOnDestroy() {
// prevent memory leak when component is destroyed
this.subscription.unsubscribe();
} logout() {
this.authService.logout(true);
} <nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" [routerLink]="['/']">{{title}}</a>
</div>
<ul class="nav navbar-nav">
<li class="nav-item" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">
<a class="nav-link" [routerLink]="['/welcome']">Home</a>
</li>
<li *ngIf="!isLoggedIn" class="nav-item" routerLinkActive="active">
<a class="nav-link" queryParamsHandling="merge" [routerLink]="['/login']">Login</a>
</li>
<li *ngIf="isLoggedIn" class="nav-item" routerLinkActive="active">
<a class="nav-link" (click)="logout()">Logoff [{{displayName}}]</a>
</li>
<li *ngIf="isLoggedIn" class="nav-item" routerLinkActive="active">
<a class="nav-link" [routerLink]="['/protectedPage']">Protected Page</a>
</li>
</ul>
</div>
</nav> import { Component, OnInit } from "@angular/core";
import { AuthService } from "../../core/services/auth.service";
@Component({
selector: "app-protected-page",
templateUrl: "./protected-page.component.html",
styleUrls: ["./protected-page.component.css"]
})
export class ProtectedPageComponent implements OnInit {
decodedAccessToken: any = {};
accessTokenExpirationDate: Date = null;
constructor(private authService: AuthService) { }
ngOnInit() {
this.decodedAccessToken = this.authService.getDecodedAccessToken();
this.accessTokenExpirationDate = this.authService.getAccessTokenExpirationDate();
}
} <h1>
Decoded Access Token
</h1>
<div class="alert alert-info">
<label> Access Token Expiration Date:</label> {{accessTokenExpirationDate}}
</div>
<div>
<pre>{{decodedAccessToken | json}}</pre>
</div>