SlideShare a Scribd company logo
1 of 9
Babel Coder
AUTHENTICATION /
AUTHORIZATION
Babel Coder
AUTHENTICATION & AUTHORIZATION
Authentication
Articles
Authorization
Authentication is the process of ascertaining that somebody really is who he claims
to be.
Authorization refers to rules that determine who is allowed to do what.
Babel Coder
SESSIONS
A
B
C
423432g2f3j23
g23hg42j4h2k3
jh3g56jh5gj333
423432g2f3j23
g23hg42j4h2k3
jh3g56jh5gj333
423432g2f3j23
g23hg42j4h2k3
jh3g56jh5gj333
stateful token stateless token
Babel Coder
JSON WEB TOKEN
<HEADER>.<PAYLOAD>.<SIGNATURE>
JSON Web Token (JWT) is a JSON-based open standard (RFC 7519) for
creating access tokens that assert some number of claims.
Header
{
"alg": "HS256",
"typ": "JWT"
}
base64UrlEncode eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
Payload
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
base64UrlEncode
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI
6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9
Signature
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret
)
Babel Coder
PAYLOAD
Subject
sub This holds the identifier for the token
Issued At
iat When the token was issued (unix timestamp)
Expiry
exp The token expiry date (unix timestamp)
Issuer
iss The issuer of the token
Babel Coder
AUTH ROUTING
router.route('/auth');
router.post('/auth/sign-up', authController.register);
router.post('/auth/sign-in', authController.login);
router.get('/auth/profile', authController.getProfile);
router.patch('/auth/profile', authController.updateProfile);
router.post('/auth/refresh-token', authController.refreshToken);
router.delete('/auth/sign-out', authController.signOut);
Babel Coder
MIDDLEWARE
import { RequestHandler } from 'express';
import passport from 'passport';
import { compose } from 'compose-middleware';
export const signUp = passport.authenticate('sign-up', { session: false });
export const signIn = passport.authenticate('sign-in', { session: false });
export const accessToken: RequestHandler = compose([
passport.initialize({ userProperty: 'userFromToken' }),
passport.authenticate('access-token', {
session: false,
}),
]);
export const refreshToken = passport.authenticate('refresh-token', {
session: false,
});
import { RequestHandler } from 'express';
import { Role } from '../entity/User';
import { HTTP_STATUSES } from '../helper/http-statuses';
import { accessToken } from './authenticator';
export const permitFor = (roles: Role | Role[]) => [
accessToken,
authorizer(roles),
];
const authorizer =
(roles: Role | Role[]): RequestHandler =>
(req, res, next) => {
const role = req.userFromToken.role;
if (Array.isArray(roles) && roles.includes(role)) return next();
if (roles === role) return next();
res.sendStatus(HTTP_STATUSES.FORBIDDEN);
};
export default authorizer;
Authenticator Authorizer
Babel Coder
CONTROLLER
const upload = multer({ dest: path.join(__dirname, 'uploads', 'users') });
export const register: RequestHandler[] = [
bodyValidator(SignUpFormDto),
authenticator.signUp,
async (req, res) => {
res.status(HTTP_STATUSES.CREATED).json(new UserResponseDto(req.user));
},
];
export const login: RequestHandler[] = [
authenticator.signIn,
async (req, res, next) => {
const user = req.user;
req.login(user, { session: false }, async (error) => {
if (error) return next(error);
const { accessToken, refreshToken } = authService.signAndSaveTokens(user);
return res
.status(HTTP_STATUSES.CREATED)
.json(new LoginResponseDto(accessToken, refreshToken, user));
});
},
];
export const getProfile: RequestHandler[] = [
authenticator.accessToken,
async (req, res) => {
const user = await userService.getUserById(req.userFromToken.id);
res.json(new UserResponseDto(user));
},
];
export const updateProfile: RequestHandler[] = [
upload.single('avatar'),
authenticator.accessToken,
bodyValidator(UpdateProfileFormDto),
async (req, res) => {
const payload: UpdateProfileFormDto & { avatar: string } = req.body;
if (req.file) payload.avatar = `uploads/users/${req.file.filename}`;
const user = await userService.updateUser(req.userFromToken.id, payload);
res.json(new UserResponseDto(user));
},
];
export const refreshToken: RequestHandler[] = [
bodyValidator(RefreshTokenFormDto),
authenticator.refreshToken,
async (req, res) => {
const user = req.user;
const { accessToken, refreshToken } = authService.signAndSaveTokens(user);
return res
.status(HTTP_STATUSES.CREATED)
.json(new LoginResponseDto(accessToken, refreshToken, user));
},
];
export const signOut: RequestHandler[] = [
authenticator.accessToken,
async (req, res) => {
const user = req.user;
await authService.signOut(user);
res.json(new LoginResponseDto(null, null, user));
},
];
Babel Coder
SERVICE
const userRepository = AppDataSource.getRepository(User);
export const signAndSaveTokens = (user: User) => {
const accessToken = jwt.sign(
{ sub: user.id, role: user.role },
config.secretKey.accessToken,
{ expiresIn: config.expiresIn.accessToken }
);
const refreshToken = jwt.sign(
{ sub: user.id },
config.secretKey.accessToken,
{ expiresIn: config.expiresIn.refreshToken }
);
user.refreshToken = refreshToken;
userRepository.save(user);
return { accessToken, refreshToken };
};
export const signOut = async (user: User) => {
user.refreshToken = null;
await userRepository.save(user);
};
const userRepository = AppDataSource.getRepository(User);
export const getUserById = (id: number) => {
return userRepository.findOneBy({ id });
};
export const updateUser = async (id: number, form: Partial<User>) => {
const currentUser = await getUserById(id);
const currentAvatar = currentUser.avatar;
const user = userRepository.create(form);
if (user.password) await user.hashPassword();
await userRepository.update(id, user);
if (user.avatar) {
fs.rm(path.join(__dirname, currentAvatar), { force: true });
}
return getUserById(id);
};
auth user

More Related Content

Similar to auth.pdf

Entity framework db model的驗證機制 20130914
Entity framework db model的驗證機制 20130914Entity framework db model的驗證機制 20130914
Entity framework db model的驗證機制 20130914LearningTech
 
Building secure applications with keycloak
Building secure applications with keycloak Building secure applications with keycloak
Building secure applications with keycloak Abhishek Koserwal
 
Open Source Ajax Solution @OSDC.tw 2009
Open Source Ajax  Solution @OSDC.tw 2009Open Source Ajax  Solution @OSDC.tw 2009
Open Source Ajax Solution @OSDC.tw 2009Robbie Cheng
 
MongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB
 
Pocket Authentication with OAuth on Firefox OS
Pocket Authentication with OAuth on Firefox OSPocket Authentication with OAuth on Firefox OS
Pocket Authentication with OAuth on Firefox OSChih-Hsuan Kuo
 
ChromeからMacBookのTouchIDでWebAuthenticationする ~Idance vol1~
ChromeからMacBookのTouchIDでWebAuthenticationする ~Idance vol1~ChromeからMacBookのTouchIDでWebAuthenticationする ~Idance vol1~
ChromeからMacBookのTouchIDでWebAuthenticationする ~Idance vol1~5 6
 
I Don't Care About Security
I Don't Care About Security I Don't Care About Security
I Don't Care About Security Joel Lord
 
W3C Web Authentication - #idcon vol.24
W3C Web Authentication - #idcon vol.24W3C Web Authentication - #idcon vol.24
W3C Web Authentication - #idcon vol.24Nov Matake
 
Getting Started with FIDO2
Getting Started with FIDO2Getting Started with FIDO2
Getting Started with FIDO2FIDO Alliance
 
The web beyond "usernames & passwords"
The web beyond "usernames & passwords"The web beyond "usernames & passwords"
The web beyond "usernames & passwords"Francois Marier
 
Securing your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris KelloggSecuring your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris KelloggStreamNative
 
"Auth for React.js APP", Nikita Galkin
"Auth for React.js APP", Nikita Galkin"Auth for React.js APP", Nikita Galkin
"Auth for React.js APP", Nikita GalkinFwdays
 
RoadSec 2017 - Trilha AppSec - APIs Authorization
RoadSec 2017 - Trilha AppSec - APIs AuthorizationRoadSec 2017 - Trilha AppSec - APIs Authorization
RoadSec 2017 - Trilha AppSec - APIs AuthorizationErick Belluci Tedeschi
 
OWASP San Diego Training Presentation
OWASP San Diego Training PresentationOWASP San Diego Training Presentation
OWASP San Diego Training Presentationowaspsd
 
使用 Passkeys 打造無密碼驗證服務
使用 Passkeys 打造無密碼驗證服務使用 Passkeys 打造無密碼驗證服務
使用 Passkeys 打造無密碼驗證服務升煌 黃
 
BlockChain implementation by python
BlockChain implementation by pythonBlockChain implementation by python
BlockChain implementation by pythonwonyong hwang
 

Similar to auth.pdf (20)

One tool to rule them all
One tool to rule them allOne tool to rule them all
One tool to rule them all
 
Entity framework db model的驗證機制 20130914
Entity framework db model的驗證機制 20130914Entity framework db model的驗證機制 20130914
Entity framework db model的驗證機制 20130914
 
IdM and AC
IdM and ACIdM and AC
IdM and AC
 
Building secure applications with keycloak
Building secure applications with keycloak Building secure applications with keycloak
Building secure applications with keycloak
 
Open Source Ajax Solution @OSDC.tw 2009
Open Source Ajax  Solution @OSDC.tw 2009Open Source Ajax  Solution @OSDC.tw 2009
Open Source Ajax Solution @OSDC.tw 2009
 
MongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB Stitch Tutorial
MongoDB Stitch Tutorial
 
Pocket Authentication with OAuth on Firefox OS
Pocket Authentication with OAuth on Firefox OSPocket Authentication with OAuth on Firefox OS
Pocket Authentication with OAuth on Firefox OS
 
ERRest
ERRestERRest
ERRest
 
ChromeからMacBookのTouchIDでWebAuthenticationする ~Idance vol1~
ChromeからMacBookのTouchIDでWebAuthenticationする ~Idance vol1~ChromeからMacBookのTouchIDでWebAuthenticationする ~Idance vol1~
ChromeからMacBookのTouchIDでWebAuthenticationする ~Idance vol1~
 
I Don't Care About Security
I Don't Care About Security I Don't Care About Security
I Don't Care About Security
 
W3C Web Authentication - #idcon vol.24
W3C Web Authentication - #idcon vol.24W3C Web Authentication - #idcon vol.24
W3C Web Authentication - #idcon vol.24
 
Getting Started with FIDO2
Getting Started with FIDO2Getting Started with FIDO2
Getting Started with FIDO2
 
The web beyond "usernames & passwords"
The web beyond "usernames & passwords"The web beyond "usernames & passwords"
The web beyond "usernames & passwords"
 
Securing your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris KelloggSecuring your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris Kellogg
 
"Auth for React.js APP", Nikita Galkin
"Auth for React.js APP", Nikita Galkin"Auth for React.js APP", Nikita Galkin
"Auth for React.js APP", Nikita Galkin
 
RoadSec 2017 - Trilha AppSec - APIs Authorization
RoadSec 2017 - Trilha AppSec - APIs AuthorizationRoadSec 2017 - Trilha AppSec - APIs Authorization
RoadSec 2017 - Trilha AppSec - APIs Authorization
 
OWASP San Diego Training Presentation
OWASP San Diego Training PresentationOWASP San Diego Training Presentation
OWASP San Diego Training Presentation
 
meet.js - QooXDoo
meet.js - QooXDoomeet.js - QooXDoo
meet.js - QooXDoo
 
使用 Passkeys 打造無密碼驗證服務
使用 Passkeys 打造無密碼驗證服務使用 Passkeys 打造無密碼驗證服務
使用 Passkeys 打造無密碼驗證服務
 
BlockChain implementation by python
BlockChain implementation by pythonBlockChain implementation by python
BlockChain implementation by python
 

More from NuttavutThongjor1

Intro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdf
Intro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdf
Intro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdfNuttavutThongjor1
 
10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf
10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf
10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdfNuttavutThongjor1
 
9 logging and monitoring.pdf 9 logging and monitoring.pdf
9 logging and monitoring.pdf 9 logging and monitoring.pdf9 logging and monitoring.pdf 9 logging and monitoring.pdf
9 logging and monitoring.pdf 9 logging and monitoring.pdfNuttavutThongjor1
 
8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdfNuttavutThongjor1
 
7 cicd.pdf 7 cicd.pdf 7 cicd.pdf 7 cicd.pdf
7 cicd.pdf 7 cicd.pdf 7 cicd.pdf 7 cicd.pdf7 cicd.pdf 7 cicd.pdf 7 cicd.pdf 7 cicd.pdf
7 cicd.pdf 7 cicd.pdf 7 cicd.pdf 7 cicd.pdfNuttavutThongjor1
 
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdfNuttavutThongjor1
 
5 Kubernetes.pdf 5 Kubernetes.pdf 5 Kubernetes.pdf
5 Kubernetes.pdf 5 Kubernetes.pdf 5 Kubernetes.pdf5 Kubernetes.pdf 5 Kubernetes.pdf 5 Kubernetes.pdf
5 Kubernetes.pdf 5 Kubernetes.pdf 5 Kubernetes.pdfNuttavutThongjor1
 
4 Docker.pdf 4 Docker.pdf 4 Docker.pdf 4 Docker.pdf
4 Docker.pdf 4 Docker.pdf 4 Docker.pdf 4 Docker.pdf4 Docker.pdf 4 Docker.pdf 4 Docker.pdf 4 Docker.pdf
4 Docker.pdf 4 Docker.pdf 4 Docker.pdf 4 Docker.pdfNuttavutThongjor1
 
3 Microservices.pdf 3 Microservices 3 Microservices.pdf.pdf
3 Microservices.pdf 3 Microservices 3 Microservices.pdf.pdf3 Microservices.pdf 3 Microservices 3 Microservices.pdf.pdf
3 Microservices.pdf 3 Microservices 3 Microservices.pdf.pdfNuttavutThongjor1
 
2 เทคโนโลยี cloud computing.pdf 2 เทคโนโลยี cloud computing.pdf
2 เทคโนโลยี cloud computing.pdf 2 เทคโนโลยี cloud computing.pdf2 เทคโนโลยี cloud computing.pdf 2 เทคโนโลยี cloud computing.pdf
2 เทคโนโลยี cloud computing.pdf 2 เทคโนโลยี cloud computing.pdfNuttavutThongjor1
 
1 devops คืออะไร.pdf 1 devops คืออะไร.pdf
1 devops คืออะไร.pdf 1 devops คืออะไร.pdf1 devops คืออะไร.pdf 1 devops คืออะไร.pdf
1 devops คืออะไร.pdf 1 devops คืออะไร.pdfNuttavutThongjor1
 
angular fundamentals.pdf angular fundamentals.pdf
angular fundamentals.pdf angular fundamentals.pdfangular fundamentals.pdf angular fundamentals.pdf
angular fundamentals.pdf angular fundamentals.pdfNuttavutThongjor1
 
mean stack mean stack mean stack mean stack
mean stack mean stack  mean stack  mean stackmean stack mean stack  mean stack  mean stack
mean stack mean stack mean stack mean stackNuttavutThongjor1
 

More from NuttavutThongjor1 (20)

Intro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdf
Intro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdf
Intro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdf
 
10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf
10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf
10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf
 
9 logging and monitoring.pdf 9 logging and monitoring.pdf
9 logging and monitoring.pdf 9 logging and monitoring.pdf9 logging and monitoring.pdf 9 logging and monitoring.pdf
9 logging and monitoring.pdf 9 logging and monitoring.pdf
 
8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
 
7 cicd.pdf 7 cicd.pdf 7 cicd.pdf 7 cicd.pdf
7 cicd.pdf 7 cicd.pdf 7 cicd.pdf 7 cicd.pdf7 cicd.pdf 7 cicd.pdf 7 cicd.pdf 7 cicd.pdf
7 cicd.pdf 7 cicd.pdf 7 cicd.pdf 7 cicd.pdf
 
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf
 
5 Kubernetes.pdf 5 Kubernetes.pdf 5 Kubernetes.pdf
5 Kubernetes.pdf 5 Kubernetes.pdf 5 Kubernetes.pdf5 Kubernetes.pdf 5 Kubernetes.pdf 5 Kubernetes.pdf
5 Kubernetes.pdf 5 Kubernetes.pdf 5 Kubernetes.pdf
 
4 Docker.pdf 4 Docker.pdf 4 Docker.pdf 4 Docker.pdf
4 Docker.pdf 4 Docker.pdf 4 Docker.pdf 4 Docker.pdf4 Docker.pdf 4 Docker.pdf 4 Docker.pdf 4 Docker.pdf
4 Docker.pdf 4 Docker.pdf 4 Docker.pdf 4 Docker.pdf
 
3 Microservices.pdf 3 Microservices 3 Microservices.pdf.pdf
3 Microservices.pdf 3 Microservices 3 Microservices.pdf.pdf3 Microservices.pdf 3 Microservices 3 Microservices.pdf.pdf
3 Microservices.pdf 3 Microservices 3 Microservices.pdf.pdf
 
2 เทคโนโลยี cloud computing.pdf 2 เทคโนโลยี cloud computing.pdf
2 เทคโนโลยี cloud computing.pdf 2 เทคโนโลยี cloud computing.pdf2 เทคโนโลยี cloud computing.pdf 2 เทคโนโลยี cloud computing.pdf
2 เทคโนโลยี cloud computing.pdf 2 เทคโนโลยี cloud computing.pdf
 
1 devops คืออะไร.pdf 1 devops คืออะไร.pdf
1 devops คืออะไร.pdf 1 devops คืออะไร.pdf1 devops คืออะไร.pdf 1 devops คืออะไร.pdf
1 devops คืออะไร.pdf 1 devops คืออะไร.pdf
 
angular fundamentals.pdf angular fundamentals.pdf
angular fundamentals.pdf angular fundamentals.pdfangular fundamentals.pdf angular fundamentals.pdf
angular fundamentals.pdf angular fundamentals.pdf
 
mean stack mean stack mean stack mean stack
mean stack mean stack  mean stack  mean stackmean stack mean stack  mean stack  mean stack
mean stack mean stack mean stack mean stack
 
pinia.pdf
pinia.pdfpinia.pdf
pinia.pdf
 
nuxt-rendering-modes.pdf
nuxt-rendering-modes.pdfnuxt-rendering-modes.pdf
nuxt-rendering-modes.pdf
 
zustand.pdf
zustand.pdfzustand.pdf
zustand.pdf
 
tanstack-query.pdf
tanstack-query.pdftanstack-query.pdf
tanstack-query.pdf
 
nuxt-fundamentals.pdf
nuxt-fundamentals.pdfnuxt-fundamentals.pdf
nuxt-fundamentals.pdf
 
vue-components.pdf
vue-components.pdfvue-components.pdf
vue-components.pdf
 
vue-reactivity.pdf
vue-reactivity.pdfvue-reactivity.pdf
vue-reactivity.pdf
 

Recently uploaded

An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfSanaAli374401
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 

Recently uploaded (20)

Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 

auth.pdf

  • 2. Babel Coder AUTHENTICATION & AUTHORIZATION Authentication Articles Authorization Authentication is the process of ascertaining that somebody really is who he claims to be. Authorization refers to rules that determine who is allowed to do what.
  • 4. Babel Coder JSON WEB TOKEN <HEADER>.<PAYLOAD>.<SIGNATURE> JSON Web Token (JWT) is a JSON-based open standard (RFC 7519) for creating access tokens that assert some number of claims. Header { "alg": "HS256", "typ": "JWT" } base64UrlEncode eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 Payload { "sub": "1234567890", "name": "John Doe", "admin": true } base64UrlEncode eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI 6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9 Signature HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret )
  • 5. Babel Coder PAYLOAD Subject sub This holds the identifier for the token Issued At iat When the token was issued (unix timestamp) Expiry exp The token expiry date (unix timestamp) Issuer iss The issuer of the token
  • 6. Babel Coder AUTH ROUTING router.route('/auth'); router.post('/auth/sign-up', authController.register); router.post('/auth/sign-in', authController.login); router.get('/auth/profile', authController.getProfile); router.patch('/auth/profile', authController.updateProfile); router.post('/auth/refresh-token', authController.refreshToken); router.delete('/auth/sign-out', authController.signOut);
  • 7. Babel Coder MIDDLEWARE import { RequestHandler } from 'express'; import passport from 'passport'; import { compose } from 'compose-middleware'; export const signUp = passport.authenticate('sign-up', { session: false }); export const signIn = passport.authenticate('sign-in', { session: false }); export const accessToken: RequestHandler = compose([ passport.initialize({ userProperty: 'userFromToken' }), passport.authenticate('access-token', { session: false, }), ]); export const refreshToken = passport.authenticate('refresh-token', { session: false, }); import { RequestHandler } from 'express'; import { Role } from '../entity/User'; import { HTTP_STATUSES } from '../helper/http-statuses'; import { accessToken } from './authenticator'; export const permitFor = (roles: Role | Role[]) => [ accessToken, authorizer(roles), ]; const authorizer = (roles: Role | Role[]): RequestHandler => (req, res, next) => { const role = req.userFromToken.role; if (Array.isArray(roles) && roles.includes(role)) return next(); if (roles === role) return next(); res.sendStatus(HTTP_STATUSES.FORBIDDEN); }; export default authorizer; Authenticator Authorizer
  • 8. Babel Coder CONTROLLER const upload = multer({ dest: path.join(__dirname, 'uploads', 'users') }); export const register: RequestHandler[] = [ bodyValidator(SignUpFormDto), authenticator.signUp, async (req, res) => { res.status(HTTP_STATUSES.CREATED).json(new UserResponseDto(req.user)); }, ]; export const login: RequestHandler[] = [ authenticator.signIn, async (req, res, next) => { const user = req.user; req.login(user, { session: false }, async (error) => { if (error) return next(error); const { accessToken, refreshToken } = authService.signAndSaveTokens(user); return res .status(HTTP_STATUSES.CREATED) .json(new LoginResponseDto(accessToken, refreshToken, user)); }); }, ]; export const getProfile: RequestHandler[] = [ authenticator.accessToken, async (req, res) => { const user = await userService.getUserById(req.userFromToken.id); res.json(new UserResponseDto(user)); }, ]; export const updateProfile: RequestHandler[] = [ upload.single('avatar'), authenticator.accessToken, bodyValidator(UpdateProfileFormDto), async (req, res) => { const payload: UpdateProfileFormDto & { avatar: string } = req.body; if (req.file) payload.avatar = `uploads/users/${req.file.filename}`; const user = await userService.updateUser(req.userFromToken.id, payload); res.json(new UserResponseDto(user)); }, ]; export const refreshToken: RequestHandler[] = [ bodyValidator(RefreshTokenFormDto), authenticator.refreshToken, async (req, res) => { const user = req.user; const { accessToken, refreshToken } = authService.signAndSaveTokens(user); return res .status(HTTP_STATUSES.CREATED) .json(new LoginResponseDto(accessToken, refreshToken, user)); }, ]; export const signOut: RequestHandler[] = [ authenticator.accessToken, async (req, res) => { const user = req.user; await authService.signOut(user); res.json(new LoginResponseDto(null, null, user)); }, ];
  • 9. Babel Coder SERVICE const userRepository = AppDataSource.getRepository(User); export const signAndSaveTokens = (user: User) => { const accessToken = jwt.sign( { sub: user.id, role: user.role }, config.secretKey.accessToken, { expiresIn: config.expiresIn.accessToken } ); const refreshToken = jwt.sign( { sub: user.id }, config.secretKey.accessToken, { expiresIn: config.expiresIn.refreshToken } ); user.refreshToken = refreshToken; userRepository.save(user); return { accessToken, refreshToken }; }; export const signOut = async (user: User) => { user.refreshToken = null; await userRepository.save(user); }; const userRepository = AppDataSource.getRepository(User); export const getUserById = (id: number) => { return userRepository.findOneBy({ id }); }; export const updateUser = async (id: number, form: Partial<User>) => { const currentUser = await getUserById(id); const currentAvatar = currentUser.avatar; const user = userRepository.create(form); if (user.password) await user.hashPassword(); await userRepository.update(id, user); if (user.avatar) { fs.rm(path.join(__dirname, currentAvatar), { force: true }); } return getUserById(id); }; auth user