first, install crypto in a project using npm.
//cmd=> npm install crypto-js
Include the node_module into your service or to your cryto.ts file
Include this module where you want to use cryptography :
import * as CryptoJS from 'crypto-js';
===================================================================
module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { routingrouting, appRoutingProviders} from '../routing.routing';
import { LoginComponent } from '../Login.component';
import { DashboardComponent } from '../Dashboard.component';
import {Auth} from '../Services/Dashboard/auth.service';
import {AuthGuard} from '../Services/Dashboard/auth.guard';
@NgModule({
declarations: [LoginComponent ],
imports: [BrowserModule,routing],
providers: [appRoutingProviders,Auth,AuthGuard],
bootstrap: [LoginComponent]
})
export class MasterModule { }
====================================================================
routing.ts
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
/*All Router Component import here*/
import { LoginComponent } from '../Components/Dashboard/login.component';
import { HomeComponent } from '../Components/Dashboard/home.component';
import { EventComponent } from '../Components/Dashboard/event.component';
import { AddforumComponent } from '../Components/Dashboard/addforum.component';
import { EmpdashboardComponent } from '../Components/Employee/Empdashboard.component';
import {AuthGuard} from '../Services/Dashboard/auth.guard';
const appRoutes: Routes = [
{ path: '', component: LoginComponent },
{ path: 'dashboard', component: EmpdashboardComponent , canActivate: [AuthGuard] },
// { path: '**', component: PageNotFoundComponent }
];
export const appRoutingProviders: any[] = [];
export const masterrouting: ModuleWithProviders = RouterModule.forRoot(appRoutes);
===================================================================
auth.service
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import * as CryptoJS from 'crypto-js';
@Injectable()
export class Auth {
// Configure Auth0
constructor(private _router:Router) { }
public loginauth(profile:any ) {
debugger;
var token= this.Encryptvalue(profile.EmpId);
var data= this.Encryptobject(profile);
// Set token in localStorage
localStorage.setItem('id_token', token);
localStorage.setItem('profile', data);
this._router.navigateByUrl('/dashboard');
};
public authenticated() {
if(localStorage.getItem('id_token')!=null && localStorage.getItem('id_token')!="")
{
return true;
}
else
{
return false;
}
};
public logout() {
// Remove token from localStorage
localStorage.removeItem('id_token');
localStorage.removeItem('profile');
};
//Encrypt Single value the user with Base64
// https://github.com/Uisli21/SecureAngularLogin
//cmd=> npm install crypto-js
Encryptvalue(plaintext:any)
{
return CryptoJS.AES.encrypt(plaintext.toString(), 'secret key 123');
}
// Decrypt Single value
Decryptvalue(ciphertext:any)
{
var bytes = CryptoJS.AES.decrypt(ciphertext.toString(), 'secret key 123');
return bytes.toString(CryptoJS.enc.Utf8);
}
//Encrypt full Object value
Encryptobject(object:any)
{
return CryptoJS.AES.encrypt(JSON.stringify(object), 'secret key 1237');
}
//Decrypt full Object value
Decryptobject(object:any)
{
var bytesobject = CryptoJS.AES.decrypt(object.toString(), 'secret key 1237');
return JSON.parse(bytesobject.toString(CryptoJS.enc.Utf8));
}
}
====================================================================
auth.guard
import {Injectable} from '@angular/core';
import {Router, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {CanActivate} from '@angular/router';
import {Auth} from '../../Services/Dashboard/auth.service';
@Injectable()
export class AuthGuard implements CanActivate{
constructor(private auth: Auth, private router: Router){ }
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot){
if(this.auth.authenticated()){
console.log('AUTH GUARD PASSED');
return true;
} else {
console.log('BLOCKED BY AUTH GUARD');
this.router.navigate(['/']);
return false;
}
}
}
====================================================================
Login.component.ts
import { Component,OnInit } from '@angular/core';
import { loginServices} from '../login.services';
import { logininfo } from '../login.interface';
//for user login auth
import {Auth} from '../auth.service';
@Component({
templateUrl: '../../UI/Dashboard/Login.component.html',
styleUrls: ['../../Content/Css/master.css'],
providers: [loginServices,logininfo]
})
export class LoginComponent {
constructor(public _lservices:loginServices, public data:logininfo, private _auth:Auth){}
emplogin()
{
this._lservices.login(this.data).subscribe(res => this.result(res),
res => this.errorlogin(res));
}
result(info: any) {
if (info != null) {
this._auth.loginauth(info.EmpId,info)
}
else {
alert('Invalid User details');
}
}
errorlogin(res: any) {
console.log(res);
};
}
==============================================================
more help full these both url:
https://github.com/Uisli21/SecureAngularLogin
https://www.npmjs.com/package/crypto-js
https://github.com/Uisli21/SecureAngularLogin
https://www.npmjs.com/package/crypto-js
No comments:
Post a Comment