Repository: cornflourblue/angular-8-jwt-authentication-example
Branch: master
Commit: afc7c42b7ad3
Files: 44
Total size: 33.4 KB
Directory structure:
gitextract_mtzcvx3z/
├── .editorconfig
├── .gitignore
├── LICENSE
├── README.md
├── angular.json
├── browserslist
├── e2e/
│ ├── protractor.conf.js
│ ├── src/
│ │ ├── app.e2e-spec.ts
│ │ └── app.po.ts
│ └── tsconfig.json
├── karma.conf.js
├── package.json
├── src/
│ ├── app/
│ │ ├── _helpers/
│ │ │ ├── auth.guard.ts
│ │ │ ├── error.interceptor.ts
│ │ │ ├── fake-backend.ts
│ │ │ ├── index.ts
│ │ │ └── jwt.interceptor.ts
│ │ ├── _models/
│ │ │ ├── index.ts
│ │ │ └── user.ts
│ │ ├── _services/
│ │ │ ├── authentication.service.ts
│ │ │ ├── index.ts
│ │ │ └── user.service.ts
│ │ ├── app.component.html
│ │ ├── app.component.ts
│ │ ├── app.module.ts
│ │ ├── app.routing.ts
│ │ ├── home/
│ │ │ ├── home.component.html
│ │ │ ├── home.component.ts
│ │ │ └── index.ts
│ │ └── login/
│ │ ├── index.ts
│ │ ├── login.component.html
│ │ └── login.component.ts
│ ├── assets/
│ │ └── .gitkeep
│ ├── environments/
│ │ ├── environment.prod.ts
│ │ └── environment.ts
│ ├── index.html
│ ├── main.ts
│ ├── polyfills.ts
│ ├── styles.less
│ └── test.ts
├── tsconfig.app.json
├── tsconfig.json
├── tsconfig.spec.json
└── tslint.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
max_line_length = off
trim_trailing_whitespace = false
================================================
FILE: .gitignore
================================================
# See http://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
/dist
/tmp
/out-tsc
# Only exists if Bazel was run
/bazel-out
# dependencies
/node_modules
# profiling files
chrome-profiler-events.json
speed-measure-plugin.json
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# misc
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
yarn-error.log
testem.log
/typings
# System Files
.DS_Store
Thumbs.db
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2019 Jason Watmore
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# angular-8-jwt-authentication-example
Angular 8 - JWT Authentication Example with the Angular CLI
To see a demo and further details go to https://jasonwatmore.com/post/2019/06/22/angular-8-jwt-authentication-example-tutorial
================================================
FILE: angular.json
================================================
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"angular-8-jwt-authentication-example": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "less"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": false,
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.less"
],
"scripts": []
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "angular-8-jwt-authentication-example:build"
},
"configurations": {
"production": {
"browserTarget": "angular-8-jwt-authentication-example:build:production"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "angular-8-jwt-authentication-example:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.less"
],
"scripts": []
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"tsconfig.app.json",
"tsconfig.spec.json",
"e2e/tsconfig.json"
],
"exclude": [
"**/node_modules/**"
]
}
},
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "angular-8-jwt-authentication-example:serve"
},
"configurations": {
"production": {
"devServerTarget": "angular-8-jwt-authentication-example:serve:production"
}
}
}
}
}},
"defaultProject": "angular-8-jwt-authentication-example"
}
================================================
FILE: browserslist
================================================
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
# You can see what browsers were selected by your queries by running:
# npx browserslist
> 0.5%
last 2 versions
Firefox ESR
not dead
not IE 9-11 # For IE 9-11 support, remove 'not'.
================================================
FILE: e2e/protractor.conf.js
================================================
// @ts-check
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const { SpecReporter } = require('jasmine-spec-reporter');
/**
* @type { import("protractor").Config }
*/
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./src/**/*.e2e-spec.ts'
],
capabilities: {
'browserName': 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare() {
require('ts-node').register({
project: require('path').join(__dirname, './tsconfig.json')
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};
================================================
FILE: e2e/src/app.e2e-spec.ts
================================================
import { AppPage } from './app.po';
import { browser, logging } from 'protractor';
describe('workspace-project App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('Welcome to angular-8-jwt-authentication-example!');
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
} as logging.Entry));
});
});
================================================
FILE: e2e/src/app.po.ts
================================================
import { browser, by, element } from 'protractor';
export class AppPage {
navigateTo() {
return browser.get(browser.baseUrl) as Promise<any>;
}
getTitleText() {
return element(by.css('app-root h1')).getText() as Promise<string>;
}
}
================================================
FILE: e2e/tsconfig.json
================================================
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/e2e",
"module": "commonjs",
"target": "es5",
"types": [
"jasmine",
"jasminewd2",
"node"
]
}
}
================================================
FILE: karma.conf.js
================================================
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, './coverage/angular-8-jwt-authentication-example'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
================================================
FILE: package.json
================================================
{
"name": "angular-8-jwt-authentication-example",
"version": "1.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --open",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"license": "MIT",
"dependencies": {
"@angular/animations": "~8.0.1",
"@angular/common": "~8.0.1",
"@angular/compiler": "~8.0.1",
"@angular/core": "~8.0.1",
"@angular/forms": "~8.0.1",
"@angular/platform-browser": "~8.0.1",
"@angular/platform-browser-dynamic": "~8.0.1",
"@angular/router": "~8.0.1",
"rxjs": "~6.4.0",
"tslib": "^1.9.0",
"zone.js": "~0.9.1"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.800.0",
"@angular/cli": "~8.0.3",
"@angular/compiler-cli": "~8.0.1",
"@angular/language-service": "~8.0.1",
"@types/node": "~8.9.4",
"@types/jasmine": "~3.3.8",
"@types/jasminewd2": "~2.0.3",
"codelyzer": "^5.0.0",
"jasmine-core": "~3.4.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.1.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
"protractor": "~5.4.0",
"ts-node": "~7.0.0",
"tslint": "~5.15.0",
"typescript": "~3.4.3"
}
}
================================================
FILE: src/app/_helpers/auth.guard.ts
================================================
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthenticationService } from '@app/_services';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private authenticationService: AuthenticationService
) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.authenticationService.currentUserValue;
if (currentUser) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
}
================================================
FILE: src/app/_helpers/error.interceptor.ts
================================================
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AuthenticationService } from '@app/_services';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if (err.status === 401) {
// auto logout if 401 response returned from api
this.authenticationService.logout();
location.reload(true);
}
const error = err.error.message || err.statusText;
return throwError(error);
}))
}
}
================================================
FILE: src/app/_helpers/fake-backend.ts
================================================
import { Injectable } from '@angular/core';
import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { delay, mergeMap, materialize, dematerialize } from 'rxjs/operators';
import { User } from '@app/_models';
const users: User[] = [{ id: 1, username: 'test', password: 'test', firstName: 'Test', lastName: 'User' }];
@Injectable()
export class FakeBackendInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const { url, method, headers, body } = request;
// wrap in delayed observable to simulate server api call
return of(null)
.pipe(mergeMap(handleRoute))
.pipe(materialize()) // call materialize and dematerialize to ensure delay even if an error is thrown (https://github.com/Reactive-Extensions/RxJS/issues/648)
.pipe(delay(500))
.pipe(dematerialize());
function handleRoute() {
switch (true) {
case url.endsWith('/users/authenticate') && method === 'POST':
return authenticate();
case url.endsWith('/users') && method === 'GET':
return getUsers();
default:
// pass through any requests not handled above
return next.handle(request);
}
}
// route functions
function authenticate() {
const { username, password } = body;
const user = users.find(x => x.username === username && x.password === password);
if (!user) return error('Username or password is incorrect');
return ok({
id: user.id,
username: user.username,
firstName: user.firstName,
lastName: user.lastName,
token: 'fake-jwt-token'
})
}
function getUsers() {
if (!isLoggedIn()) return unauthorized();
return ok(users);
}
// helper functions
function ok(body?) {
return of(new HttpResponse({ status: 200, body }))
}
function error(message) {
return throwError({ error: { message } });
}
function unauthorized() {
return throwError({ status: 401, error: { message: 'Unauthorised' } });
}
function isLoggedIn() {
return headers.get('Authorization') === 'Bearer fake-jwt-token';
}
}
}
export let fakeBackendProvider = {
// use fake backend in place of Http service for backend-less development
provide: HTTP_INTERCEPTORS,
useClass: FakeBackendInterceptor,
multi: true
};
================================================
FILE: src/app/_helpers/index.ts
================================================
export * from './auth.guard';
export * from './error.interceptor';
export * from './fake-backend';
export * from './jwt.interceptor';
================================================
FILE: src/app/_helpers/jwt.interceptor.ts
================================================
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthenticationService } from '@app/_services';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
let currentUser = this.authenticationService.currentUserValue;
if (currentUser && currentUser.token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.token}`
}
});
}
return next.handle(request);
}
}
================================================
FILE: src/app/_models/index.ts
================================================
export * from './user';
================================================
FILE: src/app/_models/user.ts
================================================
export class User {
id: number;
username: string;
password: string;
firstName: string;
lastName: string;
token?: string;
}
================================================
FILE: src/app/_services/authentication.service.ts
================================================
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { environment } from '@environments/environment';
import { User } from '@app/_models';
@Injectable({ providedIn: 'root' })
export class AuthenticationService {
private currentUserSubject: BehaviorSubject<User>;
public currentUser: Observable<User>;
constructor(private http: HttpClient) {
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
this.currentUser = this.currentUserSubject.asObservable();
}
public get currentUserValue(): User {
return this.currentUserSubject.value;
}
login(username: string, password: string) {
return this.http.post<any>(`${environment.apiUrl}/users/authenticate`, { username, password })
.pipe(map(user => {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
return user;
}));
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
}
}
================================================
FILE: src/app/_services/index.ts
================================================
export * from './authentication.service';
export * from './user.service';
================================================
FILE: src/app/_services/user.service.ts
================================================
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '@environments/environment';
import { User } from '@app/_models';
@Injectable({ providedIn: 'root' })
export class UserService {
constructor(private http: HttpClient) { }
getAll() {
return this.http.get<User[]>(`${environment.apiUrl}/users`);
}
}
================================================
FILE: src/app/app.component.html
================================================
<!-- nav -->
<nav class="navbar navbar-expand navbar-dark bg-dark" *ngIf="currentUser">
<div class="navbar-nav">
<a class="nav-item nav-link" routerLink="/">Home</a>
<a class="nav-item nav-link" (click)="logout()">Logout</a>
</div>
</nav>
<!-- main app container -->
<div class="container">
<router-outlet></router-outlet>
</div>
<!-- credits -->
<div class="text-center mt-4">
<p>
<a href="https://jasonwatmore.com/post/2019/06/22/angular-8-jwt-authentication-example-tutorial" target="_top">Angular 8 - JWT Authentication Example & Tutorial</a>
</p>
<p>
<a href="http://jasonwatmore.com" target="_top">JasonWatmore.com</a>
</p>
</div>
================================================
FILE: src/app/app.component.ts
================================================
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenticationService } from './_services';
import { User } from './_models';
@Component({ selector: 'app', templateUrl: 'app.component.html' })
export class AppComponent {
currentUser: User;
constructor(
private router: Router,
private authenticationService: AuthenticationService
) {
this.authenticationService.currentUser.subscribe(x => this.currentUser = x);
}
logout() {
this.authenticationService.logout();
this.router.navigate(['/login']);
}
}
================================================
FILE: src/app/app.module.ts
================================================
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
// used to create fake backend
import { fakeBackendProvider } from './_helpers';
import { AppComponent } from './app.component';
import { appRoutingModule } from './app.routing';
import { JwtInterceptor, ErrorInterceptor } from './_helpers';
import { HomeComponent } from './home';
import { LoginComponent } from './login';
@NgModule({
imports: [
BrowserModule,
ReactiveFormsModule,
HttpClientModule,
appRoutingModule
],
declarations: [
AppComponent,
HomeComponent,
LoginComponent
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
// provider used to create fake backend
fakeBackendProvider
],
bootstrap: [AppComponent]
})
export class AppModule { }
================================================
FILE: src/app/app.routing.ts
================================================
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home';
import { LoginComponent } from './login';
import { AuthGuard } from './_helpers';
const routes: Routes = [
{ path: '', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },
// otherwise redirect to home
{ path: '**', redirectTo: '' }
];
export const appRoutingModule = RouterModule.forRoot(routes);
================================================
FILE: src/app/home/home.component.html
================================================
<div class="card mt-4">
<h4 class="card-header">You're logged in with Angular 8 & JWT!!</h4>
<div class="card-body">
<h6>Users from secure api end point</h6>
<div *ngIf="loading" class="spinner-border spinner-border-sm"></div>
<ul *ngIf="users">
<li *ngFor="let user of users">{{user.firstName}} {{user.lastName}}</li>
</ul>
</div>
</div>
================================================
FILE: src/app/home/home.component.ts
================================================
import { Component } from '@angular/core';
import { first } from 'rxjs/operators';
import { User } from '@app/_models';
import { UserService, AuthenticationService } from '@app/_services';
@Component({ templateUrl: 'home.component.html' })
export class HomeComponent {
loading = false;
users: User[];
constructor(private userService: UserService) { }
ngOnInit() {
this.loading = true;
this.userService.getAll().pipe(first()).subscribe(users => {
this.loading = false;
this.users = users;
});
}
}
================================================
FILE: src/app/home/index.ts
================================================
export * from './home.component';
================================================
FILE: src/app/login/index.ts
================================================
export * from './login.component';
================================================
FILE: src/app/login/login.component.html
================================================
<div class="col-md-6 offset-md-3 mt-5">
<div class="alert alert-info">
Username: test<br />
Password: test
</div>
<div class="card">
<h4 class="card-header">Angular 8 JWT Login Example</h4>
<div class="card-body">
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="username">Username</label>
<input type="text" formControlName="username" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.username.errors }" />
<div *ngIf="submitted && f.username.errors" class="invalid-feedback">
<div *ngIf="f.username.errors.required">Username is required</div>
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
<div *ngIf="submitted && f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors.required">Password is required</div>
</div>
</div>
<button [disabled]="loading" class="btn btn-primary">
<span *ngIf="loading" class="spinner-border spinner-border-sm mr-1"></span>
Login
</button>
<div *ngIf="error" class="alert alert-danger mt-3 mb-0">{{error}}</div>
</form>
</div>
</div>
</div>
================================================
FILE: src/app/login/login.component.ts
================================================
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { first } from 'rxjs/operators';
import { AuthenticationService } from '@app/_services';
@Component({ templateUrl: 'login.component.html' })
export class LoginComponent implements OnInit {
loginForm: FormGroup;
loading = false;
submitted = false;
returnUrl: string;
error = '';
constructor(
private formBuilder: FormBuilder,
private route: ActivatedRoute,
private router: Router,
private authenticationService: AuthenticationService
) {
// redirect to home if already logged in
if (this.authenticationService.currentUserValue) {
this.router.navigate(['/']);
}
}
ngOnInit() {
this.loginForm = this.formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required]
});
// get return url from route parameters or default to '/'
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}
// convenience getter for easy access to form fields
get f() { return this.loginForm.controls; }
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.loginForm.invalid) {
return;
}
this.loading = true;
this.authenticationService.login(this.f.username.value, this.f.password.value)
.pipe(first())
.subscribe(
data => {
this.router.navigate([this.returnUrl]);
},
error => {
this.error = error;
this.loading = false;
});
}
}
================================================
FILE: src/assets/.gitkeep
================================================
================================================
FILE: src/environments/environment.prod.ts
================================================
export const environment = {
production: true,
apiUrl: 'http://localhost:4000'
};
================================================
FILE: src/environments/environment.ts
================================================
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false,
apiUrl: 'http://localhost:4000'
};
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/dist/zone-error'; // Included with Angular CLI.
================================================
FILE: src/index.html
================================================
<!DOCTYPE html>
<html>
<head>
<base href="/" />
<title>Angular 8 - JWT Authentication Tutorial & Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- bootstrap css -->
<link href="//netdna.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<app>Loading...</app>
</body>
</html>
================================================
FILE: src/main.ts
================================================
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
================================================
FILE: src/polyfills.ts
================================================
/**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported after ZoneJS that should be loaded before your main
* file.
*
* The current setup is for so-called "evergreen" browsers; the last versions of browsers that
* automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
* Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
*
* Learn more in https://angular.io/guide/browser-support
*/
/***************************************************************************************************
* BROWSER POLYFILLS
*/
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
// import 'classlist.js'; // Run `npm install --save classlist.js`.
/**
* Web Animations `@angular/platform-browser/animations`
* Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
* Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
*/
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
/**
* By default, zone.js will patch all possible macroTask and DomEvents
* user can disable parts of macroTask/DomEvents patch by setting following flags
* because those flags need to be set before `zone.js` being loaded, and webpack
* will put import in the top of bundle, so user need to create a separate file
* in this directory (for example: zone-flags.ts), and put the following flags
* into that file, and then add the following code before importing zone.js.
* import './zone-flags.ts';
*
* The flags allowed in zone-flags.ts are listed here.
*
* The following flags will work for all browsers.
*
* (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
* (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
* (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
*
* in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
* with the following flag, it will bypass `zone.js` patch for IE/Edge
*
* (window as any).__Zone_enable_cross_context_check = true;
*
*/
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
import 'zone.js/dist/zone'; // Included with Angular CLI.
/***************************************************************************************************
* APPLICATION IMPORTS
*/
================================================
FILE: src/styles.less
================================================
/* You can add global styles to this file, and also import other style files */
a { cursor: pointer }
================================================
FILE: src/test.ts
================================================
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
declare const require: any;
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
================================================
FILE: tsconfig.app.json
================================================
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"include": [
"src/**/*.ts"
],
"exclude": [
"src/test.ts",
"src/**/*.spec.ts"
]
}
================================================
FILE: tsconfig.json
================================================
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "esnext",
"moduleResolution": "node",
"importHelpers": true,
"target": "es2015",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2018",
"dom"
],
"paths": {
"@app/*": ["src/app/*"],
"@environments/*": ["src/environments/*"]
}
}
}
================================================
FILE: tsconfig.spec.json
================================================
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine",
"node"
]
},
"files": [
"src/test.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}
================================================
FILE: tslint.json
================================================
{
"extends": "tslint:recommended",
"rules": {
"array-type": false,
"arrow-parens": false,
"deprecation": {
"severity": "warn"
},
"component-class-suffix": true,
"contextual-lifecycle": true,
"directive-class-suffix": true,
"directive-selector": [
true,
"attribute",
"app",
"camelCase"
],
"component-selector": [
true,
"element",
"app",
"kebab-case"
],
"import-blacklist": [
true,
"rxjs/Rx"
],
"interface-name": false,
"max-classes-per-file": false,
"max-line-length": [
true,
140
],
"member-access": false,
"member-ordering": [
true,
{
"order": [
"static-field",
"instance-field",
"static-method",
"instance-method"
]
}
],
"no-consecutive-blank-lines": false,
"no-console": [
true,
"debug",
"info",
"time",
"timeEnd",
"trace"
],
"no-empty": false,
"no-inferrable-types": [
true,
"ignore-params"
],
"no-non-null-assertion": true,
"no-redundant-jsdoc": true,
"no-switch-case-fall-through": true,
"no-use-before-declare": true,
"no-var-requires": false,
"object-literal-key-quotes": [
true,
"as-needed"
],
"object-literal-sort-keys": false,
"ordered-imports": false,
"quotemark": [
true,
"single"
],
"trailing-comma": false,
"no-conflicting-lifecycle": true,
"no-host-metadata-property": true,
"no-input-rename": true,
"no-inputs-metadata-property": true,
"no-output-native": true,
"no-output-on-prefix": true,
"no-output-rename": true,
"no-outputs-metadata-property": true,
"template-banana-in-box": true,
"template-no-negated-async": true,
"use-lifecycle-interface": true,
"use-pipe-transform-interface": true
},
"rulesDirectory": [
"codelyzer"
]
}
gitextract_mtzcvx3z/ ├── .editorconfig ├── .gitignore ├── LICENSE ├── README.md ├── angular.json ├── browserslist ├── e2e/ │ ├── protractor.conf.js │ ├── src/ │ │ ├── app.e2e-spec.ts │ │ └── app.po.ts │ └── tsconfig.json ├── karma.conf.js ├── package.json ├── src/ │ ├── app/ │ │ ├── _helpers/ │ │ │ ├── auth.guard.ts │ │ │ ├── error.interceptor.ts │ │ │ ├── fake-backend.ts │ │ │ ├── index.ts │ │ │ └── jwt.interceptor.ts │ │ ├── _models/ │ │ │ ├── index.ts │ │ │ └── user.ts │ │ ├── _services/ │ │ │ ├── authentication.service.ts │ │ │ ├── index.ts │ │ │ └── user.service.ts │ │ ├── app.component.html │ │ ├── app.component.ts │ │ ├── app.module.ts │ │ ├── app.routing.ts │ │ ├── home/ │ │ │ ├── home.component.html │ │ │ ├── home.component.ts │ │ │ └── index.ts │ │ └── login/ │ │ ├── index.ts │ │ ├── login.component.html │ │ └── login.component.ts │ ├── assets/ │ │ └── .gitkeep │ ├── environments/ │ │ ├── environment.prod.ts │ │ └── environment.ts │ ├── index.html │ ├── main.ts │ ├── polyfills.ts │ ├── styles.less │ └── test.ts ├── tsconfig.app.json ├── tsconfig.json ├── tsconfig.spec.json └── tslint.json
SYMBOL INDEX (36 symbols across 13 files)
FILE: e2e/protractor.conf.js
method onPrepare (line 26) | onPrepare() {
FILE: e2e/src/app.po.ts
class AppPage (line 3) | class AppPage {
method navigateTo (line 4) | navigateTo() {
method getTitleText (line 8) | getTitleText() {
FILE: src/app/_helpers/auth.guard.ts
class AuthGuard (line 7) | class AuthGuard implements CanActivate {
method constructor (line 8) | constructor(
method canActivate (line 13) | canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
FILE: src/app/_helpers/error.interceptor.ts
class ErrorInterceptor (line 9) | class ErrorInterceptor implements HttpInterceptor {
method constructor (line 10) | constructor(private authenticationService: AuthenticationService) { }
method intercept (line 12) | intercept(request: HttpRequest<any>, next: HttpHandler): Observable<Ht...
FILE: src/app/_helpers/fake-backend.ts
class FakeBackendInterceptor (line 11) | class FakeBackendInterceptor implements HttpInterceptor {
method intercept (line 12) | intercept(request: HttpRequest<any>, next: HttpHandler): Observable<Ht...
FILE: src/app/_helpers/jwt.interceptor.ts
class JwtInterceptor (line 8) | class JwtInterceptor implements HttpInterceptor {
method constructor (line 9) | constructor(private authenticationService: AuthenticationService) { }
method intercept (line 11) | intercept(request: HttpRequest<any>, next: HttpHandler): Observable<Ht...
FILE: src/app/_models/user.ts
class User (line 1) | class User {
FILE: src/app/_services/authentication.service.ts
class AuthenticationService (line 10) | class AuthenticationService {
method constructor (line 14) | constructor(private http: HttpClient) {
method currentUserValue (line 19) | public get currentUserValue(): User {
method login (line 23) | login(username: string, password: string) {
method logout (line 33) | logout() {
FILE: src/app/_services/user.service.ts
class UserService (line 8) | class UserService {
method constructor (line 9) | constructor(private http: HttpClient) { }
method getAll (line 11) | getAll() {
FILE: src/app/app.component.ts
class AppComponent (line 8) | class AppComponent {
method constructor (line 11) | constructor(
method logout (line 18) | logout() {
FILE: src/app/app.module.ts
class AppModule (line 37) | class AppModule { }
FILE: src/app/home/home.component.ts
class HomeComponent (line 8) | class HomeComponent {
method constructor (line 12) | constructor(private userService: UserService) { }
method ngOnInit (line 14) | ngOnInit() {
FILE: src/app/login/login.component.ts
class LoginComponent (line 9) | class LoginComponent implements OnInit {
method constructor (line 16) | constructor(
method ngOnInit (line 28) | ngOnInit() {
method f (line 39) | get f() { return this.loginForm.controls; }
method onSubmit (line 41) | onSubmit() {
Condensed preview — 44 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (38K chars).
[
{
"path": ".editorconfig",
"chars": 246,
"preview": "# Editor configuration, see https://editorconfig.org\nroot = true\n\n[*]\ncharset = utf-8\nindent_style = space\nindent_size ="
},
{
"path": ".gitignore",
"chars": 629,
"preview": "# See http://help.github.com/ignore-files/ for more about ignoring files.\n\n# compiled output\n/dist\n/tmp\n/out-tsc\n# Only "
},
{
"path": "LICENSE",
"chars": 1080,
"preview": "The MIT License (MIT)\n\nCopyright (c) 2019 Jason Watmore\n\nPermission is hereby granted, free of charge, to any person obt"
},
{
"path": "README.md",
"chars": 227,
"preview": "# angular-8-jwt-authentication-example\n\nAngular 8 - JWT Authentication Example with the Angular CLI\n\nTo see a demo and f"
},
{
"path": "angular.json",
"chars": 3716,
"preview": "{\n \"$schema\": \"./node_modules/@angular/cli/lib/config/schema.json\",\n \"version\": 1,\n \"newProjectRoot\": \"projects\",\n \""
},
{
"path": "browserslist",
"chars": 429,
"preview": "# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.\n# For addit"
},
{
"path": "e2e/protractor.conf.js",
"chars": 810,
"preview": "// @ts-check\n// Protractor configuration file, see link for more information\n// https://github.com/angular/protractor/bl"
},
{
"path": "e2e/src/app.e2e-spec.ts",
"chars": 665,
"preview": "import { AppPage } from './app.po';\nimport { browser, logging } from 'protractor';\n\ndescribe('workspace-project App', ()"
},
{
"path": "e2e/src/app.po.ts",
"chars": 251,
"preview": "import { browser, by, element } from 'protractor';\n\nexport class AppPage {\n navigateTo() {\n return browser.get(brows"
},
{
"path": "e2e/tsconfig.json",
"chars": 214,
"preview": "{\n \"extends\": \"../tsconfig.json\",\n \"compilerOptions\": {\n \"outDir\": \"../out-tsc/e2e\",\n \"module\": \"commonjs\",\n "
},
{
"path": "karma.conf.js",
"chars": 1048,
"preview": "// Karma configuration file, see link for more information\n// https://karma-runner.github.io/1.0/config/configuration-fi"
},
{
"path": "package.json",
"chars": 1499,
"preview": "{\n \"name\": \"angular-8-jwt-authentication-example\",\n \"version\": \"1.0.0\",\n \"scripts\": {\n \"ng\": \"ng\",\n "
},
{
"path": "src/app/_helpers/auth.guard.ts",
"chars": 846,
"preview": "import { Injectable } from '@angular/core';\nimport { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot }"
},
{
"path": "src/app/_helpers/error.interceptor.ts",
"chars": 916,
"preview": "import { Injectable } from '@angular/core';\nimport { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angul"
},
{
"path": "src/app/_helpers/fake-backend.ts",
"chars": 2838,
"preview": "import { Injectable } from '@angular/core';\nimport { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor"
},
{
"path": "src/app/_helpers/index.ts",
"chars": 134,
"preview": "export * from './auth.guard';\nexport * from './error.interceptor';\nexport * from './fake-backend';\nexport * from './jwt"
},
{
"path": "src/app/_helpers/jwt.interceptor.ts",
"chars": 871,
"preview": "import { Injectable } from '@angular/core';\nimport { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angul"
},
{
"path": "src/app/_models/index.ts",
"chars": 24,
"preview": "export * from './user';"
},
{
"path": "src/app/_models/user.ts",
"chars": 147,
"preview": "export class User {\n id: number;\n username: string;\n password: string;\n firstName: string;\n lastName: st"
},
{
"path": "src/app/_services/authentication.service.ts",
"chars": 1426,
"preview": "import { Injectable } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\nimport { BehaviorSubject"
},
{
"path": "src/app/_services/index.ts",
"chars": 74,
"preview": "export * from './authentication.service';\nexport * from './user.service';"
},
{
"path": "src/app/_services/user.service.ts",
"chars": 393,
"preview": "import { Injectable } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\n\nimport { environment } "
},
{
"path": "src/app/app.component.html",
"chars": 699,
"preview": "<!-- nav -->\n<nav class=\"navbar navbar-expand navbar-dark bg-dark\" *ngIf=\"currentUser\">\n <div class=\"navbar-nav\">\n "
},
{
"path": "src/app/app.component.ts",
"chars": 613,
"preview": "import { Component } from '@angular/core';\nimport { Router } from '@angular/router';\n\nimport { AuthenticationService } "
},
{
"path": "src/app/app.module.ts",
"chars": 1112,
"preview": "import { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { ReactiveF"
},
{
"path": "src/app/app.routing.ts",
"chars": 461,
"preview": "import { Routes, RouterModule } from '@angular/router';\n\nimport { HomeComponent } from './home';\nimport { LoginComponen"
},
{
"path": "src/app/home/home.component.html",
"chars": 395,
"preview": "<div class=\"card mt-4\">\n <h4 class=\"card-header\">You're logged in with Angular 8 & JWT!!</h4>\n <div class=\"card-b"
},
{
"path": "src/app/home/home.component.ts",
"chars": 568,
"preview": "import { Component } from '@angular/core';\nimport { first } from 'rxjs/operators';\n\nimport { User } from '@app/_models'"
},
{
"path": "src/app/home/index.ts",
"chars": 34,
"preview": "export * from './home.component';"
},
{
"path": "src/app/login/index.ts",
"chars": 35,
"preview": "export * from './login.component';"
},
{
"path": "src/app/login/login.component.html",
"chars": 1652,
"preview": "<div class=\"col-md-6 offset-md-3 mt-5\">\n <div class=\"alert alert-info\">\n Username: test<br />\n Passwor"
},
{
"path": "src/app/login/login.component.ts",
"chars": 1855,
"preview": "import { Component, OnInit } from '@angular/core';\nimport { Router, ActivatedRoute } from '@angular/router';\nimport { F"
},
{
"path": "src/assets/.gitkeep",
"chars": 0,
"preview": ""
},
{
"path": "src/environments/environment.prod.ts",
"chars": 90,
"preview": "export const environment = {\n production: true,\n apiUrl: 'http://localhost:4000'\n};\n"
},
{
"path": "src/environments/environment.ts",
"chars": 701,
"preview": "// This file can be replaced during build by using the `fileReplacements` array.\n// `ng build --prod` replaces `environm"
},
{
"path": "src/index.html",
"chars": 381,
"preview": "<!DOCTYPE html>\n<html>\n<head>\n <base href=\"/\" />\n <title>Angular 8 - JWT Authentication Tutorial & Example</title"
},
{
"path": "src/main.ts",
"chars": 376,
"preview": "import { enableProdMode } from '@angular/core';\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynami"
},
{
"path": "src/polyfills.ts",
"chars": 2838,
"preview": "/**\n * This file includes polyfills needed by Angular and is loaded before the app.\n * You can add your own extra polyfi"
},
{
"path": "src/styles.less",
"chars": 101,
"preview": "/* You can add global styles to this file, and also import other style files */\na { cursor: pointer }"
},
{
"path": "src/test.ts",
"chars": 642,
"preview": "// This file is required by karma.conf.js and loads recursively all the .spec and framework files\n\nimport 'zone.js/dist/"
},
{
"path": "tsconfig.app.json",
"chars": 210,
"preview": "{\n \"extends\": \"./tsconfig.json\",\n \"compilerOptions\": {\n \"outDir\": \"./out-tsc/app\",\n \"types\": []\n },\n \"include\""
},
{
"path": "tsconfig.json",
"chars": 674,
"preview": "{\n \"compileOnSave\": false,\n \"compilerOptions\": {\n \"baseUrl\": \"./\",\n \"outDir\": \"./dist/out-tsc\",\n "
},
{
"path": "tsconfig.spec.json",
"chars": 270,
"preview": "{\n \"extends\": \"./tsconfig.json\",\n \"compilerOptions\": {\n \"outDir\": \"./out-tsc/spec\",\n \"types\": [\n \"jasmine\","
},
{
"path": "tslint.json",
"chars": 1985,
"preview": "{\n \"extends\": \"tslint:recommended\",\n \"rules\": {\n \"array-type\": false,\n \"arrow-parens\": false,\n \"deprecation\":"
}
]
About this extraction
This page contains the full source code of the cornflourblue/angular-8-jwt-authentication-example GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 44 files (33.4 KB), approximately 9.0k tokens, and a symbol index with 36 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.