SlideShare a Scribd company logo
1 of 15
1
Authenticating
Angular Apps With JWTs
Discussion Agenda
• OAuth 2.0 Background
• What is a JWT?
• JWT Authentication Token Lifecycle
• HTTP Interceptor design pattern in Angular
2
Background: OAuth 2.0 Bearer Tokens
• OAuth 2.0 is a Token Based Authentication Framework typically used with SPA
apps.
• OAuth 2.0 uses encrypted/encoded token strings instead of passing usernames and
passwords.
• An OAuth 2.0 infrastructure issues tokens to users after authentication. The token
must be saved locally on the client and authorizes the user’s access to resources
(APIs, etc.) for a set amount of time.
• Upon token expiration, the user must log in again to access resources (APIs) with
subsequent HTTP Requests.
• A common way of accessing OAuth 2.0 APIs is using a “Bearer Token”. This is a
single string which acts as the authentication of the API request, sent in an HTTP
“Authorization” header.
3
Sample Bearer Token Payload
In an HTTP Request sent to an API using
OAuth 2.0, the Authorization header
contains the Bearer Token as shown here
4
Bearer Tokens are encrypted/encoded token strings
labeled “Bearer” which are used to validate
authentication claims on the server side.
Bearer 0b79bab50daca910b000d4f1a2b675d604257e42…
JWT is a Token Format used to implement OAuth 2.0
• OAuth 2.0 Bearer Tokens need to contain user identity and timeout information.
• Bearer Tokens are issued by the authorization server, expire and can be reused.
• Bearer Tokens need to be signed so that the resource server can validate them
• JWTs are used with SPA apps as Bearer Tokens for OAuth 2.0 authentication.
5
User
Enterprise
login
API
JWT = JSON Web Tokens
• JSON Web Tokens are called JWTs for abbreviation.
• JWTs are digitally signed JSON payloads. Payloads typically contain user identification info
and a lifespan timestamp for authentication.
• As discussed, JWTs are often created by authentication servers to use as Bearer Tokens.
• Bearer Tokens expire, so Angular apps can use JWTs to define a user session.
• JWTs are convenient, because to confirm a session, all the authentication code needs to do
is validate the token’s signature.
• JWTs contain an encoded header, an encoded payload, and are digitally signed by
encrypting the header and payload with a secret key.
• The authentication code signs and validates JWT signatures, so only the server
(resource server and authenticating server) needs to know the secret key.
6
JWT Structure
7
{
“alg”: “HS256”,
“typ”: “JWT”
}
Header
{
“userId”: “023040506”,
“timeout”: “1234567890000”
}
Payload
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydW
V9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
Base64Url
encoded
Base64Url
encoded
Signature =
HMACSHA256( base64UrlEncode(header) + ".“ base64UrlEncode(payload), secret )
3 Components of a JWT
1. The Header defines the Algorithm and Token Type. (JWT in this case)
{
“alg”: “HS256”,
“typ”: “JWT”
}
2. The Payload contains user information necessary to support the Session. The
Payload typically contains a user ID and an expiration timestamp for authentication.
The Payload is -not- encrypted so it is important to mind its contents!
{
“userId”: “023040506”,
“timeout”: “1234567890000”
}
3. The Signature contains a Message Authentication Code string. To produce a
valid signature, you need the Payload and Header, and a Secret Key which is unique
to your app.
8
The JWT Signature is used to validate claims
• The authenticating party (authentication server and resource server) holds a secret key
string, which is used to create and validate the signatures of JWTs.
• The authentication server uses the SHA256 encryption algorithm and its personal
secret key string to create JWT signatures using the below algorithm:
HMACSHA256( base64UrlEncode(header) + ".“ base64UrlEncode(payload), secret )
• From the browser, the user logs in once through the authentication server, then receives
a personal unique JWT (a “Bearer Token”) with the above unique signature back via an
HTTP Response.
• The browser then only needs to save the JWT Bearer Token in memory, and it can be
used to validate every HTTP Request with the secret key string, thus defining a
session.
9
JWT Bearer Token Lifecycle
10
ServerBrowser
1: User sends username and password to server via
browser 2: Server validates
username and
password.
3: Server generates
JWT Bearer Token
using secret key
4: Server sends Bearer Token back to
browser. Does not include password in
Bearer Token payload
5: Browser saves
Bearer Token in
local storage
6: Browser sends Bearer Token back to server with
HTTP Requests 7: Server decodes
Bearer Token, checks
the timestamp and
validates the signature
using the secret key
8: Server sends back HTTP Response data
if the session is valid.
A valid session = timestamp
has not expired and Bearer
Token signature is valid!
eyJhbGciOiJIUzI1NiIsI
nR5cCI6IkpXVCJ9.eyJ
zdWIiOiIxMjM0NTY3O
DkwIiwibmFtZSI6Ikpva
G4gRG9lIiwiYWRtaW4i
OnRydWV9.TJVA95Or
M7E2cBab30RMHrHDc
EfxjoYZgeFONFh7HgQ
Auth
API
Angular HTTP Interceptor Design Pattern – Step 0
Install a library to your app to use to check if a JWT is expired. I
like angular2-jwt.
npm i --save angular2-jwt
11
Angular HTTP Interceptor Design Pattern – Step 1
Use angular2-jwt in a service.
// src/app/auth/auth.service.ts
import { Injectable } from '@angular/core';
import tokenNotExpired from ‘angular2-jwt’;
@Injectable()
export class AuthService {
public getToken(): string {
return localStorage.getItem('token');
}
public isAuthenticated(): boolean {
// get the token
const token = this.getToken();
// return a boolean reflecting whether or not the token is expired
return tokenNotExpired(null, token);
}
}
12
Angular HTTP Interceptor Design Pattern – Step 2
Create an Interceptor which adds the JWT from local storage to the Authorization
Header in any HTTP Request sent.
// src/app/auth/token.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { AuthService } from './auth/auth.service';
import { Observable } from 'rxjs/Observable’;
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`
}
});
return next.handle(request);
}
}
13
Angular HTTP Interceptor Design Pattern – Step 3
Add our new Interceptor class to the HTTP Interceptors service provider (and add the HTTP
Interceptors service to your app if needed).
// src/app/app.module.ts
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { TokenInterceptor } from './../auth/token.interceptor’;
@NgModule({
bootstrap: [AppComponent],
imports: [...],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}
]
})
export class AppModule {}
14
Angular HTTP Interceptor Design Pattern – Step 4
Now when we make any HTTP request, the user’s token will be attached
automatically.
Our TokenInterceptor was added to the HTTP Interceptors array by making
the existing HTTP_Interceptors array use our new class.
Now the application-scoped HTTP Interceptors service will use our new class,
and the Authorization Header with our Bearer Token will be added to every
HTTP Request.
15

More Related Content

What's hot

Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring bootAntoine Rey
 
Meetup angular http client
Meetup angular http clientMeetup angular http client
Meetup angular http clientGaurav Madaan
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectJadson Santos
 
Developing Faster with Swagger
Developing Faster with SwaggerDeveloping Faster with Swagger
Developing Faster with SwaggerTony Tam
 
Angular data binding
Angular data binding Angular data binding
Angular data binding Sultan Ahmed
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfKnoldus Inc.
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 formsEyal Vardi
 
Observables in Angular
Observables in AngularObservables in Angular
Observables in AngularKnoldus Inc.
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationWebStackAcademy
 

What's hot (20)

Support cours angular
Support cours angularSupport cours angular
Support cours angular
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring boot
 
Meetup angular http client
Meetup angular http clientMeetup angular http client
Meetup angular http client
 
Angular modules in depth
Angular modules in depthAngular modules in depth
Angular modules in depth
 
Vue.js
Vue.jsVue.js
Vue.js
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Developing Faster with Swagger
Developing Faster with SwaggerDeveloping Faster with Swagger
Developing Faster with Swagger
 
Angular data binding
Angular data binding Angular data binding
Angular data binding
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Introduction à Angular 2
Introduction à Angular 2Introduction à Angular 2
Introduction à Angular 2
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
 
Observables in Angular
Observables in AngularObservables in Angular
Observables in Angular
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
 

Similar to Authenticating Angular Apps with JWT

Microservice Protection With WSO2 Identity Server
Microservice Protection With WSO2 Identity ServerMicroservice Protection With WSO2 Identity Server
Microservice Protection With WSO2 Identity ServerAnupam Gogoi
 
JavaOne 2014 - Securing RESTful Resources with OAuth2
JavaOne 2014 - Securing RESTful Resources with OAuth2JavaOne 2014 - Securing RESTful Resources with OAuth2
JavaOne 2014 - Securing RESTful Resources with OAuth2Rodrigo Cândido da Silva
 
[WSO2 API Manager Community Call] Mastering JWTs with WSO2 API Manager
[WSO2 API Manager Community Call] Mastering JWTs with WSO2 API Manager[WSO2 API Manager Community Call] Mastering JWTs with WSO2 API Manager
[WSO2 API Manager Community Call] Mastering JWTs with WSO2 API ManagerWSO2
 
GSoC Mideterm-OAuth2 Module
GSoC Mideterm-OAuth2 ModuleGSoC Mideterm-OAuth2 Module
GSoC Mideterm-OAuth2 ModuleMayank Sharma
 
ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2Rodrigo Cândido da Silva
 
JHipster and Okta - JHipster Virtual Meetup December 2020
JHipster and Okta - JHipster Virtual Meetup December 2020JHipster and Okta - JHipster Virtual Meetup December 2020
JHipster and Okta - JHipster Virtual Meetup December 2020Matt Raible
 
Mobile Authentication - Onboarding, best practices & anti-patterns
Mobile Authentication - Onboarding, best practices & anti-patternsMobile Authentication - Onboarding, best practices & anti-patterns
Mobile Authentication - Onboarding, best practices & anti-patternsPieter Ennes
 
OAuth2 and OpenID with Spring Boot
OAuth2 and OpenID with Spring BootOAuth2 and OpenID with Spring Boot
OAuth2 and OpenID with Spring BootGeert Pante
 
Web API 2 Token Based Authentication
Web API 2 Token Based AuthenticationWeb API 2 Token Based Authentication
Web API 2 Token Based Authenticationjeremysbrown
 
An introduction to OAuth 2
An introduction to OAuth 2An introduction to OAuth 2
An introduction to OAuth 2Sanjoy Kumar Roy
 
API Security : Patterns and Practices
API Security : Patterns and PracticesAPI Security : Patterns and Practices
API Security : Patterns and PracticesPrabath Siriwardena
 
Microservices Security landscape
Microservices Security landscapeMicroservices Security landscape
Microservices Security landscapeSagara Gunathunga
 
Jwt the complete guide to json web tokens
Jwt  the complete guide to json web tokensJwt  the complete guide to json web tokens
Jwt the complete guide to json web tokensremayssat
 
#5 WSO2 Masterclassitalia - WSO2 Identity Server, un approccio OAUTH2
#5 WSO2 Masterclassitalia - WSO2 Identity Server, un approccio OAUTH2#5 WSO2 Masterclassitalia - WSO2 Identity Server, un approccio OAUTH2
#5 WSO2 Masterclassitalia - WSO2 Identity Server, un approccio OAUTH2Profesia Srl, Lynx Group
 
Protecting web APIs with OAuth 2.0
Protecting web APIs with OAuth 2.0Protecting web APIs with OAuth 2.0
Protecting web APIs with OAuth 2.0Vladimir Dzhuvinov
 
.NET Core, ASP.NET Core Course, Session 19
 .NET Core, ASP.NET Core Course, Session 19 .NET Core, ASP.NET Core Course, Session 19
.NET Core, ASP.NET Core Course, Session 19aminmesbahi
 
Client certificate validation in windows 8
Client certificate validation in windows 8Client certificate validation in windows 8
Client certificate validation in windows 8Ashish Agrawal
 
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015Stuart
 

Similar to Authenticating Angular Apps with JWT (20)

Microservice Protection With WSO2 Identity Server
Microservice Protection With WSO2 Identity ServerMicroservice Protection With WSO2 Identity Server
Microservice Protection With WSO2 Identity Server
 
JavaOne 2014 - Securing RESTful Resources with OAuth2
JavaOne 2014 - Securing RESTful Resources with OAuth2JavaOne 2014 - Securing RESTful Resources with OAuth2
JavaOne 2014 - Securing RESTful Resources with OAuth2
 
[WSO2 API Manager Community Call] Mastering JWTs with WSO2 API Manager
[WSO2 API Manager Community Call] Mastering JWTs with WSO2 API Manager[WSO2 API Manager Community Call] Mastering JWTs with WSO2 API Manager
[WSO2 API Manager Community Call] Mastering JWTs with WSO2 API Manager
 
GSoC Mideterm-OAuth2 Module
GSoC Mideterm-OAuth2 ModuleGSoC Mideterm-OAuth2 Module
GSoC Mideterm-OAuth2 Module
 
ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2
 
JHipster and Okta - JHipster Virtual Meetup December 2020
JHipster and Okta - JHipster Virtual Meetup December 2020JHipster and Okta - JHipster Virtual Meetup December 2020
JHipster and Okta - JHipster Virtual Meetup December 2020
 
Mobile Authentication - Onboarding, best practices & anti-patterns
Mobile Authentication - Onboarding, best practices & anti-patternsMobile Authentication - Onboarding, best practices & anti-patterns
Mobile Authentication - Onboarding, best practices & anti-patterns
 
OAuth2 and OpenID with Spring Boot
OAuth2 and OpenID with Spring BootOAuth2 and OpenID with Spring Boot
OAuth2 and OpenID with Spring Boot
 
Web API 2 Token Based Authentication
Web API 2 Token Based AuthenticationWeb API 2 Token Based Authentication
Web API 2 Token Based Authentication
 
An introduction to OAuth 2
An introduction to OAuth 2An introduction to OAuth 2
An introduction to OAuth 2
 
API Security : Patterns and Practices
API Security : Patterns and PracticesAPI Security : Patterns and Practices
API Security : Patterns and Practices
 
Microservices Security landscape
Microservices Security landscapeMicroservices Security landscape
Microservices Security landscape
 
Jwt the complete guide to json web tokens
Jwt  the complete guide to json web tokensJwt  the complete guide to json web tokens
Jwt the complete guide to json web tokens
 
#5 WSO2 Masterclassitalia - WSO2 Identity Server, un approccio OAUTH2
#5 WSO2 Masterclassitalia - WSO2 Identity Server, un approccio OAUTH2#5 WSO2 Masterclassitalia - WSO2 Identity Server, un approccio OAUTH2
#5 WSO2 Masterclassitalia - WSO2 Identity Server, un approccio OAUTH2
 
Protecting web APIs with OAuth 2.0
Protecting web APIs with OAuth 2.0Protecting web APIs with OAuth 2.0
Protecting web APIs with OAuth 2.0
 
Api security
Api security Api security
Api security
 
.NET Core, ASP.NET Core Course, Session 19
 .NET Core, ASP.NET Core Course, Session 19 .NET Core, ASP.NET Core Course, Session 19
.NET Core, ASP.NET Core Course, Session 19
 
OAuth2
OAuth2OAuth2
OAuth2
 
Client certificate validation in windows 8
Client certificate validation in windows 8Client certificate validation in windows 8
Client certificate validation in windows 8
 
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
 

More from Jennifer Estrada

More from Jennifer Estrada (6)

React JS .NET
React JS .NETReact JS .NET
React JS .NET
 
Angular View Encapsulation
Angular View EncapsulationAngular View Encapsulation
Angular View Encapsulation
 
Comparing Angular and React JS for SPAs
Comparing Angular and React JS for SPAsComparing Angular and React JS for SPAs
Comparing Angular and React JS for SPAs
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
Domain Driven Design for Angular
Domain Driven Design for AngularDomain Driven Design for Angular
Domain Driven Design for Angular
 
Angular IO
Angular IOAngular IO
Angular IO
 

Recently uploaded

(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 

Recently uploaded (20)

(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 

Authenticating Angular Apps with JWT

  • 2. Discussion Agenda • OAuth 2.0 Background • What is a JWT? • JWT Authentication Token Lifecycle • HTTP Interceptor design pattern in Angular 2
  • 3. Background: OAuth 2.0 Bearer Tokens • OAuth 2.0 is a Token Based Authentication Framework typically used with SPA apps. • OAuth 2.0 uses encrypted/encoded token strings instead of passing usernames and passwords. • An OAuth 2.0 infrastructure issues tokens to users after authentication. The token must be saved locally on the client and authorizes the user’s access to resources (APIs, etc.) for a set amount of time. • Upon token expiration, the user must log in again to access resources (APIs) with subsequent HTTP Requests. • A common way of accessing OAuth 2.0 APIs is using a “Bearer Token”. This is a single string which acts as the authentication of the API request, sent in an HTTP “Authorization” header. 3
  • 4. Sample Bearer Token Payload In an HTTP Request sent to an API using OAuth 2.0, the Authorization header contains the Bearer Token as shown here 4 Bearer Tokens are encrypted/encoded token strings labeled “Bearer” which are used to validate authentication claims on the server side. Bearer 0b79bab50daca910b000d4f1a2b675d604257e42…
  • 5. JWT is a Token Format used to implement OAuth 2.0 • OAuth 2.0 Bearer Tokens need to contain user identity and timeout information. • Bearer Tokens are issued by the authorization server, expire and can be reused. • Bearer Tokens need to be signed so that the resource server can validate them • JWTs are used with SPA apps as Bearer Tokens for OAuth 2.0 authentication. 5 User Enterprise login API
  • 6. JWT = JSON Web Tokens • JSON Web Tokens are called JWTs for abbreviation. • JWTs are digitally signed JSON payloads. Payloads typically contain user identification info and a lifespan timestamp for authentication. • As discussed, JWTs are often created by authentication servers to use as Bearer Tokens. • Bearer Tokens expire, so Angular apps can use JWTs to define a user session. • JWTs are convenient, because to confirm a session, all the authentication code needs to do is validate the token’s signature. • JWTs contain an encoded header, an encoded payload, and are digitally signed by encrypting the header and payload with a secret key. • The authentication code signs and validates JWT signatures, so only the server (resource server and authenticating server) needs to know the secret key. 6
  • 7. JWT Structure 7 { “alg”: “HS256”, “typ”: “JWT” } Header { “userId”: “023040506”, “timeout”: “1234567890000” } Payload eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydW V9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ Base64Url encoded Base64Url encoded Signature = HMACSHA256( base64UrlEncode(header) + ".“ base64UrlEncode(payload), secret )
  • 8. 3 Components of a JWT 1. The Header defines the Algorithm and Token Type. (JWT in this case) { “alg”: “HS256”, “typ”: “JWT” } 2. The Payload contains user information necessary to support the Session. The Payload typically contains a user ID and an expiration timestamp for authentication. The Payload is -not- encrypted so it is important to mind its contents! { “userId”: “023040506”, “timeout”: “1234567890000” } 3. The Signature contains a Message Authentication Code string. To produce a valid signature, you need the Payload and Header, and a Secret Key which is unique to your app. 8
  • 9. The JWT Signature is used to validate claims • The authenticating party (authentication server and resource server) holds a secret key string, which is used to create and validate the signatures of JWTs. • The authentication server uses the SHA256 encryption algorithm and its personal secret key string to create JWT signatures using the below algorithm: HMACSHA256( base64UrlEncode(header) + ".“ base64UrlEncode(payload), secret ) • From the browser, the user logs in once through the authentication server, then receives a personal unique JWT (a “Bearer Token”) with the above unique signature back via an HTTP Response. • The browser then only needs to save the JWT Bearer Token in memory, and it can be used to validate every HTTP Request with the secret key string, thus defining a session. 9
  • 10. JWT Bearer Token Lifecycle 10 ServerBrowser 1: User sends username and password to server via browser 2: Server validates username and password. 3: Server generates JWT Bearer Token using secret key 4: Server sends Bearer Token back to browser. Does not include password in Bearer Token payload 5: Browser saves Bearer Token in local storage 6: Browser sends Bearer Token back to server with HTTP Requests 7: Server decodes Bearer Token, checks the timestamp and validates the signature using the secret key 8: Server sends back HTTP Response data if the session is valid. A valid session = timestamp has not expired and Bearer Token signature is valid! eyJhbGciOiJIUzI1NiIsI nR5cCI6IkpXVCJ9.eyJ zdWIiOiIxMjM0NTY3O DkwIiwibmFtZSI6Ikpva G4gRG9lIiwiYWRtaW4i OnRydWV9.TJVA95Or M7E2cBab30RMHrHDc EfxjoYZgeFONFh7HgQ Auth API
  • 11. Angular HTTP Interceptor Design Pattern – Step 0 Install a library to your app to use to check if a JWT is expired. I like angular2-jwt. npm i --save angular2-jwt 11
  • 12. Angular HTTP Interceptor Design Pattern – Step 1 Use angular2-jwt in a service. // src/app/auth/auth.service.ts import { Injectable } from '@angular/core'; import tokenNotExpired from ‘angular2-jwt’; @Injectable() export class AuthService { public getToken(): string { return localStorage.getItem('token'); } public isAuthenticated(): boolean { // get the token const token = this.getToken(); // return a boolean reflecting whether or not the token is expired return tokenNotExpired(null, token); } } 12
  • 13. Angular HTTP Interceptor Design Pattern – Step 2 Create an Interceptor which adds the JWT from local storage to the Authorization Header in any HTTP Request sent. // src/app/auth/token.interceptor.ts import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; import { AuthService } from './auth/auth.service'; import { Observable } from 'rxjs/Observable’; @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(public auth: AuthService) {} intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { request = request.clone({ setHeaders: { Authorization: `Bearer ${this.auth.getToken()}` } }); return next.handle(request); } } 13
  • 14. Angular HTTP Interceptor Design Pattern – Step 3 Add our new Interceptor class to the HTTP Interceptors service provider (and add the HTTP Interceptors service to your app if needed). // src/app/app.module.ts import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { TokenInterceptor } from './../auth/token.interceptor’; @NgModule({ bootstrap: [AppComponent], imports: [...], providers: [ { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true } ] }) export class AppModule {} 14
  • 15. Angular HTTP Interceptor Design Pattern – Step 4 Now when we make any HTTP request, the user’s token will be attached automatically. Our TokenInterceptor was added to the HTTP Interceptors array by making the existing HTTP_Interceptors array use our new class. Now the application-scoped HTTP Interceptors service will use our new class, and the Authorization Header with our Bearer Token will be added to every HTTP Request. 15