Access Restful Service which is OWASP CSRFGuard protected from Different Domain - rest

My application has been built using SPRING MVC and I have exposed few Restful URIs. (Working Fine)
e.g - http://example.org/alert/alerts //get list of Alerts for the logged in user.
I have configured the application for Cross Site Request Forgery (CSRF) using OWASP CSRFGuard by following the link - (Working Fine) https://www.owasp.org/index.php/CSRFGuard_3_Configuration#Overview
The Restful services is currently been consumed by the same application's UI without having any issues. (Working Fine)
e.g - A data Grid which is part of the same WebApp is displaying list of Alerts by calling this Restful service (AJAX request)
Issue: When I try to access the same Restful services from a different domain/ Chrome Rest Client, it's doesn't return any data except for 302.
If I set The "unprotected pages" property in csrfguard.properties for the restful URIs, I am able to access the Restful service from RestClient/different domain.
Please suggest if I need to do any other configuration so that the same Restful services which are protected by CSRF can be accessed from a different domain/Chrome rest Client.

1.if you are generating CSRF Token at server side then
provide one get request inside that request validate session and send the created CSRF Token as hidden to client, now remaining request should be POST,PATCH,PUT or DELETE which are getting CSRF Token in every request header.
2. if you are generating CSRF Token at client side then from first request which is authentication or authorization get the value of Token and compare it with every request in your custom filter.

Related

CSRF Tokens with separate API and Web Server

I am learning about CSRF Tokens and how they help secure your web application. I understand the basics of it, but I am confused as to how it works in practice when the web server and api are separate. In practice how is the token generated, added to the HTML and known by the API?
For example, if I host my web app on something like Nginx or S3 and serve APIs via Spring Boot, how does the HTML with the embedded token get generated and passed to the client? Would the Sprint Boot API need to generate the token and HTML and return that to the client? Is there a different flow that am I missing? If this is the case, what is the point of it being embedded in HTML at all?
All of the documentation I have read assumes you are using something like MVC or skips over this entirely.
CSRF protection is only necessary for requests made by a client (for example, a browser) that silently adds credentials for the current user, by sending a session cookie, resending username and password that were previously typed in ("Basic Authentication") or by including a client certificate. This is because users may be tricked into making unwanted such requests by visiting a malicious web page, and these unwanted requests are then made with their credentials, that is, on their behalf.
For requests made by your web server to an API endpoint, this does not apply, therefore the API endpoint need not offer CSRF protection. A web server cannot be tricked into making unwanted requests.
Or can it? Imagine that the web server offers a "proxy" endpoint that converts incoming requests into requests to the API endpoint, and that sends the API response back to the client:
Client --request--> web server --converted request--> API endpoint
Client <--converted response-- web server <--response-- API endpoint
Further imagine that, as part of the request conversion, credentials from the client are forwarded to the API. For example, a session cookie coming from the browser is converted into an Authorization: Bearer <jwt> header that is sent to the API endpoint. Then an unwanted request to the web server endpoint with credentials effectively becomes a request to the API, and a new CSRF vulnerability has appeared: this time on the web server.
The web server must then protect its own "proxy" endpoint against CSRF by issuing and validating a CSRF token.

How to perform user registration and authentication between a single page application and a REST API with OpenID Connect

Consider that we have:
An SPA or a statically generated JAMStack website.
A REST API.
The website is being served with nignx that also reverse proxies to our API.
--
It is required that a user should be able to register/authenticate with an identity provider (say, Google) through the OpenID Connect protocol. For the sake of simplicity, let us assume that the user has already registered with our API.
Talking about authentication using OIDC, from what I have read on the subject, the steps you take are the following:
Register the application with the IdP and receive a client id and a secret.
When the user initiates a login (with Google) request on the API ('/api/loginWithGoogle') the API sets a state variable on the request session (to prevent CSRF) and redirects the user-agent to the IdP's login page.
At this page, the user enters their credentials and if they are correct, the IdP redirects the user to the callback URL on the API callback (/api/callback).
The request received on the callback has the state parameter (which we should verify with the one we set on the session previously) and a code parameter. We exchange the code for the identity token with the authorization server/IdP (we also receive access/refresh tokens from the auth server, which we discard for now because we do not want to access any APIs on the behalf of the user).
The identity token is parsed to verify user identity against our database (maybe an email).
Assume that the identity is verified.
-- The next part is what's giving me trouble --
The documentation that I have read advises that from here we redirect the user to a URL (e.g. the profile page)and start a login session between the user agent and the API. This is fine for this specific architecture (with both the SPA/static-site being hosted on the same domain).
But how does it scale?
Say I want to move from a session based flow to a JWT based flow (for authenticating to my API).
What if a mobile application comes into the picture? How can it leverage a similar SSO functionality from my API?
NOTE: I have read a little on the PKCE mechanism for SPAs (I assume it works for JAMStack as well) and native mobile apps, but from what I gather, it is an authorization mechanism that assumes that there is no back-end in place. I can not reconcile PKCE in an authentication context when an API is involved.
Usually this is done via the following components. By separating these concerns you can ensure that flows work well for all of your apps and APIs.
BACKEND FOR FRONTEND
This is a utility API to keep tokens for the SPA out of the browser and to supply the client secret to the token service.
WEB HOST
This serves unsecured static content for the SPA. It is possible to use the BFF to do this, though a separated component allows you to serve content via a content delivery network, which some companies prefer.
TOKEN SERVICE
This does the issuing of tokens for your apps and APIs. You could use Google initially, though a more complete solution is to use your own Authorization Server (AS). This is because you will not be able to control the contents of Google access tokens when authorizating in your own APIs.
SPA CLIENT
This interacts with the Backend for Frontend during OAuth and API calls. Cookies are sent from the browser and the backend forwards tokens to APIs.
MOBILE CLIENT
This interacts with the token service and uses tokens to call APIs directly, without using a Backend for Frontend.
BUSINESS APIs
These only ever receive JWT access tokens and do not deal with any cookie concerns. APIs can be hosted in any domain.
SCALING
In order for cookies to work properly, a separate instance of the Backend for Frontend must be deployed for each SPA, where each instance runs on the same parent domain as the SPA's web origin.
UPDATE - AS REQUESTED
The backend for frontend can be either a traditional web backend or an API. In the latter case CORS is used.
See this code example for an API driven approach. Any Authorization Server can be used as the token service. Following the tutorial may help you to see how the components fit together. SPA security is a difficult topic though.

Approah on creating clients/realms for separate service (frontend and backend)

I'm new to keycloak and would like to check what is the common design on the said architecture.
I have 1 backend(quarkus) 1 frontend (angular) and 1 flutter.
I would like to see if I could leverage the features of client. My idea is to have a separate client within the realm. For example
REALM = MyAppRealm
Client = backend-client and front-endclient
Is it possible that the token i got from front-endclient can be use to access the api from the backend?
Reason I have this setup is that the front-endclient has a public accesstype while the backend has confidential
to sum up. I would like to see if i can reuse the token i got from front-endclient to my backend-client
Yes of course you can do that.
The purpose of openid is to share authentication and authorization between a diversity of clients without needing to share credentials (no password is known by any of the clients). A trusted third party (here Keycloak) will give back a signed token in exchange for credentials. And this token will be a proof of who the user is and what he is allowed to do in the communications between the frontend and backend.
To sum up :
Your angular frontend authenticates an user using a public client and an implicit flow. When successfully authenticated, the frontend obtains an access token and a refresh token.
When making a REST call to the backend, your frontend needs to set the header Authorization using the access token as a bearer token ('Authorization: Bearer insert access token here'). You can automate this by using an interceptor (example)
Finally, when your backend receive an API request it can check the Authorization header to ensure the request is authenticated and authorized. For how to do that with Quarkus, everything is explained in this documentation page : https://quarkus.io/guides/security-openid-connect

angular2 login page for a web client to a back-end REST service

I am writing an Angular2 client web application client as a front end for a REST services providing access to some resources.
The REST service is protected with basic HTTP auth, and allows unauthenticated access for some of its endpoints (for instance GET /freeresource), while requires user/password authentication for other endpoints (say GET /protectedresource, or POST /freeresource, etc.).
For my Angular2 client, I would like to implement a loging page allowing access to the web application with the same ":" accepted by REST service. For this I'm following this tutorial : https://medium.com/#blacksonic86/angular-2-authentication-revisited-611bf7373bf9#.myifbz656
The problem is that the above tutorial assumes that the backend REST service has an explicit /login endpoint returning an authentication token to which you post your credentials, while my REST service does not have such an endpoint, but just returns an authorization error when passed missing or wrong credentials for endpoints that require them. I didn't find any alternative article or tutorial for a situation like this.
What is the correct way of proceeding in such a case? I could "simulate" the /login endpoint by accessing for instance a protected resource with username and password read from the app login page and trying to access a protected resource GET /protectedresource, considering as a failed login if this call returns an unauthorized error, but clearly this is not a satisfying solution (what today is a protected resource could become freely accessible tomorrow, for instance), so what is a "clean" way to implement the web app login in this case?
You don't need to simulate the /login endpoint. You just need to know on the client accessing which resource requires authentication. You can implement the same "CanActivate" method from the tutorial, and write your service call to pass credentials (or use the local storage if the user is authenticated already) when you make the REST call. If your REST endpoints require authentication every time, get them from the user at the login page, store them in the local storage, then pass them to the endpoints that need authentication.

Grails & Spring Security & Facebook & Oauth2 - Restfull server

What would be the actual solution to build a server with Grails and Spring Security that meets the following requirements :
Access to the server would be restfull, so only by third party clients (mobile,...)
The authentication would use the oauth2 facebook services and the client would use a facebook SDK to provide a token to the server
The authentication would be on per request basis so the token would be passed on the request as GET parameter (not POST as the Rest API uses it)
No need to access Facebook user's information, only authentication
I tried Spring Security Facebook but the Json filter only returns user details so no per request or per session authentication.
I noticed Spring Security Oauth2 Provider but to me it's a provider and not a consumer that could plug into another provider like Facebook so no clue on how to use it.
Spring Social doesn't seem to meet my requirements.
As a result of this search for information, I intend to write a plugin to create a Restfull server connected to facebook.
Thanks in advance
You could implement a security filter on the top of all your requests, and then if the request contains an auth header for the API you respond with as a restful API, otherwise you redirect your users to the login page, handled by the oauth authentication service, where you let the users login with the oath method (facebook, mozilla persona or whatever you like)