flask-jwt-extended Documentation

Size: px
Start display at page:

Download "flask-jwt-extended Documentation"

Transcription

1 flask-jwt-extended Documentation Release vimalloc rlam3 Jun 29, 2018

2

3 Contents 1 Installation 1 2 Basic Usage 3 3 Partially protecting routes 5 4 Storing Data in Access Tokens 7 5 Tokens from Complex Objects 9 6 Complex Objects from Tokens 11 7 Custom Decorators 15 8 Refresh Tokens 17 9 Token Freshness Changing Default Behaviors Changing callback functions Dynamic token expires time Configuration Options General Options: Header Options: Query String Options: Cookie Options: Cross Site Request Forgery Options: Blacklist Options: Blacklist and Token Revoking JWT in Cookies JWT in Query String API Documentation Configuring Flask-JWT-Extended Protected endpoint decorators i

4 15.3 Verify Tokens in Request Utilities Python Module Index 47 ii

5 CHAPTER 1 Installation The easiest way to start working with this extension with pip: $ pip install flask-jwt-extended If you want to use asymmetric (public/private) key signing algorithms, include the asymmetric_crypto extra requirements. $ pip install flask-jwt-extended[asymmetric_crypto] Note that if you are using ZSH (probably other shells as well), you will need to escape the brackets $ pip install flask-jwt-extended\[asymmetric_crypto\] If you prefer to install from source, you can clone this repo and run $ python setup.py install 1

6 2 Chapter 1. Installation

7 CHAPTER 2 Basic Usage In its simplest form, there is not much to using flask_jwt_extended. You use create_access_token() to make new access JWTs, the jwt_required() decorator to protect endpoints, and get_jwt_identity() function to get the identity of a JWT in a protected endpoint. from flask import Flask, jsonify, request from flask_jwt_extended import ( JWTManager, jwt_required, create_access_token, get_jwt_identity ) app = Flask( name ) # Setup the Flask-JWT-Extended extension app.config['jwt_secret_key'] = 'super-secret' jwt = JWTManager(app) # Change this! # Provide a method to create access tokens. The create_access_token() # function is used to actually generate the token, and you can return # it to the caller however you methods=['post']) def login(): if not request.is_json: return jsonify({"msg": "Missing JSON in request"}), 400 username = request.json.get('username', None) password = request.json.get('password', None) if not username: return jsonify({"msg": "Missing username parameter"}), 400 if not password: return jsonify({"msg": "Missing password parameter"}), 400 if username!= 'test' or password!= 'test': return jsonify({"msg": "Bad username or password"}), 401 (continues on next page) 3

8 (continued from previous page) # Identity can be any data that is json serializable access_token = create_access_token(identity=username) return jsonify(access_token=access_token), 200 # Protect a view with jwt_required, which requires a valid access token # in the request to def protected(): # Access the identity of the current user with get_jwt_identity current_user = get_jwt_identity() return jsonify(logged_in_as=current_user), 200 if name == ' main ': app.run() To access a jwt_required protected view, all we have to do is send in the JWT with the request. By default, this is done with an authorization header that looks like: Authorization: Bearer <access_token> We can see this in action using CURL: $ curl { "msg": "Missing Authorization Header" } $ curl -H "Content-Type: application/json" -X POST \ -d '{"username":"test","password":"test"}' { "access_token": "eyjhbgcioijiuzi1niisinr5cci6ikpxvcj9. eyjmcmvzaci6dhj1zswianrpijoizjhmndlmmjutntq4os00nmrjltkyowutztu2y2qxogzhnzrliiwidxnlcl9jbgfpbxmiont vcy0sec61i9prcgirrcbg8e9nv6_wfh2icfgugclkpc" } $ export ACCESS="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. eyjmcmvzaci6dhj1zswianrpijoizjhmndlmmjutntq4os00nmrjltkyowutztu2y2qxogzhnzrliiwidxnlcl9jbgfpbxmiont vcy0sec61i9prcgirrcbg8e9nv6_wfh2icfgugclkpc" $ curl -H "Authorization: Bearer $ACCESS" { "logged_in_as": "test" } NOTE: Remember to change the secret key of your application, and insure that no one is able to view it. The JSON Web Tokens are signed with the secret key, so if someone gets that, they can create arbitrary tokens, and in essence log in as any user. 4 Chapter 2. Basic Usage

9 CHAPTER 3 Partially protecting routes There may be cases where you want to use one endpoint for both protected and unprotected data. In these situations, you can use the jwt_optional() decorator. This will allow the endpoint to be accessed regardless of if a JWT is sent in with the request. If a JWT that is expired or badly constructed is sent in with the request, an error will be returned instead of calling the protected endpoint as if no token was present in the request. from flask import Flask, jsonify, request from flask_jwt_extended import ( JWTManager, jwt_optional, create_access_token, get_jwt_identity ) app = Flask( name ) # Setup the Flask-JWT-Extended extension app.config['jwt_secret_key'] = 'super-secret' jwt = JWTManager(app) # Change methods=['post']) def login(): username = request.json.get('username', None) password = request.json.get('password', None) if not username: return jsonify({"msg": "Missing username parameter"}), 400 if not password: return jsonify({"msg": "Missing password parameter"}), 400 if username!= 'test' or password!= 'test': return jsonify({"msg": "Bad username or password"}), 401 access_token = create_access_token(identity=username) return jsonify(access_token=access_token), 200 (continues on next page) 5

10 @app.route('/partially-protected', def partially_protected(): # If no JWT is sent in with the request, get_jwt_identity() # will return None current_user = get_jwt_identity() if current_user: return jsonify(logged_in_as=current_user), 200 else: return jsonify(loggeed_in_as='anonymous user'), 200 (continued from previous page) if name == ' main ': app.run() 6 Chapter 3. Partially protecting routes

11 CHAPTER 4 Storing Data in Access Tokens You may want to store additional information in the access token which you could later access in the protected views. This can be done with the user_claims_loader() decorator, and the data can be accessed later in a protected endpoint with the get_jwt_claims() function. Storing data in an access token can be good for performance. If you store data in the token, you wont need to look it up from disk next time you need it in a protected endpoint. However, you should take care what data you put in the token. Any data in the access token can be trivially viewed by anyone who can read the token. Do not store sensitive information in access tokens! from flask import Flask, jsonify, request from flask_jwt_extended import ( JWTManager, jwt_required, create_access_token, get_jwt_claims ) app = Flask( name ) app.config['jwt_secret_key'] = 'super-secret' jwt = JWTManager(app) # Change this! # Using the user_claims_loader, we can specify a method that will be # called when creating access tokens, and add these claims to the said # token. This method is passed the identity of who the token is being # created for, and must return data that is json def add_claims_to_access_token(identity): return { 'hello': identity, 'foo': ['bar', 'baz'] methods=['post']) (continues on next page) 7

12 def login(): username = request.json.get('username', None) password = request.json.get('password', None) if username!= 'test' or password!= 'test': return jsonify({"msg": "Bad username or password"}), 401 (continued from previous page) ret = {'access_token': create_access_token(username)} return jsonify(ret), 200 # In a protected view, get the claims you added to the jwt with the # get_jwt_claims() def protected(): claims = get_jwt_claims() return jsonify({ 'hello_is': claims['hello'], 'foo_is': claims['foo'] }), 200 if name == ' main ': app.run() 8 Chapter 4. Storing Data in Access Tokens

13 CHAPTER 5 Tokens from Complex Objects A very common setup is to have your users information (usernames, passwords, roles, etc) stored in a database. Now, lets pretend that we want to create an access tokens where the tokens identity is a username, and we also want to store a users roles as an additional claim in the token. We can do this with the user_claims_loader() decorator, discussed in the previous section. However, if we pass the username to the user_claims_loader(), we would end up needing to query this user from the database two times. The first time would be when login endpoint is hit and we need to verify a username and password. The second time would be in the user_claims_loader() function, because we need to query the roles for this user. This isn t a huge deal, but obviously it could be more efficient. This extension provides the ability to pass any object to the create_access_token() function, which will then be passed as is to the user_claims_loader(). This allows us access the database only once, but introduces a new issue that needs to be addressed. We still need to pull the username out of the object, so that we can have the username be the identity for the new token. We have a second decorator we can use for this, user_identity_loader(), which lets you take any object passed in to create_access_token() and return a json serializable identity from that object. Here is an example of this in action: from flask import Flask, jsonify, request from flask_jwt_extended import ( JWTManager, jwt_required, create_access_token, get_jwt_identity, get_jwt_claims ) app = Flask( name ) app.config['jwt_secret_key'] = 'super-secret' jwt = JWTManager(app) # Change this! # This is an example of a complex object that we could build # a JWT from. In practice, this will likely be something # like a SQLAlchemy instance. class UserObject: def init (self, username, roles): (continues on next page) 9

14 self.username = username self.roles = roles (continued from previous page) # Create a function that will be called whenever create_access_token # is used. It will take whatever object is passed into the # create_access_token method, and lets us define what custom claims # should be added to the access def add_claims_to_access_token(user): return {'roles': user.roles} # Create a function that will be called whenever create_access_token # is used. It will take whatever object is passed into the # create_access_token method, and lets us define what the identity # of the access token should def user_identity_lookup(user): return methods=['post']) def login(): username = request.json.get('username', None) password = request.json.get('password', None) if username!= 'test' or password!= 'test': return jsonify({"msg": "Bad username or password"}), 401 # Create an example UserObject user = UserObject(username='test', roles=['foo', 'bar']) # We can now pass this complex object directly to the # create_access_token method. This will allow us to access # the properties of this object in the user_claims_loader # function, and get the identity of this object from the # user_identity_loader function. access_token = create_access_token(identity=user) ret = {'access_token': access_token} return jsonify(ret), def protected(): ret = { 'current_identity': get_jwt_identity(), 'current_roles': get_jwt_claims() } return jsonify(ret), 200 # test # ['foo', 'bar'] if name == ' main ': app.run() 10 Chapter 5. Tokens from Complex Objects

15 CHAPTER 6 Complex Objects from Tokens We can also do the inverse of creating tokens from complex objects like we did in the last section. In this case, we can take a token and every time a protected endpoint is accessed, automatically use the token to load a complex object (such as a SQLAlchemy instance). This is done through the user_loader_callback_loader() decorator. The resulting object can be accessed in your protected endpoints by using the get_current_user() function, or directly with the current_user LocalProxy. One thing to note is if you access a database in the user_loader_callback_loader(), you will incur the cost of that database lookup on every call, regardless of if you need the additional data from the database or not. In most cases this likely isn t something to be worried about, but do be aware that it could slow your application if it handles high traffic. Here s an example of how this feature might look: from flask import Flask, jsonify, request from flask_jwt_extended import ( JWTManager, jwt_required, create_access_token, ) current_user app = Flask( name ) app.config['jwt_secret_key'] = 'super-secret' jwt = JWTManager(app) # Change this! # A demo user object that we will use in this example. class UserObject: def init (self, username, roles): self.username = username self.roles = roles # An example store of users. In production, this would likely # be a sqlalchemy instance or something similar. users_to_roles = { (continues on next page) 11

16 } 'foo': ['admin'], 'bar': ['peasant'], 'baz': ['peasant'] (continued from previous page) # This function is called whenever a protected endpoint is accessed, # and must return an object based on the tokens identity. # This is called after the token is verified, so you can use # get_jwt_claims() in here if desired. Note that this needs to # return None if the user could not be loaded for any reason, # such as not being found in the underlying data def user_loader_callback(identity): if identity not in users_to_roles: return None return UserObject( username=identity, roles=users_to_roles[identity] ) # You can override the error returned to the user if the # user_loader_callback returns None. If you don't override # this, # it will return a 401 status code with the JSON: # {"msg": "Error loading the user <identity>"}. # You can use # get_jwt_claims() here too if def custom_user_loader_error(identity): ret = { "msg": "User {} not found".format(identity) } return jsonify(ret), 404 # Create a token for any user, so this can be tested methods=['post']) def login(): username = request.get_json().get('username', None) access_token = create_access_token(identity=username) ret = {'access_token': access_token} return jsonify(ret), 200 # If the user_loader_callback returns None, this method will # not be run, even if the access token is valid. You can # access the loaded user via the ``current_user``` LocalProxy, # or with the ```get_current_user()``` def protected(): if 'admin' not in current_user.roles: return jsonify({"msg": "Forbidden"}), 403 else: return jsonify({"msg": "don't forget to drink your ovaltine"}) (continues on next page) 12 Chapter 6. Complex Objects from Tokens

17 (continued from previous page) if name == ' main ': app.run() 13

18 14 Chapter 6. Complex Objects from Tokens

19 CHAPTER 7 Custom Decorators You can create your own decorators that extend the functionality of the decorators provided by this extension. For example, you may want to create your own decorator that verifies a JWT is present as well as verifying that this token has sufficient permissions/roles to access an endpoint. Verify Tokens in Request is a list of functions that can be used to build your own decorators (these are also what all the default decorators provided by this extension use internally). Here is an example of how this might look. from functools import wraps from flask import Flask, jsonify, request from flask_jwt_extended import ( JWTManager, verify_jwt_in_request, create_access_token, get_jwt_claims ) app = Flask( name ) app.config['jwt_secret_key'] = 'super-secret' jwt = JWTManager(app) # Change this! # Here is a custom decorator that verifies the JWT is present in # the request, as well as insuring that this user has a role of # `admin` in the access token def def wrapper(*args, **kwargs): verify_jwt_in_request() claims = get_jwt_claims() if claims['roles']!= 'admin': return jsonify(msg='admins only!'), 403 else: (continues on next page) 15

20 return fn(*args, **kwargs) return wrapper (continued from previous def add_claims_to_access_token(identity): if identity == 'admin': return {'roles': 'admin'} else: return {'roles': methods=['post']) def login(): username = request.json.get('username', None) access_token = create_access_token(username) return def protected(): return jsonify(secret_message="go banana!") if name == ' main ': app.run() 16 Chapter 7. Custom Decorators

21 CHAPTER 8 Refresh Tokens Flask-JWT-Extended supports refresh tokens out of the box. These are long lived tokens which can be used to create new access tokens once an old access token has expired. Refresh tokens cannot access an endpoint that is protected with jwt_required() and access tokens cannot access and endpoint that is protected with jwt_refresh_token_required(). By setting the access tokens to a shorter lifetime (see Configuration Options), and utilizing refresh tokens we can help reduce the damage that can be done if an access token is stolen. However, if an attacker gets their hands on the refresh token, they can keep generating new access tokens and accessing protected endpoints as though he was that user. We can help combat this by using the fresh token pattern, discussed in the next section. Here is an example of using access and refresh tokens: from flask import Flask, jsonify, request from flask_jwt_extended import ( JWTManager, jwt_required, create_access_token, jwt_refresh_token_required, create_refresh_token, get_jwt_identity ) app = Flask( name ) app.config['jwt_secret_key'] = 'super-secret' jwt = JWTManager(app) # Change methods=['post']) def login(): username = request.json.get('username', None) password = request.json.get('password', None) if username!= 'test' or password!= 'test': return jsonify({"msg": "Bad username or password"}), 401 # Use create_access_token() and create_refresh_token() to create our # access and refresh tokens (continues on next page) 17

22 ret = { 'access_token': create_access_token(identity=username), 'refresh_token': create_refresh_token(identity=username) } return jsonify(ret), 200 (continued from previous page) # The jwt_refresh_token_required decorator insures a valid refresh # token is present in the request before calling this endpoint. We # can use the get_jwt_identity() function to get the identity of # the refresh token, and use the create_access_token() function again # to make a new access token for this def refresh(): current_user = get_jwt_identity() ret = { 'access_token': create_access_token(identity=current_user) } return jsonify(ret), def protected(): username = get_jwt_identity() return jsonify(logged_in_as=username), 200 if name == ' main ': app.run() 18 Chapter 8. Refresh Tokens

23 CHAPTER 9 Token Freshness The fresh token pattern is built into this extension. This pattern is very simple, you can choose to mark some access tokens as fresh and others as non-fresh, and use the fresh_jwt_required() decorator to only allow fresh tokens to access certain endpoints. This is useful for allowing fresh tokens to do some critical things (such as update an address or complete an online purchase), but to deny those features to non-fresh tokens. Utilizing Fresh tokens in conjunction with refresh tokens can lead to a more secure site, without creating a bad user experience by making users constantly re-authenticate. Here is an example of how you could utilize refresh tokens with the fresh token pattern: from flask import Flask, jsonify, request from flask_jwt_extended import ( JWTManager, jwt_required, create_access_token, jwt_refresh_token_required, create_refresh_token, get_jwt_identity, fresh_jwt_required ) app = Flask( name ) app.config['jwt_secret_key'] = 'super-secret' jwt = JWTManager(app) # Change this! # Standard login endpoint. Will return a fresh access token and # a refresh methods=['post']) def login(): username = request.json.get('username', None) password = request.json.get('password', None) if username!= 'test' or password!= 'test': return jsonify({"msg": "Bad username or password"}), 401 # create_access_token supports an optional 'fresh' argument, # which marks the token as fresh or non-fresh accordingly. # As we just verified their username and password, we are (continues on next page) 19

24 # going to mark the token as fresh here. ret = { 'access_token': create_access_token(identity=username, fresh=true), 'refresh_token': create_refresh_token(identity=username) } return jsonify(ret), 200 (continued from previous page) # Refresh token endpoint. This will generate a new access token from # the refresh token, but will mark that access token as non-fresh, # as we do not actually verify a password in this def refresh(): current_user = get_jwt_identity() new_token = create_access_token(identity=current_user, fresh=false) ret = {'access_token': new_token} return jsonify(ret), 200 # Fresh login endpoint. This is designed to be used if we need to # make a fresh token for a user (by verifying they have the # correct username and password). Unlike the standard login endpoint, # this will only return a new access token, so that we don't keep # generating new refresh tokens, which entirely defeats their methods=['post']) def fresh_login(): username = request.json.get('username', None) password = request.json.get('password', None) if username!= 'test' or password!= 'test': return jsonify({"msg": "Bad username or password"}), 401 new_token = create_access_token(identity=username, fresh=true) ret = {'access_token': new_token} return jsonify(ret), 200 # Any valid JWT can access this def protected(): username = get_jwt_identity() return jsonify(logged_in_as=username), 200 # Only fresh JWTs can access this def protected_fresh(): username = get_jwt_identity() return jsonify(fresh_logged_in_as=username), 200 if name == ' main ': app.run() 20 Chapter 9. Token Freshness

25 CHAPTER 10 Changing Default Behaviors 10.1 Changing callback functions We provide what we think are sensible behaviors when attempting to access a protected endpoint. If the access token is not valid for any reason (missing, expired, tampered with, etc) we will return json in the format of { msg : why accessing endpoint failed } along with an appropriate http status code (generally 401 or 422). However, you may want to customize what you return in some situations. We can do that with the jwt_manager loader functions. from flask import Flask, jsonify, request from flask_jwt_extended import ( JWTManager, jwt_required, create_access_token ) app = Flask( name ) app.config['jwt_secret_key'] = 'super-secret' jwt = JWTManager(app) # Change this! # Using the expired_token_loader decorator, we will now call # this function whenever an expired but otherwise valid access # token attempts to access an def my_expired_token_callback(): return jsonify({ 'status': 401, 'sub_status': 42, 'msg': 'The token has expired' }), methods=['post']) def login(): username = request.json.get('username', None) (continues on next page) 21

26 password = request.json.get('password', None) if username!= 'test' or password!= 'test': return jsonify({"msg": "Bad username or password"}), 401 (continued from previous page) ret = {'access_token': create_access_token(username)} return jsonify(ret), def protected(): return jsonify({'hello': 'world'}), 200 if name == ' main ': app.run() Here are the possible loader functions. Click on the links for a more more details about what arguments your callback functions should expect and what the return values of your callback functions need to be. Loader Decorator Description expired_token_loader() Function to call when an expired token accesses a protected endpoint invalid_token_loader() Function to call when an invalid token accesses a protected endpoint unauthorized_loader() Function to call when a request with no JWT accesses a protected endpoint needs_fresh_token_loader() Function to call when a non-fresh token accesses a fresh_jwt_required() endpoint revoked_token_loader() Function to call when a revoked token accesses a protected endpoint user_loader_callback_loader() Function to call to load a user object when token accesses a protected endpoint user_loader_error_loader() Function that is called when the user_loader callback function returns None token_in_blacklist_loader() Function that is called to check if a token has been revoked claims_verification_loader() Function that is called to verify the user_claims data. Must return True or False claims_verification_failed_loader() Function that is called when the user claims verification callback returns False 10.2 Dynamic token expires time You can also change the expires time for a token via the expires_delta kwarg in the create_refresh_token() and create_access_token() functions. This takes a datetime.timedelta and overrides the JWT_REFRESH_TOKEN_EXPIRES and JWT_ACCESS_TOKEN_EXPIRES settings (see Configuration Options). This can be useful if you have different use cases for different tokens. For example, you might use short lived access tokens used in your web application, but you allow the creation of long lived access tokens that other developers can generate and use to interact with your api in their programs. You could accomplish this like def create_dev_token(): username = get_jwt_identity() (continues on next page) 22 Chapter 10. Changing Default Behaviors

27 expires = datetime.timedelta(days=365) token = create_access_token(username, expires_delta=expires) return jsonify({'token': token}), 201 (continued from previous page) You can even disable expiration by setting expires_delta to def create_api_token(): username = get_jwt_identity() token = create_access_token(username, expires_delta=false) return jsonify({'token': token}), 201 Note that in this case, you should enable token revoking (see Blacklist and Token Revoking) Dynamic token expires time 23

28 24 Chapter 10. Changing Default Behaviors

29 CHAPTER 11 Configuration Options You can change many options for how this extension works via app.config[option_name] = new_options 25

30 11.1 General Options: JWT_TOKEN_LOCATION Where to look for a JWT when processing a request. The options are 'headers', 'cookies', or 'query_string'. You can pass in a list to check more then one location, such as: ['headers', 'cookies']. Defaults to 'headers' JWT_ACCESS_TOKEN_EXPIRES How long an access token should live before it expires. This takes a datetime.timedelta, and defaults to 15 minutes. Can be set to False to disable expiration. JWT_REFRESH_TOKEN_EXPIRES How long a refresh token should live before it expires. This takes a datetime.timedelta, and defaults to 30 days. Can be set to False to disable expiration. JWT_ALGORITHM Which algorithm to sign the JWT with. See here for the options. Defaults to 'HS256'. JWT_SECRET_KEY The secret key needed for symmetric based signing algorithms, such as HS*. If this is not set, we use the flask SECRET_KEY value instead. JWT_PUBLIC_KEY The public key needed for asymmetric based signing algorithms, such as RS* or ES*. PEM format expected. JWT_PRIVATE_KEY The private key needed for asymmetric based signing algorithms, such as RS* or ES*. PEM format expected. JWT_IDENTITY_CLAIM Claim in the tokens that is used as source of identity. For interoperativity, the JWT RFC recommends using 'sub'. Defaults to 'identity' for legacy reasons. JWT_USER_CLAIMS Claim in the tokens that is used to store user claims. Defaults to 'user_claims'. JWT_CLAIMS_IN_REFRESH_TOKEN If user claims should be included in refresh tokens. Defaults to False Header Options: These are only applicable if JWT_TOKEN_LOCATION is set to use headers. JWT_HEADER_NAME What header to look for the JWT in a request. Defaults to 'Authorization' JWT_HEADER_TYPE What type of header the JWT is in. Defaults to 'Bearer'. This can be an empty string, in which case the header contains only the JWT (insead of something like HeaderName: Bearer <JWT>) 11.3 Query String Options: These are only applicable if JWT_TOKEN_LOCATION is set to use query strings. JWT_QUERY_STRING_NAME What query paramater name to look for a JWT in a request. Defaults to 'jwt' 26 Chapter 11. Configuration Options

31 11.4 Cookie Options: These are only applicable if JWT_TOKEN_LOCATION is set to use cookies. JWT_ACCESS_COOKIE_NAME JWT_REFRESH_COOKIE_NAME JWT_ACCESS_COOKIE_PATH JWT_REFRESH_COOKIE_PATH JWT_COOKIE_SECURE JWT_COOKIE_DOMAIN JWT_SESSION_COOKIE JWT_COOKIE_SAMESITE JWT_COOKIE_CSRF_PROTECT The name of the cookie that holds the access token. Defaults to access_token_cookie The name of the cookie that holds the refresh token. Defaults to refresh_token_cookie What path should be set for the access cookie. Defaults to '/', which will cause this access cookie to be sent in with every request. Should be modified for only the paths that need the access cookie What path should be set for the refresh cookie. Defaults to '/', which will cause this refresh cookie to be sent in with every request. Should be modified for only the paths that need the refresh cookie If the secure flag should be set on your JWT cookies. This will only allow the cookies to be sent over https. Defaults to False, but in production this should likely be set to True. Value to use for cross domain cookies. Defaults to None which sets this cookie to only be readable by the domain that set it. If the cookies should be session cookies (deleted when the browser is closed) or persistent cookies (never expire). Defaults to True (session cookies). If the cookies should be sent in a cross-site browsing context. Defaults to None, which means cookies are always sent. Enable/disable CSRF protection when using cookies. Defaults to True Cross Site Request Forgery Options: These are only applicable if JWT_TOKEN_LOCATION is set to use cookies and JWT_COOKIE_CSRF_PROTECT is True Cookie Options: 27

32 JWT_CSRF_METHODS The request types that will use CSRF protection. Defaults to ['POST', 'PUT', 'PATCH', 'DELETE'] JWT_ACCESS_CSRF_HEADER_NAME Name of the header that should contain the CSRF double submit value for access tokens. Defaults to X-CSRF-TOKEN. JWT_REFRESH_CSRF_HEADER_NAME Name of the header that should contains the CSRF double submit value for refresh tokens. Defaults to JWT_CSRF_IN_COOKIES X-CSRF-TOKEN. If we should store the CSRF double submit value in another cookies when using set_access_cookies() and set_refresh_cookies(). Defaults to True. If this is False, you are responsible for getting the CSRF value to the callers (see: get_csrf_token(encoded_token)). JWT_ACCESS_CSRF_COOKIE_NAME Name of the CSRF access cookie. Defaults to 'csrf_access_token'. Only applicable if JWT_CSRF_IN_COOKIES is True JWT_REFRESH_CSRF_COOKIE_NAME Name of the CSRF refresh cookie. Defaults to 'csrf_refresh_token'. Only applicable if JWT_CSRF_IN_COOKIES is True JWT_ACCESS_CSRF_COOKIE_PATH JWT_REFRESH_CSRF_COOKIE_PATH Path for the CSRF access cookie. Defaults to '/'. Only applicable if JWT_CSRF_IN_COOKIES is True Path of the CSRF refresh cookie. Defaults to '/'. Only applicable if JWT_CSRF_IN_COOKIES is True 11.6 Blacklist Options: JWT_BLACKLIST_ENABLED Enable/disable token revoking. Defaults to False JWT_BLACKLIST_TOKEN_CHECKS What token types to check against the blacklist. The options are 'refresh' or 'access'. You can pass in a list to check more then one type. Defaults to ['access', 'refresh']. Only used if blacklisting is enabled. 28 Chapter 11. Configuration Options

33 CHAPTER 12 Blacklist and Token Revoking This extension supports optional token revoking out of the box. This will allow you to revoke a specific token so that it can no longer access your endpoints. You will have to choose what tokens you want to check against the blacklist. In most cases, you will probably want to check both refresh and access tokens, which is the default behavior. However, if the extra overhead of checking tokens is a concern you could instead only check the refresh tokens, and set the access tokens to have a short expires time so any damage a compromised token could cause is minimal. Blacklisting works by is providing a callback function to this extension, using the token_in_blacklist_loader() decorator. This method will be called whenever the specified tokens (access and/or refresh) are used to access a protected endpoint. If the callback function says that the token is revoked, we will not allow the call to continue, otherwise we will allow the call to access the endpoint as normal. Here is a basic example of this in action. from flask import Flask, request, jsonify from flask_jwt_extended import ( JWTManager, jwt_required, get_jwt_identity, create_access_token, create_refresh_token, jwt_refresh_token_required, get_raw_jwt ) # Setup flask app = Flask( name ) # Enable blacklisting and specify what kind of tokens to check # against the blacklist app.config['jwt_secret_key'] = 'super-secret' # Change this! app.config['jwt_blacklist_enabled'] = True app.config['jwt_blacklist_token_checks'] = ['access', 'refresh'] jwt = JWTManager(app) # A storage engine to save revoked tokens. In production if (continues on next page) 29

34 (continued from previous page) # speed is the primary concern, redis is a good bet. If data # persistence is more important for you, postgres is another # great option. In this example, we will be using an in memory # store, just to show you how this might work. For more # complete examples, check out these: # py # blacklist blacklist = set() # For this example, we are just checking if the tokens jti # (unique identifier) is in the blacklist set. This could # be made more complex, for example storing all tokens # into the blacklist with a revoked status when created, # and returning the revoked status in this call. This # would allow you to have a list of all created tokens, # and to consider tokens that aren't in the blacklist # (aka tokens you didn't create) as revoked. These are # just two options, and this can be tailored to whatever # your application def check_if_token_in_blacklist(decrypted_token): jti = decrypted_token['jti'] return jti in blacklist # Standard login methods=['post']) def login(): username = request.json.get('username', None) password = request.json.get('password', None) if username!= 'test' or password!= 'test': return jsonify({"msg": "Bad username or password"}), 401 ret = { 'access_token': create_access_token(identity=username), 'refresh_token': create_refresh_token(identity=username) } return jsonify(ret), 200 # Standard refresh endpoint. A blacklisted refresh token # will not be able to access this def refresh(): current_user = get_jwt_identity() ret = { 'access_token': create_access_token(identity=current_user) } return jsonify(ret), 200 # Endpoint for revoking the current users access methods=['delete']) (continues on next page) 30 Chapter 12. Blacklist and Token Revoking

35 @jwt_required def logout(): jti = get_raw_jwt()['jti'] blacklist.add(jti) return jsonify({"msg": "Successfully logged out"}), 200 (continued from previous page) # Endpoint for revoking the current users refresh def logout2(): jti = get_raw_jwt()['jti'] blacklist.add(jti) return jsonify({"msg": "Successfully logged out"}), 200 # This will now prevent users with blacklisted tokens from # accessing this def protected(): return jsonify({'hello': 'world'}) if name == ' main ': app.run() In production, you will likely want to use either a database or in memory store (such as redis) to store your tokens. In memory stores are great if you are wanting to revoke a token when the users logs out, as they are blazing fast. A downside to using redis is that in the case of a power outage or other such event, it s possible that you might forget that some tokens have been revoked, depending on if the redis data was synced to disk. In contrast to that, databases are great if the data persistance is of the highest importance (for example, if you have very long lived tokens that other developers use to access your api), or if you want to add some addition features like showing users all of their active tokens, and letting them revoke and unrevoke those tokens. For more in depth examples of these, check out:

36 32 Chapter 12. Blacklist and Token Revoking

37 CHAPTER 13 JWT in Cookies If the frontend that is consuming this backend is a website, you may be storing JWTs in the browser localstorage or sessionstorage. There is nothing wrong with this, but if you have any sort of XSS vulnerability on your site, an attacker will be able to trivially steal your refresh and access tokens. If you want some additional security on your site, you can save your JWTs in a httponly cookie instead, which keeps javascript from being able to access the cookie. See this great blog for a more in depth analysis between these options: Here is a basic example of how to store JWTs in cookies: from flask import Flask, jsonify, request from flask_jwt_extended import ( JWTManager, jwt_required, create_access_token, jwt_refresh_token_required, create_refresh_token, get_jwt_identity, set_access_cookies, set_refresh_cookies, unset_jwt_cookies ) # NOTE: This is just a basic example of how to enable cookies. This is # vulnerable to CSRF attacks, and should not be used as is. See # csrf_protection_with_cookies.py for a more complete example! app = Flask( name ) # Configure application to store JWTs in cookies. Whenever you make # a request to a protected endpoint, you will need to send in the # access or refresh JWT via a cookie. app.config['jwt_token_location'] = ['cookies'] # Set the cookie paths, so that you are only sending your access token # cookie to the access endpoints, and only sending your refresh token # to the refresh endpoint. Technically this is optional, but it is in # your best interest to not send additional cookies in the request if # they aren't needed. (continues on next page) 33

38 app.config['jwt_access_cookie_path'] = '/api/' app.config['jwt_refresh_cookie_path'] = '/token/refresh' (continued from previous page) # Disable CSRF protection for this example. In almost every case, # this is a bad idea. See examples/csrf_protection_with_cookies.py # for how safely store JWTs in cookies app.config['jwt_cookie_csrf_protect'] = False # Set the secret key to sign the JWTs with app.config['jwt_secret_key'] = 'super-secret' # Change this! jwt = JWTManager(app) # Use the set_access_cookie() and set_refresh_cookie() on a response # object to set the JWTs in the response cookies. You can configure # the cookie names and other settings via various app.config methods=['post']) def login(): username = request.json.get('username', None) password = request.json.get('password', None) if username!= 'test' or password!= 'test': return jsonify({'login': False}), 401 # Create the tokens we will be sending back to the user access_token = create_access_token(identity=username) refresh_token = create_refresh_token(identity=username) # Set the JWT cookies in the response resp = jsonify({'login': True}) set_access_cookies(resp, access_token) set_refresh_cookies(resp, refresh_token) return resp, 200 # Same thing as login here, except we are only setting a new cookie # for the access def refresh(): # Create the new access token current_user = get_jwt_identity() access_token = create_access_token(identity=current_user) # Set the JWT access cookie in the response resp = jsonify({'refresh': True}) set_access_cookies(resp, access_token) return resp, 200 # Because the JWTs are stored in an httponly cookie now, we cannot # log the user out by simply deleting the cookie in the frontend. # We need the backend to send us a response to delete the cookies # in order to logout. unset_jwt_cookies is a helper function to # do just methods=['post']) def logout(): (continues on next page) 34 Chapter 13. JWT in Cookies

39 resp = jsonify({'logout': True}) unset_jwt_cookies(resp) return resp, 200 (continued from previous page) # We do not need to make any changes to our protected endpoints. They # will all still function the exact same as they do when sending the # JWT in via a header instead of a def protected(): username = get_jwt_identity() return jsonify({'hello': 'from {}'.format(username)}), 200 if name == ' main ': app.run() This isn t the full story however. We can now keep our cookie from being stolen via XSS attacks, but have traded that for a vulnerability to CSRF attacks. To combat CSRF, we are going to use a technique called double submit verification. When we create a JWT, we will also create a random string and store it in the JWT. This token is saved in a cookie with httponly set to True, so it cannot be accessed via javascript. We will then create a secondary cookie that contains only the random string, but has httponly set to False, so that it can be accessed via javascript running on your website. Now in order to access a protected endpoint, you will need to add a custom header that contains the the random string in it, and if that header doesn t exist or it doesn t match the string that is stored in the JWT, the request will be kicked out as unauthorized. To break this down, if an attacker attempts to perform a CSRF attack they will send the JWT (via the cookie) to a protected endpoint, but without the random string in the requests header, they wont be able to access the endpoint. They cannot access the random string, unless they can run javascript on your website (likely via an XSS attack), and if they are able to perform an XSS attack, they will not be able to steal the actual access and refresh JWTs, as javascript is still not able to access those httponly cookies. This obviously isn t a golden bullet. If an attacker can perform an XSS attack they can still access protected endpoints from people who visit your site. However, it is better then if they were able to steal the access and refresh tokens tokens from local/session storage, and use them whenever they wanted. If this additional security is worth the added complexity of using cookies and double submit CSRF protection is a choice you will have to make. Here is an example of using cookies with CSRF protection: from flask import Flask, jsonify, request from flask_jwt_extended import ( JWTManager, jwt_required, create_access_token, jwt_refresh_token_required, create_refresh_token, get_jwt_identity, set_access_cookies, set_refresh_cookies, unset_jwt_cookies ) app = Flask( name ) # Configure application to store JWTs in cookies app.config['jwt_token_location'] = ['cookies'] # Only allow JWT cookies to be sent over https. In production, this (continues on next page) 35

40 # should likely be True app.config['jwt_cookie_secure'] = False (continued from previous page) # Set the cookie paths, so that you are only sending your access token # cookie to the access endpoints, and only sending your refresh token # to the refresh endpoint. Technically this is optional, but it is in # your best interest to not send additional cookies in the request if # they aren't needed. app.config['jwt_access_cookie_path'] = '/api/' app.config['jwt_refresh_cookie_path'] = '/token/refresh' # Enable csrf double submit protection. See this for a thorough # explanation: app.config['jwt_cookie_csrf_protect'] = True # Set the secret key to sign the JWTs with app.config['jwt_secret_key'] = 'super-secret' # Change this! jwt = JWTManager(app) # By default, the CRSF cookies will be called csrf_access_token and # csrf_refresh_token, and in protected endpoints we will look for the # CSRF token in the 'X-CSRF-TOKEN' header. You can modify all of these # with various app.config options. Check the options page for details. # With JWT_COOKIE_CSRF_PROTECT set to True, set_access_cookies() and # set_refresh_cookies() will now also set the non-httponly CSRF cookies # as methods=['post']) def login(): username = request.json.get('username', None) password = request.json.get('password', None) if username!= 'test' or password!= 'test': return jsonify({'login': False}), 401 # Create the tokens we will be sending back to the user access_token = create_access_token(identity=username) refresh_token = create_refresh_token(identity=username) # Set the JWTs and the CSRF double submit protection cookies # in this response resp = jsonify({'login': True}) set_access_cookies(resp, access_token) set_refresh_cookies(resp, refresh_token) return resp, def refresh(): # Create the new access token current_user = get_jwt_identity() access_token = create_access_token(identity=current_user) # Set the access JWT and CSRF double submit protection cookies (continues on next page) 36 Chapter 13. JWT in Cookies

41 # in this response resp = jsonify({'refresh': True}) set_access_cookies(resp, access_token) return resp, 200 (continued from previous page) # Because the JWTs are stored in an httponly cookie now, we cannot # log the user out by simply deleting the cookie in the frontend. # We need the backend to send us a response to delete the cookies # in order to logout. unset_jwt_cookies is a helper function to # do just methods=['post']) def logout(): resp = jsonify({'logout': True}) unset_jwt_cookies(resp) return resp, def protected(): username = get_jwt_identity() return jsonify({'hello': 'from {}'.format(username)}), 200 if name == ' main ': app.run() By default, the CSRF double submit values are sent back as additional cookies to the caller. If you prefer, you can disable that, and send them back directly to the caller, like such: app.config['jwt_csrf_in_cookies'] = False #... #... methods=['post']) def login(): username = request.json.get('username', None) password = request.json.get('password', None) if username!= 'test' or password!= 'test': return jsonify({'login': False}), 401 # Create the tokens we will be sending back to the user access_token = create_access_token(identity=username) refresh_token = create_refresh_token(identity=username) # Return the double submit values in the resulting JSON # instead of in additional cookies resp = jsonify({ 'access_csrf': get_csrf_token(access_token), 'refresh_csrf': get_csrf_token(refresh_token) }) # We still need to call these functions to set the # JWTs in the cookies set_access_cookies(resp, access_token) (continues on next page) 37

42 set_refresh_cookies(resp, refresh_token) return resp, 200 (continued from previous page) 38 Chapter 13. JWT in Cookies

43 CHAPTER 14 JWT in Query String You can also pass the token in as a paramater in the query string instead of as a header or a cookie (ex: /protected?jwt=<token>). However, in almost all cases it is recomended that you do not do this, as it comes with some security issues. If you perform a GET request with a JWT in the query param, it is possible that the browser will save the URL, which could lead to a leaked token. It is also very likely that your backend (such as nginx or uwsgi) could log the full url paths, which is obviously not ideal from a security standpoint. If you do decide to use JWTs in query paramaters, here is an example of how it might look: from flask import Flask, jsonify, request from flask_jwt_extended import ( JWTManager, jwt_required, create_access_token, ) # IMPORTANT NOTE: # In most cases this is not recommended! It can lead some some # security issues, such as: # - The browser saving GET request urls in it's history that # has a JWT in the query string # - The backend server logging JWTs that are in the url # # If possible, you should use headers instead! app = Flask( name ) app.config['jwt_token_location'] = ['query_string'] app.config['jwt_secret_key'] = 'super-secret' # Change this! jwt = methods=['post']) def login(): username = request.json.get('username', None) password = request.json.get('password', None) (continues on next page) 39

flask-jwt-simple Documentation

flask-jwt-simple Documentation flask-jwt-simple Documentation Release 0.0.3 vimalloc rlam3 Nov 17, 2018 Contents 1 Installation 3 2 Basic Usage 5 3 Changing JWT Claims 7 4 Changing Default Behaviors 9 5 Configuration Options 11 6 API

More information

flask-jwt Documentation

flask-jwt Documentation flask-jwt Documentation Release 0.3.2 Dan Jacob Nov 16, 2017 Contents 1 Links 3 2 Installation 5 3 Quickstart 7 4 Configuration Options 9 5 API 11 6 Changelog 13 6.1 Flask-JWT Changelog..........................................

More information

django-oauth2-provider Documentation

django-oauth2-provider Documentation django-oauth2-provider Documentation Release 0.2.7-dev Alen Mujezinovic Aug 16, 2017 Contents 1 Getting started 3 1.1 Getting started.............................................. 3 2 API 5 2.1 provider.................................................

More information

flask-praetorian Documentation

flask-praetorian Documentation flask-praetorian Documentation Release 0.4.7 Tucker Beck Jun 21, 2018 Contents: 1 Table of Contents 3 1.1 Quickstart................................................ 3 1.2 Notes...................................................

More information

GitHub-Flask Documentation

GitHub-Flask Documentation GitHub-Flask Documentation Release 3.2.0 Cenk Altı Jul 01, 2018 Contents 1 Installation 3 2 Configuration 5 3 Authenticating / Authorizing Users 7 4 Invoking Remote Methods 9 5 Full Example 11 6 API Reference

More information

WEB API. Nuki Home Solutions GmbH. Münzgrabenstraße 92/ Graz Austria F

WEB API. Nuki Home Solutions GmbH. Münzgrabenstraße 92/ Graz Austria F WEB API v 1. 1 0 8. 0 5. 2 0 1 8 1. Introduction 2. Calling URL 3. Swagger Interface Example API call through Swagger 4. Authentication API Tokens OAuth 2 Code Flow OAuth2 Authentication Example 1. Authorization

More information

Flask-Cors Documentation

Flask-Cors Documentation Flask-Cors Documentation Release 3.0.4 Cory Dolphin Apr 26, 2018 Contents 1 Installation 3 2 Usage 5 2.1 Simple Usage............................................... 5 3 Documentation 7 4 Troubleshooting

More information

django-secure Documentation

django-secure Documentation django-secure Documentation Release 0.1.2 Carl Meyer and contributors January 23, 2016 Contents 1 Quickstart 3 1.1 Dependencies............................................... 3 1.2 Installation................................................

More information

Advanced API Security

Advanced API Security Advanced API Security ITANA Group Nuwan Dias Architect 22/06/2017 Agenda 2 HTTP Basic Authentication Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l 3 API Security is about controlling Access Delegation

More information

P2_L12 Web Security Page 1

P2_L12 Web Security Page 1 P2_L12 Web Security Page 1 Reference: Computer Security by Stallings and Brown, Chapter (not specified) The web is an extension of our computing environment, because most of our daily tasks involve interaction

More information

WEB SECURITY: XSS & CSRF

WEB SECURITY: XSS & CSRF WEB SECURITY: XSS & CSRF CMSC 414 FEB 22 2018 Cross-Site Request Forgery (CSRF) URLs with side-effects http://bank.com/transfer.cgi?amt=9999&to=attacker GET requests should have no side-effects, but often

More information

Canonical Identity Provider Documentation

Canonical Identity Provider Documentation Canonical Identity Provider Documentation Release Canonical Ltd. December 14, 2018 Contents 1 API 3 1.1 General considerations.......................................... 3 1.2 Rate limiting...............................................

More information

System and Software Architecture Description (SSAD)

System and Software Architecture Description (SSAD) System and Software Architecture Description (SSAD) REAL ESTATE INVESTMENT AND REVIEW TOOL TEAM 02 Venkata Sravanti Malapaka (Project Manager / Software Architect) Yuxuan Chen (Prototyper / Developer/Trainer)

More information

bzz Documentation Release Rafael Floriano and Bernardo Heynemann

bzz Documentation Release Rafael Floriano and Bernardo Heynemann bzz Documentation Release 0.1.0 Rafael Floriano and Bernardo Heynemann Nov 15, 2017 Contents 1 Getting Started 3 2 Flattening routes 5 3 Indices and tables 7 3.1 Model Hive................................................

More information

CS 161 Computer Security

CS 161 Computer Security Paxson Spring 2017 CS 161 Computer Security Discussion 4 Week of February 13, 2017 Question 1 Clickjacking (5 min) Watch the following video: https://www.youtube.com/watch?v=sw8ch-m3n8m Question 2 Session

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Web Servers and Web APIs Raymond Yin University of Pennsylvania November 12, 2015 Raymond Yin (University of Pennsylvania) CIS 192 November 12, 2015 1 / 23 Outline 1 Web Servers

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Web Servers and Web APIs Eric Kutschera University of Pennsylvania March 6, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 March 6, 2015 1 / 22 Outline 1 Web Servers

More information

Sessions. Mendel Rosenblum. CS142 Lecture Notes - Sessions

Sessions. Mendel Rosenblum. CS142 Lecture Notes - Sessions Sessions Mendel Rosenblum How do we know what user sent request? Would like to authenticate user and have that information available each time we process a request. More generally web apps would like to

More information

StorageGRID Webscale 11.0 Tenant Administrator Guide

StorageGRID Webscale 11.0 Tenant Administrator Guide StorageGRID Webscale 11.0 Tenant Administrator Guide January 2018 215-12403_B0 doccomments@netapp.com Table of Contents 3 Contents Administering a StorageGRID Webscale tenant account... 5 Understanding

More information

Integrating with ClearPass HTTP APIs

Integrating with ClearPass HTTP APIs Integrating with ClearPass HTTP APIs HTTP based APIs The world of APIs is full concepts that are not immediately obvious to those of us without software development backgrounds and terms like REST, RPC,

More information

HOW TO FLASK. And a very short intro to web development and databases

HOW TO FLASK. And a very short intro to web development and databases HOW TO FLASK And a very short intro to web development and databases FLASK Flask is a web application framework written in Python. Created by an international Python community called Pocco. Based on 2

More information

Security. CSC309 TA: Sukwon Oh

Security. CSC309 TA: Sukwon Oh Security CSC309 TA: Sukwon Oh Outline SQL Injection NoSQL Injection (MongoDB) Same Origin Policy XSSI XSS CSRF (XSRF) SQL Injection What is SQLI? Malicious user input is injected into SQL statements and

More information

CS144: Sessions. Cookie : CS144: Web Applications

CS144: Sessions. Cookie : CS144: Web Applications CS144: Sessions HTTP is a stateless protocol. The server s response is purely based on the single request, not anything else Q: How does a web site like Amazon can remember a user and customize its results?

More information

Application Security Introduction. Tara Gu IBM Product Security Incident Response Team

Application Security Introduction. Tara Gu IBM Product Security Incident Response Team Application Security Introduction Tara Gu IBM Product Security Incident Response Team About Me - Tara Gu - tara.weiqing@gmail.com - Duke B.S.E Biomedical Engineering - Duke M.Eng Computer Engineering -

More information

CSRF in the Modern Age

CSRF in the Modern Age CSRF in the Modern Age Sidestepping the CORS Standard Tanner Prynn @tannerprynn In This Talk The State of CSRF The CORS Standard How Not To Prevent CSRF The Fundamentals of HTTP Without cookies: With cookies:

More information

Security and Privacy. SWE 432, Fall 2016 Design and Implementation of Software for the Web

Security and Privacy. SWE 432, Fall 2016 Design and Implementation of Software for the Web Security and Privacy SWE 432, Fall 2016 Design and Implementation of Software for the Web Today Security What is it? Most important types of attacks Privacy For further reading: https://www.owasp.org/index.php/

More information

Quick housekeeping Last Two Homeworks Extra Credit for demoing project prototypes Reminder about Project Deadlines/specifics Class on April 12th Resul

Quick housekeeping Last Two Homeworks Extra Credit for demoing project prototypes Reminder about Project Deadlines/specifics Class on April 12th Resul CIS192 Python Programming Web Frameworks and Web APIs Harry Smith University of Pennsylvania March 29, 2016 Harry Smith (University of Pennsylvania) CIS 192 March 29, 2016 1 / 25 Quick housekeeping Last

More information

Web Services Configuration Guide

Web Services Configuration Guide Web Services Configuration Guide Freezerworks 2017 PO Box 174 Mountlake Terrace, WA 98043 www.freezerworks.com support@freezerworks.com 425-673-1974 877-289-7960 U.S. Toll Free Freezerworks is a registered

More information

EasyCrypt passes an independent security audit

EasyCrypt passes an independent security audit July 24, 2017 EasyCrypt passes an independent security audit EasyCrypt, a Swiss-based email encryption and privacy service, announced that it has passed an independent security audit. The audit was sponsored

More information

I hate money. Release 1.0

I hate money. Release 1.0 I hate money Release 1.0 Nov 01, 2017 Contents 1 Table of content 3 2 Indices and tables 15 i ii «I hate money» is a web application made to ease shared budget management. It keeps track of who bought

More information

Application vulnerabilities and defences

Application vulnerabilities and defences Application vulnerabilities and defences In this lecture We examine the following : SQL injection XSS CSRF SQL injection SQL injection is a basic attack used to either gain unauthorized access to a database

More information

CS 161 Computer Security

CS 161 Computer Security Nick Weaver Fall 2018 CS 161 Computer Security Homework 3 Due: Friday, 19 October 2018, at 11:59pm Instructions. This homework is due Friday, 19 October 2018, at 11:59pm. No late homeworks will be accepted

More information

Chapter 1 - Consuming REST Web Services in Angular

Chapter 1 - Consuming REST Web Services in Angular Chapter 1 - Consuming REST Web Services in Angular Objectives Key objectives of this chapter REST Overview Common Angular tasks for REST communication Using Angular to send various HTTP requests 1.1 REST

More information

The production version of your service API must be served over HTTPS.

The production version of your service API must be served over HTTPS. This document specifies how to implement an API for your service according to the IFTTT Service Protocol. It is recommended that you treat this document as a reference and follow the workflow outlined

More information

CSE361 Web Security. Attacks against the client-side of web applications. Nick Nikiforakis

CSE361 Web Security. Attacks against the client-side of web applications. Nick Nikiforakis CSE361 Web Security Attacks against the client-side of web applications Nick Nikiforakis nick@cs.stonybrook.edu Despite the same origin policy Many things can go wrong at the client-side of a web application

More information

WEB SECURITY WORKSHOP TEXSAW Presented by Solomon Boyd and Jiayang Wang

WEB SECURITY WORKSHOP TEXSAW Presented by Solomon Boyd and Jiayang Wang WEB SECURITY WORKSHOP TEXSAW 2014 Presented by Solomon Boyd and Jiayang Wang Introduction and Background Targets Web Applications Web Pages Databases Goals Steal data Gain access to system Bypass authentication

More information

CacheControl Documentation

CacheControl Documentation CacheControl Documentation Release 0.12.4 Eric Larson May 01, 2018 Contents 1 Install 3 2 Quick Start 5 3 Tests 7 4 Disclaimers 9 4.1 Using CacheControl........................................... 9 4.2

More information

Protect Your API with OAuth 2. Rob Allen

Protect Your API with OAuth 2. Rob Allen Protect Your API with OAuth 2 Authentication Know who is logging into your API Rate limiting Revoke application access if its a problem Allow users to revoke 3rd party applications How? Authorization header:

More information

OWASP Thailand. Proxy Caches and Web Application Security. OWASP AppSec Asia October 21, Using the Recent Google Docs 0-Day as an Example

OWASP Thailand. Proxy Caches and Web Application Security. OWASP AppSec Asia October 21, Using the Recent Google Docs 0-Day as an Example Proxy Caches and Web Application Security Using the Recent Google Docs 0-Day as an Example Tim Bass, CISSP Chapter Leader, Thailand +66832975101, tim@unix.com AppSec Asia October 21, 2008 Thailand Worldwide

More information

Using OAuth 2.0 to Access ionbiz APIs

Using OAuth 2.0 to Access ionbiz APIs Using OAuth 2.0 to Access ionbiz APIs ionbiz APIs use the OAuth 2.0 protocol for authentication and authorization. ionbiz supports common OAuth 2.0 scenarios such as those for web server, installed, and

More information

Handout 20 - Quiz 2 Solutions

Handout 20 - Quiz 2 Solutions Department of Electrical Engineering and Computer Science MASSACHUSETTS INSTITUTE OF TECHNOLOGY 6.033 Computer Systems Engineering: Spring 2001 Handout 20 - Quiz 2 Solutions 20 Average: 81 Median: 83 Std.

More information

Perslink Security. Perslink Security. Eleonora Petridou Pascal Cuylaerts. System And Network Engineering University of Amsterdam.

Perslink Security. Perslink Security. Eleonora Petridou Pascal Cuylaerts. System And Network Engineering University of Amsterdam. Eleonora Petridou Pascal Cuylaerts System And Network Engineering University of Amsterdam June 30, 2011 Outline Research question About Perslink Approach Manual inspection Automated tests Vulnerabilities

More information

f5-icontrol-rest Documentation

f5-icontrol-rest Documentation f5-icontrol-rest Documentation Release 1.3.10 F5 Networks Aug 04, 2018 Contents 1 Overview 1 2 Installation 3 2.1 Using Pip................................................. 3 2.2 GitHub..................................................

More information

Advanced Flask Patterns

Advanced Flask Patterns Advanced Flask Patterns (mysteriously also applicable to other things) a presentation by Armin Ronacher @mitsuhiko Some of these things are general suggestions of how I think applications can be structured

More information

Django Synctool Documentation

Django Synctool Documentation Django Synctool Documentation Release 1.0.0 Preston Timmons November 01, 2014 Contents 1 Basic usage 3 1.1 How it works............................................... 4 2 Installation 5 3 Contents 7 3.1

More information

DreamFactory Security Guide

DreamFactory Security Guide DreamFactory Security Guide This white paper is designed to provide security information about DreamFactory. The sections below discuss the inherently secure characteristics of the platform and the explicit

More information

If the presented credentials are valid server will respond with a success response:

If the presented credentials are valid server will respond with a success response: Telema EDI REST API Telema EDI REST API allows client to send and receive document to and from Telema server. In order to use EDI REST API client must have correct channel configured in Telema system.

More information

Instructions 1 Elevation of Privilege Instructions

Instructions 1 Elevation of Privilege Instructions Instructions 1 Elevation of Privilege Instructions Draw a diagram of the system you want to threat model before you deal the cards. Deal the deck to 3-6 players. Play starts with the 3 of Tampering. Play

More information

RKN 2015 Application Layer Short Summary

RKN 2015 Application Layer Short Summary RKN 2015 Application Layer Short Summary HTTP standard version now: 1.1 (former 1.0 HTTP /2.0 in draft form, already used HTTP Requests Headers and body counterpart: answer Safe methods (requests): GET,

More information

Web Security 2 https://www.xkcd.com/177/ http://xkcd.com/1323/ Encryption basics Plaintext message key secret Encryp)on Func)on Ciphertext Insecure network Decryp)on Func)on Curses! Foiled again! key Plaintext

More information

Project 2: Web Security

Project 2: Web Security EECS 388 September 30, 2016 Intro to Computer Security Project 2: Web Security Project 2: Web Security This project is due on Thursday, October 13 at 6 p.m. and counts for 8% of your course grade. Late

More information

Persistence. SWE 432, Fall 2017 Design and Implementation of Software for the Web

Persistence. SWE 432, Fall 2017 Design and Implementation of Software for the Web Persistence SWE 432, Fall 2017 Design and Implementation of Software for the Web Today Demo: Promises and Timers What is state in a web application? How do we store it, and how do we choose where to store

More information

eb Security Software Studio

eb Security Software Studio eb Security Software Studio yslin@datalab 1 OWASP Top 10 Security Risks in 2017 Rank Name 1 Injection 2 Broken Authentication and Session Management 3 Cross-Site Scripting (XSS) 4 Broken Access Control

More information

Web Application Security. Philippe Bogaerts

Web Application Security. Philippe Bogaerts Web Application Security Philippe Bogaerts OWASP TOP 10 3 Aim of the OWASP Top 10 educate developers, designers, architects and organizations about the consequences of the most common web application security

More information

Attacks Against Websites. Tom Chothia Computer Security, Lecture 11

Attacks Against Websites. Tom Chothia Computer Security, Lecture 11 Attacks Against Websites Tom Chothia Computer Security, Lecture 11 A typical web set up TLS Server HTTP GET cookie Client HTML HTTP file HTML PHP process Display PHP SQL Typical Web Setup HTTP website:

More information

Web 2.0 and AJAX Security. OWASP Montgomery. August 21 st, 2007

Web 2.0 and AJAX Security. OWASP Montgomery. August 21 st, 2007 Web 2.0 and AJAX Security OWASP Montgomery August 21 st, 2007 Overview Introduction Definition of Web 2.0 Basics of AJAX Attack Vectors for AJAX Applications AJAX and Application Security Conclusions 1

More information

BlackBerry AtHoc Networked Crisis Communication. BlackBerry AtHoc API Quick Start Guide

BlackBerry AtHoc Networked Crisis Communication. BlackBerry AtHoc API Quick Start Guide BlackBerry AtHoc Networked Crisis Communication BlackBerry AtHoc API Quick Start Guide Release 7.6, September 2018 Copyright 2018 BlackBerry Limited. All Rights Reserved. This document may not be copied,

More information

If you re a Facebook marketer, you re likely always looking for ways to

If you re a Facebook marketer, you re likely always looking for ways to Chapter 1: Custom Apps for Fan Page Timelines In This Chapter Using apps for Facebook marketing Extending the Facebook experience Discovering iframes, Application Pages, and Canvas Pages Finding out what

More information

CSCE 120: Learning To Code

CSCE 120: Learning To Code CSCE 120: Learning To Code Module 11.0: Consuming Data I Introduction to Ajax This module is designed to familiarize you with web services and web APIs and how to connect to such services and consume and

More information

Topic 15: Authentication

Topic 15: Authentication Topic 15: Authentication CITS3403 Agile Web Development Getting MEAN with Mongo, Express, Angular and Node, Chapter 11 Semester 1, 2018 Secure web apps Security is a primary concern for anyone developing

More information

flask-ldap3-login Documentation

flask-ldap3-login Documentation flask-ldap3-login Documentation Release 0.0.0.dev0 Nick Whyte Nov 09, 2018 Contents 1 Contents: 3 1.1 Configuration............................................... 3 1.2 Quick Start................................................

More information

Requests Mock Documentation

Requests Mock Documentation Requests Mock Documentation Release 1.5.1.dev4 Jamie Lennox Jun 16, 2018 Contents 1 Overview 3 2 Using the Mocker 5 2.1 Activation................................................ 5 2.2 Class Decorator.............................................

More information

ColdFusion Application Security: The Next Step - Handout

ColdFusion Application Security: The Next Step - Handout ColdFusion Application Security: The Next Step - Handout Jason Dean http://www.12robots.com Boston CFUG September 16 th, 2009 REQUEST FORGERIES A request forgery, also sometimes called a Cross-Site (or

More information

Application Layer Security

Application Layer Security Application Layer Security General overview Ma. Angel Marquez Andrade Benefits of web Applications: No need to distribute separate client software Changes to the interface take effect immediately Client-side

More information

Authentication CS 4720 Mobile Application Development

Authentication CS 4720 Mobile Application Development Authentication Mobile Application Development System Security Human: social engineering attacks Physical: steal the server itself Network: treat your server like a 2 year old Operating System: the war

More information

Introduction & Basics! Technical Foundation! Authentication! Obtaining a token!... 4 Using the token! Working with notes!...

Introduction & Basics! Technical Foundation! Authentication! Obtaining a token!... 4 Using the token! Working with notes!... Simplenote API2 Documentation v2.1.3: (April 18, 2011). Recent documentation changes are listed on the last page. Contents Introduction & Basics!... 3 Technical Foundation!... 3 Authentication!... 4 Obtaining

More information

Security. 1 Introduction. Alex S. 1.1 Authentication

Security. 1 Introduction. Alex S. 1.1 Authentication Security Alex S. 1 Introduction Security is one of the most important topics in the IT field. Without some degree of security, we wouldn t have the Internet, e-commerce, ATM machines, emails, etc. A lot

More information

Building Web Applications

Building Web Applications Building Web Applications Ambient intelligence Fulvio Corno Politecnico di Torino, 2017/2018 Goal Create simple web applications In Python For interactive interfaces For server-side components Learn a

More information

Smart Bulk SMS & Voice SMS Marketing Script with 2-Way Messaging. Quick-Start Manual

Smart Bulk SMS & Voice SMS Marketing Script with 2-Way Messaging. Quick-Start Manual Mobiketa Smart Bulk SMS & Voice SMS Marketing Script with 2-Way Messaging Quick-Start Manual Overview Mobiketa Is a full-featured Bulk SMS and Voice SMS marketing script that gives you control over your

More information

djangotribune Documentation

djangotribune Documentation djangotribune Documentation Release 0.7.9 David THENON Nov 05, 2017 Contents 1 Features 3 2 Links 5 2.1 Contents................................................. 5 2.1.1 Install..............................................

More information

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 08 Tutorial 2, Part 2, Facebook API (Refer Slide Time: 00:12)

More information

NIELSEN API PORTAL USER REGISTRATION GUIDE

NIELSEN API PORTAL USER REGISTRATION GUIDE NIELSEN API PORTAL USER REGISTRATION GUIDE 1 INTRODUCTION In order to access the Nielsen API Portal services, there are three steps that need to be followed sequentially by the user: 1. User Registration

More information

Attacking the Application OWASP. The OWASP Foundation. Dave Ferguson, CISSP Security Consultant FishNet Security.

Attacking the Application OWASP. The OWASP Foundation. Dave Ferguson, CISSP Security Consultant FishNet Security. Attacking the Application Dave Ferguson, CISSP Security Consultant FishNet Security Copyright The Foundation Permission is granted to copy, distribute and/or modify this document under the terms of the

More information

Business Logic Security

Business Logic Security Business Logic Security Ilia Alshanetsky @iliaa https://joind.in/14863 whois: Ilia Alshanetsky PHP Core Developer since 2001 Release Master of 4.3, 5.1 and 5.2 Author of Guide to PHP Security Author/Co-Author

More information

CONVERSION TRACKING PIXEL GUIDE

CONVERSION TRACKING PIXEL GUIDE Conversion Tracking Pixel Guide A Step By Step Guide to Installing a conversion tracking pixel for your next Facebook ad. Go beyond clicks, and know who s converting. PRESENTED BY JULIE LOWE OF SOCIALLY

More information

Replay Caching is a Pain

Replay Caching is a Pain Replay Caching is a Pain Kerberos AP exchange requires replay caching Replays bad rcaches usually hard to get right, and slow Regular disks 120 fsync()s per-disk/second Clustering ouch! Want to do something

More information

BIG-IP DataSafe Configuration. Version 13.1

BIG-IP DataSafe Configuration. Version 13.1 BIG-IP DataSafe Configuration Version 13.1 Table of Contents Table of Contents Adding BIG-IP DataSafe to the BIG-IP System...5 Overview: Adding BIG-IP DataSafe to the BIG-IP system... 5 Provisioning Fraud

More information

Web Security. Web Programming.

Web Security. Web Programming. Web Security Web Programming yslin@datalab 1 OWASP Top 10 Security Risks in 2017 Rank Name 1 Injection 2 Broken Authentication and Session Management 3 Cross-Site Scripting (XSS) 4 Broken Access Control

More information

DJOAuth2 Documentation

DJOAuth2 Documentation DJOAuth2 Documentation Release 0.6.0 Peter Downs Sep 27, 2017 Contents 1 Important Links 1 2 What is DJOAuth2? 3 3 Why use DJOAuth2? 5 4 What is implemented? 7 5 Quickstart Guide 9 5.1 Requirements...............................................

More information

PROBLEMS IN PRACTICE: THE WEB MICHAEL ROITZSCH

PROBLEMS IN PRACTICE: THE WEB MICHAEL ROITZSCH Faculty of Computer Science Institute of Systems Architecture, Operating Systems Group PROBLEMS IN PRACTICE: THE WEB MICHAEL ROITZSCH THE WEB AS A DISTRIBUTED SYSTEM 2 WEB HACKING SESSION 3 3-TIER persistent

More information

CSE361 Web Security. Attacks against the server-side of web applications. Nick Nikiforakis

CSE361 Web Security. Attacks against the server-side of web applications. Nick Nikiforakis CSE361 Web Security Attacks against the server-side of web applications Nick Nikiforakis nick@cs.stonybrook.edu Threat model In these scenarios: The server is benign The client is malicious The client

More information

OpenID Connect Opens the Door to SAS Viya APIs

OpenID Connect Opens the Door to SAS Viya APIs Paper SAS1737-2018 OpenID Connect Opens the Door to SAS Viya APIs Mike Roda, SAS Institute Inc. ABSTRACT As part of the strategy to be open and cloud-ready, SAS Viya services leverage OAuth and OpenID

More information

Building the Modern Research Data Portal. Developer Tutorial

Building the Modern Research Data Portal. Developer Tutorial Building the Modern Research Data Portal Developer Tutorial Thank you to our sponsors! U. S. DEPARTMENT OF ENERGY 2 Presentation material available at www.globusworld.org/workshop2016 bit.ly/globus-2016

More information

API Gateway. Version 7.5.1

API Gateway. Version 7.5.1 O A U T H U S E R G U I D E API Gateway Version 7.5.1 15 September 2017 Copyright 2017 Axway All rights reserved. This documentation describes the following Axway software: Axway API Gateway 7.5.1 No part

More information

Combating Common Web App Authentication Threats

Combating Common Web App Authentication Threats Security PS Combating Common Web App Authentication Threats Bruce K. Marshall, CISSP, NSA-IAM Senior Security Consultant bmarshall@securityps.com Key Topics Key Presentation Topics Understanding Web App

More information

Persistence & State. SWE 432, Fall 2016 Design and Implementation of Software for the Web

Persistence & State. SWE 432, Fall 2016 Design and Implementation of Software for the Web Persistence & State SWE 432, Fall 2016 Design and Implementation of Software for the Web Today What s state for our web apps? How do we store it, where do we store it, and why there? For further reading:

More information

How to Configure Authentication and Access Control (AAA)

How to Configure Authentication and Access Control (AAA) How to Configure Authentication and Access Control (AAA) Overview The Barracuda Web Application Firewall provides features to implement user authentication and access control. You can create a virtual

More information

OWASP TOP 10. By: Ilia

OWASP TOP 10. By: Ilia OWASP TOP 10 By: Ilia Alshanetsky @iliaa ME, MYSELF & I PHP Core Developer Author of Guide to PHP Security Security Aficionado WEB SECURITY THE CONUNDRUM USABILITY SECURITY YOU CAN HAVE ONE ;-) OPEN WEB

More information

STARCOUNTER. Technical Overview

STARCOUNTER. Technical Overview STARCOUNTER Technical Overview Summary 3 Introduction 4 Scope 5 Audience 5 Prerequisite Knowledge 5 Virtual Machine Database Management System 6 Weaver 7 Shared Memory 8 Atomicity 8 Consistency 9 Isolation

More information

INTEGRATION MANUAL DOCUMENTATION E-COMMERCE

INTEGRATION MANUAL DOCUMENTATION E-COMMERCE INTEGRATION MANUAL DOCUMENTATION E-COMMERCE LOGIN: In order to use Inkapay's e-commerce payment API you should be registered and verified on Inkapay, otherwise you can do this by entering to www.inkapay.com.

More information

Volante NACHA ISO20022 Validator AMI User Guide

Volante NACHA ISO20022 Validator AMI User Guide Volante NACHA ISO20022 Validator AMI User Guide 1. About Volante NACHA ISO20022 Validator AMI User Guide This document is referenced in the REST Services Deployment Guide. This outlines the available REST

More information

Writing Secure APIs. Armin Ronacher for PyCon.ru 2014

Writing Secure APIs. Armin Ronacher for PyCon.ru 2014 Writing Secure APIs Armin Ronacher for PyCon.ru 2014 Armin Ronacher Independent Contractor for Splash Damage / Fireteam Doing Online Infrastructure for Computer Games lucumr.pocoo.org/talks but does it

More information

Bootstrap your APEX authentication & authorisation. a presentation by

Bootstrap your APEX authentication & authorisation. a presentation by Bootstrap your APEX authentication & authorisation a presentation by Who am I? Richard Martens independant Consultant since 2012 smart4apex founding member (2010) oracle since 2002 (Oracle 8i) PL/SQL,

More information

Accounts and Passwords

Accounts and Passwords Accounts and Passwords Hello, I m Kate and we re here to learn how to set up an account on a website. Many websites allow you to create a personal account. Your account will have its own username and password.

More information

WELCOME. APEX Security Primer. About Enkitec. About the Presenter. ! Oracle Platinum Partner! Established in 2004

WELCOME. APEX Security Primer. About Enkitec. About the Presenter. ! Oracle Platinum Partner! Established in 2004 WELCOME APEX Security Primer Scott Spendolini Executive Director!1!2 About the Presenter About Enkitec! Scott Spendolini! Oracle Platinum Partner! scott.spendolini@enkitec.com! Established in 2004! @sspendol!

More information

E POSTBUSINESS API Login-API Reference. Version 1.1

E POSTBUSINESS API Login-API Reference. Version 1.1 E POSTBUSINESS API Login-API Reference Imprint Software and documentation are protected by copyright and may not be copied, reproduced, stored, translated, or otherwise reproduced without the written approval

More information

mozilla-django-oidc Documentation

mozilla-django-oidc Documentation mozilla-django-oidc Documentation Release 1.0.0 Mozilla Jun 12, 2018 Contents 1 Installation 3 1.1 Quick start................................................ 3 1.2 Additional optional configuration....................................

More information

Building a Django Twilio Programmable Chat Application

Building a Django Twilio Programmable Chat Application Building a Django Twilio Programmable Chat Application twilio.com/blog/08/0/python-django-twilio-programmable-chat-application.html March 7, 08 As a developer, I ve always wanted to include chat capabilities

More information

Ruby on Rails Secure Coding Recommendations

Ruby on Rails Secure Coding Recommendations Introduction Altius IT s list of Ruby on Rails Secure Coding Recommendations is based upon security best practices. This list may not be complete and Altius IT recommends this list be augmented with additional

More information

Web Application Security

Web Application Security Web Application Security Rajendra Kachhwaha rajendra1983@gmail.com October 16, 2015 Lecture 16: 1/ 14 Outline Browser Security Principles: 1 Cross Site Scripting (XSS) 2 Types of XSS 3 Lecture 16: 2/ 14

More information