Here I am providing only code snippet, required for angular authentication. If you are angular guy then you will understand the code easily and use in your application.
I have a User Model. Below is the code.
1- Creating user model
export class User {
isAuth = false;
userId: string;
email: string;
password: string;
name: string;
address: string;
role: string;
roles = [];
token: string;
contact: string;
createdDate: any;
updatedDate: any;
costructor() { }
}
Environment.ts file code snippet.
export const environment = {
production: false,
apiAddress: 'http://localhost:1300/api',
}
2- Creating AuthService
First we will create a Auth service in Angular. Below is the code for AuthService.
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { UserLogin } from '../public/models/userLogin';
import { Observable } from 'rxjs/Rx';
import { User } from '../models/user';
import { environment as env } from '../../environments/environment';
declare const localStorage: any;
@Injectable()
export class AuthService {
headers: Headers;
user: User;
constructor(private http: Http) {
this.headers = new Headers({ 'content-type': 'application/json' });
this.loadAuthUser();
}
loadAuthUser() {
if (localStorage['authInfo'] !== undefined && localStorage['authInfo'] !== null) {
this.user = JSON.parse(localStorage['authInfo']);
}
}
SignOut() {
localStorage.removeItem('authInfo');
this.user = undefined;
}
setAuthUser(user: User) {
localStorage['authInfo'] = JSON.stringify(user);
this.user = user;
}
ValidateUser(user: UserLogin): Observable<User> {
return this.http.post(env.apiAddress + '/auth', JSON.stringify(user),
{ headers: this.headers }).map((res) => {
return res.json();
}).catch((err) => Observable.throw(err));
}
}
3- Creating LoginComponent code
Then We will call Login function for user authentication and token storage. Below is the code for Login Component.
import { Component, OnInit } from '@angular/core';
import { UserLogin } from '../models/userLogin';
import { AuthService } from '../../services/auth.service';
import { User } from '../../models/user';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styles: []
})
export class LoginComponent implements OnInit {
user: UserLogin;
ref = '';
constructor(private authService: AuthService, private router: Router,
private route: ActivatedRoute) {
this.user = new UserLogin();
}
ngOnInit() {
this.route.queryParams.subscribe((params) => {
this.ref = params.ref;
});
}
Login() {
this.authService.ValidateUser(this.user).subscribe((res) => {
const authObj: User = res;
if (authObj.email !== '') {
authObj.isAuth = true;
this.authService.setAuthUser(authObj);
if (this.ref !== undefined && this.ref !== '') {
this.router.navigate([this.ref]);
}
else {
if (authObj.roles.indexOf('Admin') > -1) {
this.router.navigate(['admin']);
} else {
this.router.navigate(['user']);
}
}
}
});
}
}
4- Creating AppRouting file
Below is the Code of app.routing.ts file.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AdminAuthGuard, UserAuthGuard } from './services/auth.guard';
const routes: Routes = [
{ path: '', loadChildren: 'app/public/public.module#PublicModule' },
{ path: 'user', loadChildren: 'app/user/user.module#UserModule',
canActivate:[UserAuthGuard] },
{ path: 'admin', loadChildren: 'app/admin/admin.module#AdminModule',
canActivate: [AdminAuthGuard] }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule { }
5- Creating Route Guard file
Below is the code of auth.guard.ts file.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AdminAuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) { }
canActivate() {
if (!(this.authService.user != null && this.authService.user.isAuth)) {
this.router.navigate(['login']);
return false;
} else if (this.authService.user.roles.indexOf('Admin') > -1) {
return true;
} else {
this.router.navigate(['unauthorize']);
return false;
}
}
}
@Injectable()
export class UserAuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) { }
canActivate() {
if (!(this.authService.user != null && this.authService.user.isAuth)) {
this.router.navigate(['login']);
return false;
} else if (this.authService.user.roles.indexOf('User') > -1) {
return true;
} else {
this.router.navigate(['unauthorize']);
return false;
}
}
}
Creating Sign-out feature
Below is the code snippet from a component.
...
<ul class="nav navbar-nav pull-right" *ngIf="authService.user!=undefined">
<li style="padding: 15px;">
Welcome : {{authService.user.name}}
</li>
<li>
<a href="javascript:void(0)" (click)="signout()">SignOut</a>
</li>
</ul>
...
...
constructor(public authService: AuthService, private router: Router) { }
signout() {
this.authService.SignOut();
this.router.navigate(['/login']);
}
...
Sending token value in Request header-
1- Using Http-Interceptors
2- Using RequestOptions (below is example code snippet)
@Injectable()
export class ProductService {
private baseUrl = '';
private headers: any;
private options;
constructor(private http: Http, private authService: AuthService) {
this.options = new RequestOptions({
headers: new Headers({
'authorization': this.authService.user.token,
'Content-Type': 'application/json'
})
});
this.baseUrl = env.apiAddress;
}
getAll(): Observable<Product[]> {
return this.http.get(`${this.baseUrl}/product`, this.options)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
add(product: Product): Observable<Response> {
return this.http
.post(`${this.baseUrl}/product`, JSON.stringify(product), this.options)
.catch((error: any) => Observable.throw('Server error'));
}
.......
......
0 comments:
Post a Comment