Building an OAuth 2.0 Server
So recently I had to build an OAuth2 server, for those that don’t know what OAuth means, it stands for “Open Authorization”. so basically OAuth is just a protocol by which we allow secure authorization, a secure way in which a client can access resources from the resource owner(User) hosted by the resource server.
The protocol flow is as follows

now in OAuth there are 4 roles
- User
- Resource server
- Client
- authorization server
what we would be building is the Authorization server, we can implement it in different ways, but here passport and oauth2orize are used.
The way OAuth2.0 works is that a client e.g “a website”, “web app” makes a request for permission from the user via the authorization server, once the user grants permission to the client, the clients obtain a Authorization grant which are of different types.
Once the client has obtained Authorization grant, a request can be made to the authorization server to exchange the authorization grant for an access token.
Once the access token is obtained the client can now use it to get the protected resource.
Authorization Server Implementation
Passport allows us to use different types of strategies to verify client, users and access token. Going by the protocol flow .These are basically what we need to do to implement it.
here we defined all the strategies we would use i.e “passport-Http-bearer, passport-oauth2-client-password”,
Bearer strategy is used to authenticate either users or clients based on an access token (aka a bearer token). If a user, they must have previously authorized a client application, which is issued an access token to make requests on behalf of the authorizing user.
The OAuth 2.0 client password authentication strategy authenticates clients using a client ID and client secret. The strategy requires a verify callback, which accepts those credentials and calls done providing a client.

oauth2orize is a authorization server toolkit that helps to implement the OAuth 2.0 protocol. with it we are able implement the process of granting access and exchanging the grant for access token.

we connect these modules with our app.js

with this, we have built a very basic OAuth2 server.
*note some modules are not shown here, check out the oauth2orize and Passport documentation to get a better understanding.