Coder Social home page Coder Social logo

udemyoauth2.0's Introduction

The Nuts and Bolts of OAuth 2.0

by Aaron Parecki

Get the course

Section 1:

  • History of OAuth:

"OAuth started around November 2006, while Blaine Cook was working on the Twitter OpenID implementation. He got in touch with Chris Messina looking for a way to use OpenID together with the Twitter API to delegate authentication. They met with David Recordon, Larry Halff, and others at a CitizenSpace OpenID meeting to discuss existing solutions. Larry was looking into integrating OpenID for Ma.gnolia Dashboard Widgets. After reviewing existing OpenID functionality, as well as other industry practices, they came to the conclusion that there was no open standard for API access delegation. The conversation continued online and off for a few months.

In April 2007, a Google group was created with a small group of implementers to write a proposal for an open protocol. It turned out that this problem wasn’t unique to OpenID and when DeWitt Clinton from Google caught wind of the project, he expressed his interest in supporting the effort, if only as a stakeholder. In July 2007 the team drafted an initial specification and the group was opened to anyone interested in contributing. On October 3rd, 2007 the OAuth Core 1.0 final draft was released." Reference

  • How Oauth improves application security

"Many luxury cars today come with a valet key. It is a special key you give the parking attendant and unlike your regular key, will not allow the car to drive more than a mile or two. Some valet keys will not open the trunk, while others will block access to your onboard cell phone address book. Regardless of what restrictions the valet key imposes, the idea is very clever. You give someone limited access to your car with a special key, while using your regular key to unlock everything.

Every day new websites launch offering services which tie together functionality from other sites. A photo lab printing your online photos, a social network using your address book to look for friends, and APIs to build your own desktop application version of a popular site. These are all great services – what is not so great about some of the implementations is their request for your username and password to the other site. When you agree to share your secret credentials, not only do you expose your password to someone else (yes, that same password you also use for online banking), you also give them full access to do as they wish. They can do anything they wanted – even change your password and lock you out.

This is the problem OAuth solves. It allows you, the User, to grant access to your private resources on one site (which is called the Service Provider), to another site (called Consumer, not to be confused with you, the User). While OpenID is all about using a single identity to sign into many sites, OAuth is about giving access to your stuff without sharing your identity at all (or its secret parts)." Reference

  • OAuth vs OpenId Connect

OAuth is Accessing APIs vs OpenId which is Identifying Users. OAuth is used for authorization, OpenID is used for authentication.

oauth2

OAuth And OpenID Connect Core Concepts6

OAuth And OpenID Connect Core Concepts5

Quiz 1

  1. Is there ever a reason to enter your Google password in a third party app? No, Google requires that all third-party and even first-party apps use OAuth and never accept passwords directly. This gives them the most security and most flexibility for adding new multifactor auth methods in the future as well.

  2. a risk to the user of entering their password directly into an application? The application can potentially access and modify all data in their account. When you give your password to an application, you have no way of knowing what it will do with the password, even if it claims it will only access a limited amount of information

  3. True or false: OAuth was created to be a single-sign-on protocol FALSE - OAuth was created as a delegated authorization protocol. It has been extended to be used as a single-sign-on protocol through things like OpenID Connect, but that was not its original goal.

  4. True or false: OAuth provides the application with the identity of the user signing in FALSE - In order to learn the user’s identity, applications need to use OpenID Connect or a custom API of the OAuth service.

  5. True or false: OpenID Connect provides the application with the identity of the user signing in TRUE - OAuth only provides the application with an access token. OpenID Connect was created as an extension of OAuth in order to provide the application with the user’s identity information.

  6. True or false: OAuth provides a way for an application to get an access token to make API requests TRUE - This is the exact thing OAuth was created to solve. This is also called delegated authorization.

  7. True or False: Applications need to be able to parse access tokens to be able to use them FALSE - Just like a hotel key, the application using the access token doesn’t need to know anything about how it works. Applications should just use the access token in an API request and let the API figure out if it’s valid.

Section 2: API Security Concepts

  • Roles in OAuth
  1. The User - the resource owner
  2. The Device - user agent
  3. The Application - oauth client
  4. The API - where the data lives - resource server

Authorization server - creates an access token which then is given to the app to get the password. The app makes an api request but never sees the password.

API Gateway is always in the resource server

  • Application Types Confidential & Public Clients

The difference between the two is the deployment credentials.

Confidential applications can hold credentials in a secure way without exposing them to unauthorized parties. They require a trusted backend server to store the secret(s).

Credentials cannot be securely stored in public applications.

Reference

  • User Consent

Concent screen being critical to the flow

Password grant - app sends password prompt to user, user gives permisions and provides password then server provides an access token

2022-01-31_23-33-45

consent-dialog

  • Front Channel vs Back Channel

describes the 2 different ways how data moves around between systems:

back channel: normal/ secure, HTTPS client to serever connection (certification, encription, trusted)

Backend request with java is done with ajax or fetch

front channel: using address bar to transfer data (uncertainty) flow-channels-5d8996b3706cab1e4ac8f9ed716d6529d3970f91cbc3cb5ff5a21a94389d0e1d reference

  • Application Identity

Authorization code flow

PKCE (pronounced "pixy") is a security extension to OAuth 2.0 for public clients on mobile devices, designed to prevent interception of the authorisation code by a malicious application that has sneaked into the same device. reference

Redirect URI

Quiz 2

  1. When a user is using Travis CI to test code from GitHub, GitHub is playing which of the OAuth roles? Authorization Server and Resource Server - Even though GitHub is one piece of software, it is playing two roles in the OAuth flow

  2. When a user is using Travis CI to test code from GitHub, Travis CI is playing which of the OAuth roles? Client - A "client" in OAuth is the one that's trying to access resources using an access token

  3. If you are building an iPhone app, using an external service as your Authorization Server, which roles are you building? Client

  4. If you are building an API, using an external service as your Authorization Server, which roles are you building? Resource Server

  5. If you are building an application with a .NET backend, which type of application are you building? Confidential

  6. If you are building a mobile app, which type of application are you building? Public

  7. Which of the below is considered a “public client”? An iPhone app used only by employees - Mobile apps don’t have the ability to be deployed with credentials, so they are considered public clients. The users of the app are not significant to this distinction.

  8. Which of the below is considered a “confidential client”? A server-side Java app for publising blog posts - Even though the app will be used to create public content, the application is considered a "confidential client" since it can be deployed with credentials

  9. Which is the better description of the term “back channel”? A request from an HTTP client to an HTTP server - Any HTTP client that makes a request to an HTTP server is using the back channel, even if that client is JavaScript code in a browser

  10. Which is the better description of the term “front channel”? Sending data by making the browser redirect - Using the browser’s address bar to move data between two other pieces of software is using the front channel.

Section 3: OAuth Clients

The application thats getting and using access tokens to make API requests.

Assignment 1:

Sign up at developer.okta.com then follow along with exercises. assignemt1 saved uri

Section 4: OAuth for Server-side applications

  • Registering an appliction

"When a developer comes to your website, they will need a way to create a new application and obtain credentials. Typically you will have them create a developer account, or create an account on behalf of their organization, before they can create an application.

While the OAuth 2.0 spec doesn’t require you to collect any application information in particular before granting credentials, most services collect basic information about an app, such as the app name and an icon, before issuing the client_id and client_secret. It is, however, important that you require the developer to register one or more redirect URLs for the application for security purposes. This is explained in more detail in Redirect URLs." Reference

  • Authorization Code Flow for Web Applictions The user is using their browser to access the application which needs an access token from the OAuth server so it can make an API request at the API. End goal is to get the access token from the back channel. The browser should never see the access token.

auth-sequence-auth-code

  1. The user clicks Login within the regular web application.

  2. Auth0's SDK redirects the user to the Auth0 Authorization Server (/authorize endpoint).

  3. Your Auth0 Authorization Server redirects the user to the login and authorization prompt.

  4. The user authenticates using one of the configured login options and may see a consent page listing the permissions Auth0 will give to the regular web application.

  5. Your Auth0 Authorization Server redirects the user back to the application with an authorization code, which is good for one use.

  6. Auth0's SDK sends this code to the Auth0 Authorization Server (/oauth/token endpoint) along with the application's Client ID and Client Secret.

  7. Your Auth0 Authorization Server verifies the code, Client ID, and Client Secret.

  8. Your Auth0 Authorization Server responds with an ID Token and Access Token (and optionally, a Refresh Token).

  9. Your application can use the Access Token to call an API to access information about the user.

  10. The API responds with requested data.

Reference

Be careful of the Authorizaion injection code attack "With a client secret and authorization code, a malicious application can effectively impersonate the original application for which the authorization code was issued." Reference

whattofetch

Assignment 2

The goal of this exercise is to get an access token using the authorization code flow and PKCE. This exercise will walk you through the flow manually without writing any code. You are of course free to write code to do this instead if you’d like, but the instructions here will show you the step by step process of what’s happening under the hood.

applications create uri

alloweveryone

secrets

paste setup

URL404page 404help After clearing cookies and restating I still have the same 404 error. My issue was the link I had inserted - I needed to use the example link when I used my URL link.

tanksE signin smieface token done

Section 5: OAuth for native applications

Mobile apps: Redirect URL

Claiming URL patterns etc

Custom URL Scheme: Register a custom URL scheme that will launch the app when a URL with that scheme is visited from the system browser.

The native app starts the OAuth flow as normal, by launching the system browser with the standard authorization code parameters. The only difference is that the redirect URL will be a URL with the app’s custom scheme.

When the authorization server sends the Location header intending to redirect the user to myapp://callback#token=...., the phone will launch the application and the app will be able to resume the authorization process, parsing the access token from the URL and storing it internally.

Custom URL Scheme Namespaces: Choose URL schemes that won’t conflict with other apps.

Your service can help by requiring the URL scheme to follow a certain pattern, and only allow the developer to register a custom scheme that matches that pattern.

Example; Facebook generates a URL scheme for every app based on the app’s client ID. fb00000000:// where the numbers correspond to the app’s client ID. This provides a reasonably sure method of generating globally unique URL schemes, since other apps are unlikely to use a URL scheme with this pattern.

Or reverse domain name pattern with a domain that is under the control of the app’s publisher, resulting in a URL scheme of com.example.myapp for example. It's something that can be enforced by the service. Reference

hoauth-flow

abbriviations Reference

codeflow Code flow native apps

Assignment 3

Similar process to Assignment 2 but for native apps.

Go into your applications - click applications applications method

new

Under Sign-in redirect URIs, replace the default value with https://example-app.com/redirect as the redirect URI for your application

uri

wroks get didt

bash1

gra success bashih native

Section 6: OAuth for singlepage applications

Javascript is seen as a public client becuase you can't store your API key in the code. You can't hide it becuase it could be reversed engineered. You can do an OAuth flow with PKCE code. Be careful of cross site scripting attacks. Known as XSS.

Have a strong content security policy.

Hotlinking javascripts are potentioal risks. Try to avoid. User could have extensions in their browser that could gain access, so you need to plan for all these kinds of breaches.

Authorization code flow: The flow starts out with the user clicking the login button EG : User says, "I would like to use this application." Before the app redirects the user, it first makes up a new secret for this particular flow. This is not a client secret. This is a random string the app generates and it has to be different every time itstarts a flow. This is called the PKCE code verifier. It holds on to that code verifier in the browser, usually by storing it in LocalStorage or SessionStorage and then it calculates a hash of it called the code challenge.

Hash = a one way operation.

If somebody knows the hash value, they can't reverse engineer it and figure out the secret. It takes that hash and includes it in the URL that it goes and builds, which tells the browser to go over to the OAuth server. The app redirects the user to the server with a bunch of stuff in the query string, including that hash, the client ID, the redirect URL, and scope. The user ends up at the server delivering the message the app sent." Code flow single page apps

Javascript storing:

  • LocalStorage: local api, will last even when browser is closed, each tab stores data
  • SessionStorage: data stored only while windows are open, every tab gets new data
  • Cookies

Possibily keep tokens in memory or store tokens in a service worker.

But even better is don't even give tokens to javascript apps. This is how:

  • Dynamic backend server
  • HttpOnly

Assignment 4:

new page

assi works

yay done

pkce term

Section 7: OAuth for the Internet of things

Limitations of ioT(internet of things) like apple tv and smartphone devices if the browser/keyboard is not on the device then there is an issue with the previous situations encountered.

The device flow: There is a pop up (a URL and a code to go enter at that url) that tells you to type in a code that is sent to another device. Doesn't need your device to connect to your phone but only needs the oAuth. api saqava

Section 8: Client Credentials Flow

Client credentials grant = no user/ browse involved

Getting a token without a user

Only machine-to-machine.

Assignment 5: Getting an Access Token with the Client Credentials

new app term done

Section 9: OpenID Connect

OpenID connect is an extension of OAuth. Main goal is to communicate information about users to applications. OAuth is maining applications accessing Apis, OpenID connect learns info about users.

ID Token - They are always JWT (JSON Web Tokens) jwt dec

The difference between an ID Token and an Access Token They are very different so do not get confused - they are not even remotly the same. diff

They have different audiences.

How to obtain an ID Token:

  • scope=openid
  • response_type=id_token

Hybrid Flows: Combinations of response types

  • response_type=code+id_token
  • response_type=token+id_token

Dont use these response type tokens to avoid leakage in front channel. ignore

Use PKCE and auth flow for maximum security.

Step 1: Validate the signature - know which key to use. Step 2: Double check the time so it doesn't or isn't expired. Step 3: If the token is stored and comes from somewhere else then it needs to be revalidated.

Assignment 6

correct srg

sg decode ergd

working

yay

You don’t need to verify the JWT signature of the ID token: because when you get the ID token over the back channel, you already know it’s valid and where it came from, so checking the JWT signature doesn’t give you any new information and is unnecessary.

Section 10: Protecting an API with OAuth

OAuth doesn't care what format the access token is in. But the API doesn't know then how to read the information.

Section 11: Access Token Types and their Tradeoffs

Access Tokens:

  • Reference token
  • Structured token
  • Self encoded token

Cache layer:

  • Memcache
  • Redis

Only the API reads the access token

Reference token: Pros

  • Simple
  • Easy to revoke
  • Token data is not visible

Cons

  • Must be stored in the database
  • Requires network to validate

Self encoded token: Pros

  • Can be valdated without network
  • Don't need shared storage

Cons

  • JWT contents are visible
  • No way to revoke them

Assignment 7: Protecting an API endpoint with access tokens

se1 api sfdv def qefac

Reference test

Drawbacks of validating access tokens this way: This method of token validation requires that your API make a request over the network, adding network latency to every API request.

An alternative way for an API to validate access tokens: These access tokens are JWTs, the API could validate the JWT locally without going over the network.

Section 12: JWT Access Tokens

Pros and Cons using JWT Pros

  • No Database Table
  • Simpler to use if careful
  • Used across services

Cons

  • Compromised Secret Key
  • Cannot manage client from the server
  • Cannot push Messages to clients
  • Crypto-algo can be deprecated
  • Data Overhead
  • Complicated to understand

Reference

SAMPLE JWTCL RES Reference

Custom claims You can define your own custom claims which you control and you can add them to a token using a rule. You must use collision-resistant name using namespacing (which Auth0 requires).

  • Add a user's email address to an access token and use that to uniquely identify the user.
  • Add custom information stored in an Auth0 user profile to an ID token.

Public claims You can create custom claims for public consumption, which might contain generic information like name and email

  • auth_time
  • acr
  • nonce

Private claims You can create private custom claims to share information specific to your application. For example, while a public claim might contain generic information like name and email, private claims would be more specific, such as employee ID and department name.

(Validate Access Tokens)[https://auth0.com/docs/secure/tokens/access-tokens/validate-access-tokens]

(API Gateway)[https://auth0.com/docs/customize/integrations/aws/aws-api-gateway-custom-authorizers]

Quiz 3

  1. Which of the following is true about JWTs? Once a JWT is created it can never be changed

  2. FALSE: Access tokens in OAuth are always JWTs OAuth does not define any particular format for access tokens. That said, there is a recent extension to OAuth to formalize the use of JWTs as access tokens that an authorization server can optionally follow.

  3. What is the structure of a JWT? Header, Payload, Signature

  4. Which of the following is true about encoding and encrypting JWTs? JWTs can be encrypted and signed, but do not have to be either encrypted or signed. With the highly insecure “alg: none” method, no signature is included in the JWT. This method is not recommended.

  5. The JWT spec requires the following claims in the payload No claims are required - The core JWT spec does not require any claims, but it does define a few registered claims that implementations can use if they wish.

  6. The JWT OAuth Access Token spec requires the following claims in the payload 6

  7. Which of the following is a disadvantage of an API always doing remote token introspection? It adds network latency to every API request

  8. Which of the following is an advantage of an API always doing remote token introspection? The API doesn't need to worry about whether a token has been invalidated before its expiration

  9. Which of the following is a disadvantage of an API always doing local token validation? The API will be unaware if a token became invalid before it expired By only looking at the token itself, the API is looking at a snapshot of the state of the system when the token was issued, not the current state of the system.

  10. Which of the following is an advantage of an API doing local token validation? Virtually no additional latency is added to the Api request - Since local token validation does not require network requests, the performance cost of doing this validation is nearly zero.

Section 13: Choosing Token Lifetimes

Increase security by using short lifetime tokens

Quiz 4: Lifetime

  1. Which would be a more secure access token lifetime if your APIs are doing local token validation? 1 hour

  2. Which access token lifetime would be less disruptive to users? 24 hours

  3. Which access token lifetime would be most disruptive to users? 1 hour

  4. FALSE: Refresh token lifetimes always correspond to the session lifetime at the OAuth server

  5. FALSE: All access tokens issued by an OAuth server have to have the same lifetime The OAuth server is free to make up its own policies about token lifetimes Token lifetime may depend on many factors, including but not limited to the particular application, the user, or a group the user is in

  6. Which type of application has the highest user experience cost when the application has no refresh token and needs to get a new access token? Mobile Apps - Mobile apps have to launch an in-app browser in order to get new access tokens without a refresh token, which will always be visible to the user

  7. Which would be the most appropriate access token lifetime for admin users compared to consumers, and why? 2 hours, because you want to ensure the user is actively using the application Short token lifetimes force the application to frequently get new access tokens, reducing the risk of access tokens being used without the user’s knowledge

Section 14: Handeling Revoked or Invalidated Tokens

Reasons why and access toekn may become invalid

  • A deactivated account
  • User revoking access to the application
  • Changed password
  • Immediate changes in the token system rolled out by the devs

The problem with local validation

  • local validations can't live inside the token
  • you won't know if a token has been revoked for other reasons

Assignment 8: Handeling revoked Tokens

If your API were validating tokens by looking at only the JWT signature and claims, would you be able to tell if a token was revoked? The revocation information lives only in the authorization server, so the token will look the same before and after it’s revoked, meaning your APIs would not know if a token had been revoked if they are only looking at the token itself.

Section 15: Scopes

"Scope is a mechanism in OAuth 2.0 to limit an application's access to a user's account. An application can request one or more scopes, this information is then presented to the user in the consent screen, and the access token issued to the application will be limited to the scopes granted.

The OAuth spec allows the authorization server or user to modify the scopes granted to the application compared to what is requested, although there are not many examples of services doing this in practice.

OAuth does not define any particular values for scopes, since it is highly dependent on the service's internal architecture and needs. Github, Slack, FitBit, Google are services that are an example of this." Reference

Assignment 9: Enforce Scopes in your API

What scopes are you thinking about creating for your own API? I'd love to try out GET images or GET themes in scopes under create. But they all seem very helpful and useful.

Section 16: Conclusion

OAuth 2.1 (More modern version)

  • Authorization Code + PKCE
  • Client Credentials
  • Tokens in HTTP Header
  • Tokens in POST Form Body

New developments coming up.

Additional Recources: EBook Playground

done

Last Edit July 2022

udemyoauth2.0's People

Contributors

rominalodolo avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.