Securing REST API in Grails and Spring Security - rest

I have split my Grails app into two apps - a customer facing web app and a separate app that hosts a REST api. I am doing this because I'm building an iOS app to go with my web app. My app uses Spring Security and I want to secure the REST api. I've surprisingly found very little information on the proper way to do this. Should I implement oauth with Spring Security, thus making my API app an oauth provider?
Any suggestions would be great.

Yes, I just did this for another application. You have to tell spring security to behave differently when the REST URLS are accessed.
Add this to your config.groovy
Now you will have two parts of your application that are authenticated in the following manner
a) Anything with /api ( assuming thats how you have your REST set up) in the URL, gets the basic authentication
b) Everything else , goes through the login page.
// making the application more secured by intercepting all URLs
grails.plugins.springsecurity.useBasicAuth = true
grails.plugins.springsecurity.basic.realmName = " REST API realm"
grails.plugins.springsecurity.securityConfigType = SecurityConfigType.InterceptUrlMap
//Exclude normal controllers from basic auth filter. Just the JSON API is included
grails.plugins.springsecurity.filterChain.chainMap = [
'/api/**': 'JOINED_FILTERS,-exceptionTranslationFilter',
'/**': 'JOINED_FILTERS,-basicAuthenticationFilter,-basicExceptionTranslationFilter'
]

I've been working during the last weeks on a plugin that covers exactly what you want to do:
http://grails.org/plugin/spring-security-rest
Have a look at it and let me know if you have any problem.

Related

Spring boot oauth2 integration with keycloak using Spring webflux along with multi-tenancy

I need to implement Authentication & Authorization using spring boot oauth2 with keycloak as a provider.
I also need to support muti-tenancy. I tried example with authentication using spring-boot-starter-auth2-client to authenticate, but not able to add multi-tenancy.
When I used spring-boot-starter-auth2-client, I need to configure hardcode keycloak urls(specific to one tenant) in properties and not able to support multi-tenancy.
I also analyze spring-boot-starter-auth2-resouce-server, but not clear. I understand that resouce server use for validation of token and expiry.
Note: I don't want to use keycloak adapter library which is provided by keycloak.
Could you please help me -
Where need to use spring-boot-starter-oauth2-client and spring-boot-starter-oauth2-resouce-server?
Is spring-boot-starter-oauth2-resouce-server also use to authentication?
How to authenticat user using spring-boot-starter-oauth2-client and pass to spring-boot-starter-oauth2-resouce-server for authorization.
How to implement multi-tenacy e.g. take tenant id from url and redirect user to tenant specific keycloak login page.
I tried some example but won't succeed, working example will be helpful with -
Spring Webflux + spring-boot-starter-oauth2-client+ spring-boot-starter-oauth2-resouce-server + multi-tenancy + keycloak as a provider.
Thanks & Regards,
Pravin Nawale
tried some example found on internet, but didn't work.
This question should not be answered because:
it is actually a container for many questions
quite a few are way too wide or lack precision.
But as it seems to be a first question... (break it down next time, give more details and edit your question when you get comments asking precisions)
1. Where need to use spring-boot-starter-oauth2-client and spring-boot-starter-oauth2-resouce-server?
This one is important to start with as I suspect you lack OAuth2 background, specifically regarding involved parties and how it is implemented with spring-security:
spring-boot-starter-oauth2-client is to be used with OAuth2 clients:
apps serving UI with oauth2Login (#Controllers with methods returning template names)
apps consuming REST APIs with auto-configured Spring client: WebClient, #FeignClient, RestTemplate
spring-boot-starter-oauth2-resouce-server is to be used with resource-servers: apps serving REST APIs (#RestController or #Controller with #ResponseBody)
Now, if your app has controllers for both the resources and the UI to manipulate it (with Thymeleaf or any other server-side rendering engine), then define two different security filter-chains: one for each, ordered, and with securityMatcher in the first in order to limit the routes it applies to (the second being used as fallback for unmatched routes). Sample in this answer (the sample is for servlet, but it's the exact same principles): Use Keycloak Spring Adapter with Spring Boot 3
2. Is spring-boot-starter-oauth2-resouce-server also use to authentication?
OAuth2 requests should be authorized with an Authorization header containing a Bearer access-token.
The client is responsible for acquiring such an access-token from the authorization-server before sending requests to resource-server.
Your question is not quite clear but here are a few statements which could answer:
resource-server should return 401 (unauthorized) and not 302 (redirect to login) when authorization is missing or invalid => do not configure oauth2Login in resource-server filter-chain. Again, this is client business
resource-server is responsible for resources access-control: check that access-token is valid, that the user has required authorities, etc.
3. How to authenticat user using spring-boot-starter-oauth2-client and pass to spring-boot-starter-oauth2-resouce-server for authorization.
This question is not focused enough to get a single answer: what kind of client? what kind of request? context?
I see three main cases here:
the UI is rendered on Spring server with Thymeleaf, JSF, and alike => use spring's oauth2Login and refer to its documentation to overrides defaults and implement your authorization-server selection logic
the UI is rendered in the browser (Angular, React, Vue, ...) and you are ok to make it an OAuth2 client => find a certified client lib for your framework and implement the logic in the client (angular-auth-oidc-client, for instance, supports multi-tenancy)
the UI is rendered in the browser, but you prefer to implement the Backend For Frontend pattern to hide tokens from browser, then choose a BFF (like spring-cloud-gateway with tokenRelay filter) and refer to its doc for implementing your logic in it
If that can be of any help, I have:
here a tutorial for configuring an app with a Thymeleaf UI client and REST API
there a sample repo with an Angular workspace (app configured as OIDC client + API client lib generated from OpenAPI spec) and spring-boot resource-server (using servlet, but this makes no difference to the client).
4. How to implement multi-tenacy e.g. take tenant id from url and redirect user to tenant specific keycloak login page
Note
One of key principles of OAuth2 is that identities (tokens) are emitted (issued) by trusted 3rd parties (authorization-servers) => you must configure the list of issuers your resource-servers can trust (and clients can fetch tokens from). This list is static (loaded with conf at startup).
Accept identities from various issuers on the resource-server
This is done by overriding the default ReactiveAuthenticationManagerResolver<ServerWebExchange> in your SecurityWebFilterChain configuration: http.oauth2ResourceServer().authenticationManagerResolver(authenticationManagerResolver)
I provide with thin wrappers around spring-boot-starter-oauth2-resource-server which support multi-tenancy just by defining properties. Complete sample there:
Instead of spring-boot-starter-oauth2-resource-server (which is a transient dependency):
<dependency>
<groupId>com.c4-soft.springaddons</groupId>
<artifactId>spring-addons-webflux-jwt-resource-server</artifactId>
</dependency>
Instead of all your resource-server Java conf (unless you want access control from configuration and not with method-security, in which case, you'd have to define an AuthorizeExchangeSpecPostProcessor bean here). Of course, you'll have to add here a client filter-chain with a restrictive securityMatcher if you also serve UI client with oauth2Login:
#EnableReactiveMethodSecurity
#Configuration
public class SecurityConfig {
}
Instead of spring.security.oauth2.resourceserver properties:
com.c4-soft.springaddons.security.issuers[0].location=https://localhost:8443/realms/realm-1
com.c4-soft.springaddons.security.issuers[0].authorities.claims=realm_access.roles,resource_access.client-1.roles,resource_access.client-2.roles
com.c4-soft.springaddons.security.issuers[1].location=https://localhost:8443/realms/realm-2
com.c4-soft.springaddons.security.issuers[1].authorities.claims=realm_access.roles,resource_access.client-1.roles,resource_access.client-2.roles
# Comma separated list of routes accessible to anonymous
com.c4-soft.springaddons.security.permit-all=/api/v1/public/**,/actuator/health/readiness,/actuator/health/liveness
# Fine-grained CORS configuration can be set per path as follow:
com.c4-soft.springaddons.security.cors[0].path=/api/**
com.c4-soft.springaddons.security.cors[0].allowed-origins=https://localhost,https://localhost:8100,https://localhost:4200
# this are defaults and can be omitted
com.c4-soft.springaddons.security.cors[0].allowedOrigins=*
com.c4-soft.springaddons.security.cors[0].allowedMethods=*
com.c4-soft.springaddons.security.cors[0].allowedHeaders=*
com.c4-soft.springaddons.security.cors[0].exposedHeaders=*
If you don't want to use "my" wrappers, just copy from the source, it is open.
Redirect the user to the right authorization-server from client UI
As explained at point 3., this depends on the kind of client, used framework and if BFF pattern is applied or not
5. I tried some example but won't succeed, working example will be helpful with - Spring Webflux + spring-boot-starter-oauth2-client + spring-boot-starter-oauth2-resouce-server + multi-tenancy + keycloak as a provider
With all the elements above and linked resources, you should have enough to find your own path

Channerl url in mobile webapp

I am plannig to create a FirefoxOS app using Deezer API. So it would be a WebApp but it doesn't run on a server.
My main doubt is about the chanel url for cross domain requests.
Which one can I use or how can I manage that as soon as I have not a server URL neither a native package name?
Thank you.
Auth necessarily needs a domain or a bundle id to work properly. API cross domain requests can work without the channel URL though, you'll find code snippets to make jsonp queries here: https://github.com/deezer/code-snippets/blob/master/deezer-sdk-js/simple-deezer-api-request.js

What is the correct way to save state back to database in AngularJS?

The last example on the Angular homepage shows state being saved to a Mongo database using the mongolab API, however the API key is in the JavaScript file and easily viewable by the client. My question is what is the correct way to securely communicate with the server side rest API using Angular?
a pretty standard strategy is to run the API on the same domain as the AngularJS app (to prevent cross domain issues)
so for example the routes for the entire app (backend + frontend) can be:
/ - frontend AngularJS app,
/api - rest API
the next step is authentication and authorization, this can be done with sessions.
so when someone is accessing /api you know which user is it and if he is permitted to do so.
just to be clear - don't access Mongo directly from the frontend app, build an API for this.

web.xml, using form and basic authentication simultaneously

I have setup FORM-authentication within web.xml (java-webcontainer) successfully.
I did not find a way to sent the username/password within the get-request of the restful-uri from my client when using FORM-Authentication. So I have to use BASIC-Authentication only for the restful-uri.
So I have this question:
How can I set up both form-based authentication and basic authentication?
Basic authentication should only be enabled for the restful-uri.
I was also facing a similar problem and I realized that if you are using Wildfly then its possible to configure multiple mechanism using web.xml:-
<auth-method>BASIC?silent=true,FORM</auth-method>
Using this silent basic authentication will be tried first, which is basic authentication that only takes effect if an Authorization header is present. If no such header is present then form authentication will be used instead.
Maybe its too late for a reply but I just updated this in case someone finds this useful :P
There were no responses here for a while, so I did a quick servlet refresher myself. Servlet specs indeed allow only one <login-config> element per web application, so there is no way to have an entry point with BASIC authetication for the REST API and another with FORM-based authentication for the UI. The only option is to build them as two independently deployable applications. To avoid code duplication, it might be a good idea just to let the UI application talk to the REST API the same way the third-party clients are supposed to.

What is the best way to implement REST with Spring security?

I've implemented a web application with form and OpenID authentication, but in addition I want make my webapp RESTful. On the other hand requests to REST should be accesible only to authenticated users.
What is the best way to make my REST service secure?
Look at this example . I guess that solves your problem. A little google search yielded me to that page.