I'm implement oauth2 in a angular frontend spring backend microservice system, where backend fetches the access-token from authorization server, then redirects to the frontend url to be saved in browser. The access-token if sent from backend through cookie header, will not work as the origins are different and cookies are ignored in browser, they can still be a part of query parameter to a GET frontend URI which I redirect to, but this would be security issue. Is there were some way of sending access-token through a POST call to the frontend? Are there alternatives to solve this issue?
2 Answers
Your way to send the token as a query param is one way to do this. A second way is to send a code as a query and then get (POST) the token from the backend inside the frontend, like this:
Backend got token -> redirect to Frontend
HTTP/1.1 303 See Other
Location: http://frontend.de/?code=xxxxxxxxx
Frontend use this code to get token.
POST /oauthtoken/ HTTP/1.1
Host: backend.de
Content-Type: application/json
{
"code": "xxxxxxxxx"
}
The RFC 7636 can be helpful by protect the code itself.
1 Comment
When backend is a REST API, it should be configured as a resource-server (not as client).
Authentication (which includes authorization-code flow for user login or client-credentials flow to identify a trusted programmatic client with a secret, etc.), as well as fetching and refreshing tokens, is clients business, not resource-server one.
As a consequence, do not try to retrieve tokens from resource-server and, instead, either:
- make your Angular app an OAuth2 client with a lib like angular-auth-oidc-client, I which case the Angular app handles redirects and tokens (but this is now discouraged)
- implement the BFF pattern where a Middleware on your servers (spring cloud gateway for instance) is the only OAuth2 client and handles redirects and tokens. In this config, the Angular app is secured with just sessions and never sees tokens. I wrote a tutorial for that on Baeldung.
headersin your request.headers: { Authorization: Bearer YOURTOKENHERE }. You must send it with every request. You can store the token in localStorage and retrieve it from there for each request you make.