how do I return a Bearer Token supplied by my server - swift

I'm using Vapor to handle http requests. I've implemented a registration and login, as well as other functioning code. On registration, a Bearer Token is generated, so I can return that to or write it into the page I'm about to render.
The page contains two forms, one of which generates a request that requires authorization, so I need to associate that request with the bearer token. How do I do this? Through explicitly setting headers for the form request that will be sent to the server? Via a cookie?

If you're writing a traditional web app using HTML then bearer authentication is not suitable as you can't attach custom headers with requests. You should use session based authentication as described in the docs

Related

Property header for firebase auth token api request to a custom server

I have a project including both a frontend (made with Vue) and a backend (made with Node.js). My server handles all the frontend requests and has its own mongodb. I am using firebase only for the authentications.
My problem is this: how can I make the server sure that a certain request is sent by a logged in user that has the privilege to do that request?
For instance if I have the request POST /user/:uid/products, that makes a user add a product to its account, I want to be sure that it was the actual user that made this request.
I came up with this: https://firebase.google.com/docs/auth/admin/verify-id-tokens#web, getting the user token from the frontend and checking it in the server through the firebase admin api.
I just want to know which is the right header where I should put this token. I mean, should the frontend put the created token in the "Authorization" header? Which header is the most appropriate?
It's customary to put it in the "Authorization" header, just as you said.
Typically the header is formatted like this:
Authorization: Bearer <token>
This is documented in the OAuth 2.0 Authorization Framework: Bearer Token Usage, section 2.1. Your backend should of course parse the same format.

Is it bad to have access token in OAuth redirect URL

I am building an oauth login flow and I am not sure if I have done it wrong because I will need to send the bearer token back via redirect URL, like /oauth2/redirect?token=[TOKEN]. But isn't it not recommended to have token passed along through URL? As it is pointed out in this thread:
Don't pass bearer tokens in page URLs: Bearer tokens SHOULD NOT be passed in page URLs (for example, as query string parameters).Instead, bearer tokens SHOULD be passed in HTTP message headers or message bodies for which confidentiality measures are taken. Browsers, web servers, and other software may not adequately secure URLs in the browser history, web server logs, and other data structures. If bearer tokens are passed in page URLs, attackers might be able to steal them from the history data, logs, or other unsecured locations.
I must have missed something in the whole flow and would like to understand more about this matter. Any input is appreciated!
UPDATE
Might not be correct but this is my understanding after some digging. The three means to pass token:
URL (not preferable)
Auth header
Request body
But under the oauth redirect use case, option 2 and 3 not feasible. So option 1 is the only option available. If really needed, token can be encrypted to ensure security.
I think this only means, that you should not use a GET request when the server requires the token, instead you should use POST or whatever is appropriate. In a GET request the parameters are included in the URL and those can end up in logs or other histories, other request types will send the paramters separat from the request URL.
P.S. BTW if you are not implementing the OAuth server yourself, you won't have to send a redirect url containing the token.
The basic auth header which provides a little extra security as it's required to be through TLS:
In the case of a "Basic" authentication like shown in the figure, the exchange must happen over an HTTPS (TLS) connection to be secure.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication
Also, the headers aren't logged in easy places like browser history.
From the spec,
it SHOULD NOT be used
unless it is impossible to transport the access token in the
"Authorization" request header field or the HTTP request entity-body.
https://www.rfc-editor.org/rfc/rfc6750#section-2.3

Keycloak - Retrieve JWT token via OIDC Endpoint

I'm currently trying to retrieve a user token from the keycloak token endpoint using a POST request (instead of using one of the designated adapters). I have set up a keycloak realm and added my own machine as a client. In the documentation the Token Endpoint is described as:
/realms/{realm-name}/protocol/openid-connect/token
As far as I have read in the openid specification, I will need to set the body parameter grant_type=authorization_code as well as the parameters code and redirect_uri. I will also need to set the Authorization header, for which I will need a Basic Token.
So far I will get the response:
"error": "unauthorized_client", "error_description":
"INVALID_CREDENTIALS: Invalid client credentials"
Where do I get the Basic Authorization Token from? I expected that I need to provide a username and a password, since the JWT token is what I'm trying to recieve as response. Do I need to set the redirect_url if I just want to request a token?
Keycloak offers more than one way to retrieve a user access token, following the OpenId Connect spec. Here you have the steps to do it for Authorization code flow (the one recommended for web applications) according to the openid connect spec: https://rograce.github.io/openid-connect-documentation/explore_auth_code_flow
Basically, if you're not using any adapter, when detecting a request to some protected resource you should:
Perform a redirection to the keycloak login page (keep in mind keycloak uses the REALM entity, so you'll need to specify it too):
HTTP/1.1 302 Found
Location: https://mykeycloakinstance.org/auth/realms/demo/protocol/openid-connect/auth?
response_type=code
&scope=openid
&client_id=s6BhdRkqt3
&state=af0ifjsldkj
&redirect_uri=https%3A%2F%2Fclient.example.org%2Fcb
You'll need to keep the state value in the client, as it needs to survive the redirection process:
It is recommended that client’s use this parameter to maintain state
between the request and the callback. Typically, Cross-Site Request
Forgery (CSRF, XSRF) mitigation is done by cryptographically binding
the value of this parameter with a browser cookie.
You don't interact with username/passwords. The keycloak authentication page does. Once the login is successful, it will redirect to your page with a valid code:
HTTP/1.1 302 Found
Location: https://client.example.org/cb?
code=SplxlOBeZQQYbYS6WxSbIA
&state=af0ifjsldkj
Here you'll need to either check that the state is the one you originally sent (you may need to track it through web session, using cookies) and also to obtain the token using that code. You do a POST to the authorization endpoint with this code:
POST /auth/realms/demo/protocol/openid-connect/auth HTTP/1.1
Host: https://mykeycloakinstance.org
Content-Type: application/x-www-form-urlencoded
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fclient.example.org%2Fcb
This is the flow in summary, I haven't tested the code myself, so use it as an example and don't hesitate to fix it if you consider ;-)
See also:
What are Keycloak's OAuth2 / OpenID Connect endpoints?

Pass jwt refresh token on header or body

When access token is expired, it should re-issued refresh token.
At this point, I'm little hesitate which method is better.
For access token, it passed HTTP header per every request.
pass refresh token on HTTP header.
pass refresh token on HTTP POST body(payload).
Which one is recommended?
The jwt specification recommends (but does not require) sending the access tokens in an authorization header of type Bearer. But there is no mention of the refresh tokens.
Refresh tokens are an Oauth2 concept. If you read the Rfc6749 specification, to refresh an access token, the refresh token is sent using a form parameter in a POST request
6. Refreshing an Access Token
...
POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA
You can use the example of oauth2 as reference (pass it in the body), although if you do not use oauth2, you have no obligation, so use the method to send that best suits your project.

Protecting Image resources with OAuth2 Bearer Tokens

I've created a number of Web Services that produce/consume JSON data and I've protected them using OAuth2 and Bearer Tokens, which works fine.
Now however I need to build a similar Web Service that produces images rather than JSON (so JPEG/PNG data). For consistency I would also like to protect the service with OAuth2/Bearer Tokens, but doing so would make the service more challenging to consume in browser based applications that wish to display the image data using the <img> tag, because the <img> tag will not send the necessary Authorization: Bearer ...bearer-token... HTTP header.
I can see two ways round this:
Browser based clients of the Service would use XHR Level2 and the Blob and Blob URL schemes from HTML5 to retrieve the image data as a Blob, use the Blob URL scheme to generate a URL for the Blob and then dynamically create an img tag that refers to the Blob URl. A lot of work just to display an image!
Modify the OAuth2 infrastructure to generate a Http cookie in addition to the Bearer Token. Modify the service Authorirzation to accept EITHER the Authorization: Bearer ... OAuth2 header OR the cookie as proof of identity. Cookie to have same lifetime as bearer token, httpOnly etc. Browser based clients can just rely on browser cookie support to get access to service, can deference image data via <img> tag as normal. Easy to use for browser clients, but non-standard. Security risk profile seems the same for either bearer token or cookie.
Am I overlooking any security issues with the latter approach?
Are there any alternative approaches for protecting image/media resources with OAuth2?
I assume you are using the user-agent-based application profile in terms of getting a bearer token into the browser base app.
The OAuth Bearer Token spec supports sending the token as a query parameter ?access_token=mF_9.B5f-4.1JqM. The javascript in your browser could add the token as a query parameter to your img links.
This would be more standards based, but then you would have to worry about the access_token value leaking out in logs, etc. I think the security trade offs would really depend on the scope of those bearer tokens, and how important these images are to protect.
I think opening up your OAuth infrastructure to accept cookies could open you up to new attack vectors. RFC 6750 specifically calls out the risk of CSRF attacks
Implementations that do store bearer tokens in cookies MUST take precautions
against cross-site request forgery.