SlideShare a Scribd company logo
Testing
AngularJS
Security
José Manuel Ortega
@jmortegac
iNDEX
• Authenticate users API
• Securing Admin pages
• CSRF,XSS Prevention
• Sanitize Module
• Security Audit Tools
• OWASP
Authenticate users API
POST /register
POST /login
POST /logout
GET /status # returns 401 or the authenticated user
Login controller
Session service
Represent the user’s session
Session service
Session management global config
$rootScope.$on('Auth:Required', function() {
$location.path('/login');
});
$rootScope.$on('Auth:Login', function() {
$location.path('/');
});
$rootScope.$on('Auth:Logout', function() {
StorageService.clear(); // clear user info
$rootScope.$broadcast('Auth:Required');
});
Authentication Interceptor config
factory('AuthInterceptor', ['$q', '$rootScope', function($q, $rootScope) {
return {
'responseError': function(rejection) {
if (rejection.status === 401) {
$rootScope.$broadcast('Auth:Required');
}
return $q.reject(rejection);
}
}
}])
Authentication controller
Auth Service
Securing admin pages
.service("AuthService", function() {
var data = {};
data.checkAuth = function() {return true;}
return data;
})
.when("/admin", {
templateUrl: “admin.html",
controller: “adminController",
resolve: {
checkAuth: function(AuthService){
return AuthService.checkAuth();
}
}
})
Securing admin pages
controller(“adminController", function ($scope, checkAuth) {
$scope.isAuthenticated = checkAuth;
});
Browser risks
• Cross Site Scripting(XSS)
• Cross-Site Request Forgery(CSRF)
CSRF Prevention
• XSRF token
• Inject in HTTP Forms
• Protected from Cross-Site Request Forgery attack
• XSRF-TOKEN → HTTP HEADER X-XSRF-TOKEN
• Set a domain cookie in the request
• Validate the header with the content the cookie
• Used for authorize requests from the user
CSRF Prevention
XSRF Token
XSRF Token
• When using $http ,Angular automatically look for
a cookie called XSRF-TOKEN
• If this cookie is found,when make a request add
this information in the request-header
• This header is sent to the server,at the token can
be validated
• The API can verify that the token is correct for the
current user
• Server sends success or failure
Module CSURF
app.js
var csrf = require("csurf"); //require package
app.use(csrf()); //initialize
//middleware for every http request
app.use(function(req, res, next) {
res.cookie("XSRF-TOKEN", req.csrfToken());
next();});
CSRF Interceptor
'responseError': function(rejection) {
var statusCode = rejection.status;
var config = rejection.config;
// Check if XSRF token is invalid
if (statusCode === 403 && rejection.data === 'XsrfToken.Invalid') {
// Handle invalid token
}
return $q.reject(rejection);
}
}
Http Interceptor - Handle invalid token responses
CSRF Interceptor
var deferred = $q.defer();
var req = {config: config, deferred: deferred}
if (angular.isUndefined($rootScope.pendingRequests)) {
$rootScope.pendingRequests = [];
}
$rootScope.pendingRequests.push(req);
// Raise an event
$rootScope.$broadcast('XsrfToken:Invalid');
return deferred.promise;
Store the original request and the promise
CSRF Interceptor
$rootScope.$on('XsrfToken:Invalid', function() {
Security.status().then(function() {
$rootScope.$broadcast('XsrfToken:Valid');
});
});
Store the original request and the promise
CSRF Interceptor
$rootScope.$on('XsrfToken:Valid', function() {
var i, requests = $rootScope.pendingRequests ?
$rootScope.pendingRequests : [];
for (i = 0; i < requests.length; i++) {
retry(requests.pop());
}
function retry(req) {
$http(req.config).then(function(response) {
req.deferred.resolve(response);
});
}
});
Resume the pending requests
XSS Protection
For XSS protection, AngularJS uses Strict Contextual Escaping (SCE). We
need to include $sce service to the code. SCE defines a trust in different
context.
Since 1.3, the HTML compiler will escape all {{}} & ngbind by
default
https://www.ng-book.com/p/Security
http://java.dzone.com/articles/angularjs-how-handle-xss
Sanitize
• The ngSanitize module provides functionality to sanitize
HTML.
• Avoid Cross Site Scripting(XSS) attacks
• Requires angular-sanitize.js
• Provides ng-bind-html directive for sanitize HTML filtering
the javascript code
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-
sanitize.js"></script>
ngSanitize && SCE
• The input is sanitized by parsing the HTML into tokens.
• All safe tokens are then serialized back to properly
escaped html string
• SCE(Strict Contextual Escaping) is a mode in wich
AngularJS requires binding in certain contexts to result
in a value that is marked as safe to use for that context.
Strict Contextual Escaping Service
Strict Contextual Escaping Service
var data ='<b onmouseover="alert('over')">trust
me</b>:<script>alert("XSS");</script> <xss>XSS</xss>';
$scope.untrusted = data;
$scope.sanitized = $sanitize(data);
$scope.trusted = $sce.trustAsHtml(data);
{{ untrusted }}
<span ng-bind-html="sanitized"></span>
<span ng-bind-html="trusted"></span>
ng-bind-html .vs. ng-bind
<div ng-bind-html="to_trusted(msg)">
</div>
• ng-bind-htmlAutomatically uses $sanitize
• <p ng-bind="msg"></p> Hello, <b>World</b>!
• <p ng-bind-html="msg"></p> Hello, World!
Retire.js
• Detecting components and JavaScript libraries with
known vulnerabilities
• https://raw.githubusercontent.com/RetireJS/retire.js/m
aster/repository/jsrepository.json
• Retire.js has these parts:
• A command line scanner
• A grunt plugin
• A Chrome plugin
• A Firefox plugin
• Burp and OWASP Zap plugin
Build a secure HTTPS Server
var https = require('https');
var privateKey =
fs.readFileSync('cert/privatekey.pem').toString();
var certificate =
fs.readFileSync('cert/certificate.pem').toString();
var credentials = {key: privateKey, cert: certificate};
var secureServer = https.createServer(credentials, app);
secureServer.listen(config.server.securePort); //443
Build a secure HTTPS Server
https-redirect-server
https://www.npmjs.com/package/https-redirect-server
A node module to redirect all traffic to https and a
secure port.
Security Audit Tools
Securing Headers
Security Audit Tools
Security Audit Tools
Security Audit Tools
JWT
• JSON Web Token
• Avoid CSRF and XSS
• angular-jwt
JWT
• Store the token from service response
• Sending the token at each request with interceptor
$http(...).then(function(response) {
currentToken.jwt =response.data.access_token;
}
angular.module('myApp')
.config(function ($httpProvider,jwtInterceptorProvider) {
jwtInterceptorProvider.tokenGetter=['currentToken',function(current
Token) {return currentToken.jwt;}];
$httpProvider.interceptors.push('jwtInterceptor');
});
OWASP
• Open Web Application Security Project
• Online community dedicated to web application security
• Identify Vulnerabilities
• Document Best Practices
• Repository with use cases
• https://github.com/hakanson/ng-owasp
Recommendations
• Access control input validation and security decisions
must be made on the server.
• Handle untrusted data with care
• Use contextual encoding and avoid building code from
strings.
• Protect your services
• Learn how to use security HTTP headers
Conclusions
• Angular is a purely client side framework
• There are risks in the client that are discret to the
network and server
• The client and the network are not in your control!
• Protect the server!
Links & References
https://docs.angularjs.org/api/ng/service/$sce
https://docs.angularjs.org/guide/security
https://docs.angularjs.org/api/ngSanitize
https://code.google.com/p/mustache-security/wiki/AngularJS.wiki
https://www.ng-book.com/p/Security
https://github.com/fnakstad/angular-client-side-auth
https://github.com/auth0/angular-jwt
http://retirejs.github.io/retire.js
https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project
Youtube videos
Security in the world of JS frameworks
https://www.youtube.com/watch?v=4Qs5mqa4ioU
Top 10 Security Risks for AngularJS Applications
https://www.youtube.com/watch?v=6uloYE87pkk
JS Security - A Pentesters Perspective
https://www.youtube.com/watch?v=LVamMYljS4Q

More Related Content

What's hot (20)

PDF
HTTP For the Good or the Bad
Xavier Mertens
 
PDF
Pycon - Python for ethical hackers
Mohammad Reza Kamalifard
 
PDF
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Zend by Rogue Wave Software
 
PDF
Two scoops of Django - Security Best Practices
Spin Lai
 
PPTX
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Ivan Piskunov
 
PDF
Waf.js: How to Protect Web Applications using JavaScript
Denis Kolegov
 
PDF
Logstash for SEO: come monitorare i Log del Web Server in realtime
Andrea Cardinale
 
PDF
End to end web security
George Boobyer
 
PDF
HTTP For the Good or the Bad - FSEC Edition
Xavier Mertens
 
PDF
"Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ...
PROIDEA
 
PPTX
Hack ASP.NET website
Positive Hack Days
 
PDF
Code obfuscation, php shells & more
Mattias Geniar
 
PDF
Threat stack aws
Jen Andre
 
PPTX
[OPD 2019] Side-Channels on the Web:
Attacks and Defenses
OWASP
 
PDF
Bootstrapping multidc observability stack
Bram Vogelaar
 
PDF
What should a hacker know about WebDav?
Mikhail Egorov
 
PPTX
Mitigating CSRF with two lines of codes
Minhaz A V
 
PDF
Static Typing in Vault
GlynnForrest
 
PDF
Introduction to Flask Micro Framework
Mohammad Reza Kamalifard
 
PDF
Practical django secuirty
Andy Dai
 
HTTP For the Good or the Bad
Xavier Mertens
 
Pycon - Python for ethical hackers
Mohammad Reza Kamalifard
 
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Zend by Rogue Wave Software
 
Two scoops of Django - Security Best Practices
Spin Lai
 
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Ivan Piskunov
 
Waf.js: How to Protect Web Applications using JavaScript
Denis Kolegov
 
Logstash for SEO: come monitorare i Log del Web Server in realtime
Andrea Cardinale
 
End to end web security
George Boobyer
 
HTTP For the Good or the Bad - FSEC Edition
Xavier Mertens
 
"Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ...
PROIDEA
 
Hack ASP.NET website
Positive Hack Days
 
Code obfuscation, php shells & more
Mattias Geniar
 
Threat stack aws
Jen Andre
 
[OPD 2019] Side-Channels on the Web:
Attacks and Defenses
OWASP
 
Bootstrapping multidc observability stack
Bram Vogelaar
 
What should a hacker know about WebDav?
Mikhail Egorov
 
Mitigating CSRF with two lines of codes
Minhaz A V
 
Static Typing in Vault
GlynnForrest
 
Introduction to Flask Micro Framework
Mohammad Reza Kamalifard
 
Practical django secuirty
Andy Dai
 

Similar to Angular js security (20)

PPTX
JWT Authentication with AngularJS
robertjd
 
PDF
Secure my ng-app
M A Hossain Tonu
 
PDF
Reviewing AngularJS
Lewis Ardern
 
PPTX
Is your app secure
Chathuranga Bandara
 
PDF
OWASP London - So you thought you were safe using AngularJS.. Think again!
Lewis Ardern
 
PPTX
Angular Tutorial Freshers and Experienced
rajkamaltibacademy
 
PPTX
Building Secure User Interfaces With JWTs
robertjd
 
PDF
Securing your AngularJS Application
Philippe De Ryck
 
PDF
Security in Node.JS and Express:
Petros Demetrakopoulos
 
PDF
The Art of AngularJS - DeRailed 2014
Matt Raible
 
PPTX
How Secure Is AngularJS?
Ksenia Peguero
 
PPTX
Javascript Security - Three main methods of defending your MEAN stack
Ran Bar-Zik
 
PPTX
Building Secure User Interfaces With JWTs (JSON Web Tokens)
Stormpath
 
PDF
Api security-testing
n|u - The Open Security Community
 
PPTX
CBSecurity 3 - Secure Your ColdBox Applications
Ortus Solutions, Corp
 
PDF
An Abusive Relationship with AngularJS by Mario Heiderich - CODE BLUE 2015
CODE BLUE
 
PDF
An Abusive Relationship with AngularJS
Mario Heiderich
 
PDF
Neoito — Secure coding practices
Neoito
 
PPTX
AngularJS Services
Eyal Vardi
 
PDF
AppSec Tel Aviv - OWASP Top 10 For JavaScript Developers
Lewis Ardern
 
JWT Authentication with AngularJS
robertjd
 
Secure my ng-app
M A Hossain Tonu
 
Reviewing AngularJS
Lewis Ardern
 
Is your app secure
Chathuranga Bandara
 
OWASP London - So you thought you were safe using AngularJS.. Think again!
Lewis Ardern
 
Angular Tutorial Freshers and Experienced
rajkamaltibacademy
 
Building Secure User Interfaces With JWTs
robertjd
 
Securing your AngularJS Application
Philippe De Ryck
 
Security in Node.JS and Express:
Petros Demetrakopoulos
 
The Art of AngularJS - DeRailed 2014
Matt Raible
 
How Secure Is AngularJS?
Ksenia Peguero
 
Javascript Security - Three main methods of defending your MEAN stack
Ran Bar-Zik
 
Building Secure User Interfaces With JWTs (JSON Web Tokens)
Stormpath
 
Api security-testing
n|u - The Open Security Community
 
CBSecurity 3 - Secure Your ColdBox Applications
Ortus Solutions, Corp
 
An Abusive Relationship with AngularJS by Mario Heiderich - CODE BLUE 2015
CODE BLUE
 
An Abusive Relationship with AngularJS
Mario Heiderich
 
Neoito — Secure coding practices
Neoito
 
AngularJS Services
Eyal Vardi
 
AppSec Tel Aviv - OWASP Top 10 For JavaScript Developers
Lewis Ardern
 
Ad

More from Jose Manuel Ortega Candel (20)

PDF
Seguridad y auditorías en Modelos grandes del lenguaje (LLM).pdf
Jose Manuel Ortega Candel
 
PDF
Beyond the hype: The reality of AI security.pdf
Jose Manuel Ortega Candel
 
PDF
Seguridad de APIs en Drupal_ herramientas, mejores prácticas y estrategias pa...
Jose Manuel Ortega Candel
 
PDF
Security and auditing tools in Large Language Models (LLM).pdf
Jose Manuel Ortega Candel
 
PDF
Herramientas de benchmarks para evaluar el rendimiento en máquinas y aplicaci...
Jose Manuel Ortega Candel
 
PDF
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
Jose Manuel Ortega Candel
 
PDF
PyGoat Analizando la seguridad en aplicaciones Django.pdf
Jose Manuel Ortega Candel
 
PDF
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Jose Manuel Ortega Candel
 
PDF
Evolution of security strategies in K8s environments- All day devops
Jose Manuel Ortega Candel
 
PDF
Evolution of security strategies in K8s environments.pdf
Jose Manuel Ortega Candel
 
PDF
Implementing Observability for Kubernetes.pdf
Jose Manuel Ortega Candel
 
PDF
Computación distribuida usando Python
Jose Manuel Ortega Candel
 
PDF
Seguridad en arquitecturas serverless y entornos cloud
Jose Manuel Ortega Candel
 
PDF
Construyendo arquitecturas zero trust sobre entornos cloud
Jose Manuel Ortega Candel
 
PDF
Tips and tricks for data science projects with Python
Jose Manuel Ortega Candel
 
PDF
Sharing secret keys in Docker containers and K8s
Jose Manuel Ortega Candel
 
PDF
Implementing cert-manager in K8s
Jose Manuel Ortega Candel
 
PDF
Python para equipos de ciberseguridad(pycones)
Jose Manuel Ortega Candel
 
PDF
Python para equipos de ciberseguridad
Jose Manuel Ortega Candel
 
PDF
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
Jose Manuel Ortega Candel
 
Seguridad y auditorías en Modelos grandes del lenguaje (LLM).pdf
Jose Manuel Ortega Candel
 
Beyond the hype: The reality of AI security.pdf
Jose Manuel Ortega Candel
 
Seguridad de APIs en Drupal_ herramientas, mejores prácticas y estrategias pa...
Jose Manuel Ortega Candel
 
Security and auditing tools in Large Language Models (LLM).pdf
Jose Manuel Ortega Candel
 
Herramientas de benchmarks para evaluar el rendimiento en máquinas y aplicaci...
Jose Manuel Ortega Candel
 
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
Jose Manuel Ortega Candel
 
PyGoat Analizando la seguridad en aplicaciones Django.pdf
Jose Manuel Ortega Candel
 
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Jose Manuel Ortega Candel
 
Evolution of security strategies in K8s environments- All day devops
Jose Manuel Ortega Candel
 
Evolution of security strategies in K8s environments.pdf
Jose Manuel Ortega Candel
 
Implementing Observability for Kubernetes.pdf
Jose Manuel Ortega Candel
 
Computación distribuida usando Python
Jose Manuel Ortega Candel
 
Seguridad en arquitecturas serverless y entornos cloud
Jose Manuel Ortega Candel
 
Construyendo arquitecturas zero trust sobre entornos cloud
Jose Manuel Ortega Candel
 
Tips and tricks for data science projects with Python
Jose Manuel Ortega Candel
 
Sharing secret keys in Docker containers and K8s
Jose Manuel Ortega Candel
 
Implementing cert-manager in K8s
Jose Manuel Ortega Candel
 
Python para equipos de ciberseguridad(pycones)
Jose Manuel Ortega Candel
 
Python para equipos de ciberseguridad
Jose Manuel Ortega Candel
 
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
Jose Manuel Ortega Candel
 
Ad

Recently uploaded (20)

PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
Biography of Daniel Podor.pdf
Daniel Podor
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
July Patch Tuesday
Ivanti
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Biography of Daniel Podor.pdf
Daniel Podor
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
July Patch Tuesday
Ivanti
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 

Angular js security