Minimal Angular OAuth2 demo App with Client Credentials Grant.
Note: The Client Credentials grant is used when applications request an access token to access their own resources, not on behalf of a user. It's generally for backend server to server and not for SPA.
- clone project with git.
- install dependencies:
npm install. - build the app with server-side-rendering:
npm run build:ssr. - start app:
npm run serve:ssr - open browser, navigate to
http://localhost:3000
When user navigate to the /home, before angular ssr rendering the page, the express server will check if the token exists in memory cache:
- if token cached and valid, pass the request to angular ssr
- if token not existed or expired, then re-generate the token and save to cache
Then angular ssr will start to render the page.
- for ssr, the guard will use
InMemoryStorageServiceto get/set the token. If token not existed or expired, then get the token from server API. When the angular component has api call, the ssr interceptor will auto set the token header. After rendering finished, the redered html will send to client. - for ssr-csr transmission, if token or api has transfered from ssr, then csr won't get the token or api from browser again.
- for pure csr flow, will use
localStorageto get/set the token.
It's important to handle the error with the API:
- if get token failed from remote server, then only the page reload will retry to get token
- if api request failed, then won't save error response in state, the api call will execute in browser each tome