Is it possible to leverage Spring Security while manually handling multiple oauth2 logins? - spring-boot

The current application I'm working on makes use of oauth2 quite extensively.
For each screen, the user may be required to authenticate via an external service (while still maintaining authentication for the other screens they have already visited).
So for example:
ScreenA -> Authenticate via ServiceX
ScreenB -> Authenticate via ServiceY
ScreenC -> Authenticate via ServiceZ
It is possible for users to be authenticated to multiple login providers at the same time in a given session.
As such, I've decided to handle the oauth2 workflow manually instead of relying on Spring Boot's OAuth2 library. It does seem like this library provides multiple login providers but it looks far too complicated for such a simple scenario and I'm not sure if it's even possible to have users authenticated to multiple providers at once.
Anyway, that was the background information. My plan for the implementation is to just store the access token in the session object for each of the screens. So this means that I have a separate bean in the session object for each of the screens, and I'm going to make it thread safe to account for the web session pitfalls.
Is there an easier way of doing what I'm trying to achieve? I can't find any best practices on this approach.
If my manual approach is the best way, then how do I take advantage of the other functionalities provided by Spring Security? Namely, I would like to use #PreAuthorize (perhaps define a role for each of login providers) and maybe even get WebSecurityConfigurerAdapter to work with these roles.
Ultimately, I'm having difficulty coming up with the right architecture for this situation.

With what you have provided, it's possible to implement OAuth2 authentication.
Use one Authentication Server ( this will be a wrapper service that can authenticate against service X, Y and Z)
Any time you go to any screen, you pass down which service to authenticate against (in request header or in some way), so that Authentication Server can authenticate and return you proper token.
All of the spring security features will still be useable in this scenario.

Related

Authentication system in frontend - backend services

I'm very new in Spring and never really used java for making web. And I'm making a web with a separated frontend and backend services and I'm trying to make an authentication system using Spring Boot Security. How can I do it? Do I put the security on both the service or just one of them? What's the best way to implement it?
The question is subjective and can have too many interpretations based on context. My understanding is that putting security on both front-end and backend is the best way to implement. After a successful backend authentication you should issue a unique cookie to the browser as it allows users to continue using a site without having to log in to every single page. For each subsequent call, the website recognizes the user from cookie data.
You can use this link for a better understanding of dual authentication mechanism.

Managing user permissions in keycloak and spring rest api

TL;DR
Objective: managing api permissions:
OIDC authorization direct grant flow
User federation and authentication source : LDAP
Permissions store : legacy database
Client management and authentication: Keycloak
Question: What are the best practices for managing user permissions on Keycloak and rest api?
Context
We are implementing a rest API with spring to be used by a mobile application and an SPA. Our users accounts, permissions, rules… and all data are stored in a custom database used by different monolithic applications. To secure our api we have decided to use Keycloak.
The keycloak server is configured with an existing LDAP for user federation and ‘Direct grand flow’ for the mobile client application. For the first use case (authentication) everything is working fine.
Now we have to manage users permissions as follow :
The client applications should know user permissions to display/hide functionalities
The api should be able to validate user permissions to use different endpoints
Users permissions are based on some rules in the database and change frequently
In my understanding keycloak can handle authorization and fine grained permissions using hardcoded or user based policies but can’t be plugged to a different authorization source natively. As a consequence, I thought of building a custom role mapper using Keycloak SPI, retrieve user permissions from a custom api that I will develop, then map them to the access token.
As a result, my access token should look like:
"resource_access": {
“My-client”: {
“permissions”: [
“Show-products”,
“Buy-something”,
“Display-prices”
]
}
},
"username": “myUser”
Then the mobile application should be able to know user permissions based on the token, and my stateless server side (API) should be able to access user permissions on every call to check them using spring annotation :
#PreAuthorize("hasRole('Show-products')")
Problem
After first experimenting my solution seem to work fine, but I still have some security concerns about this choice since it’s out of the keycloak standard and includes rest calls to a different backend inside keycloak mappers.
So I was wondering :
Is it secure to put user permissions on the access token claims?
How to secure keycloak access to an external system (rest calls) to
retrieve permissions?
Should I rely on token claims to verify user permissions on each
request in my resource server?
Is there any other clean solution / best practices to handle user
permissions from external source in keycloak ?
Complimentary Informations
I’m using :
Springboot 1.5.13.RELEASE
Keycloak-adapter-bom 3.4.3.Final
Standalone keycloak server 3.4.3.Final
regarding your questions:
- Is it secure to put user permissions on the access token claims?
Yes, capabilities can (and should be) on the access-token, and with that you can take some decisions in your business layer (based on the roles/access claims). Remember nevertheless that a token is only base 64 encoded, and could be copied by other person and looked into, so it shouldn't contain secret or particularly confidential information, usually you put there enough info regarding the user, and some of its current permissions/capabilities/claims.
How to secure keycloak access to an external system (rest calls) to retrieve permissions?
It depends if it needs to be accessed from outside your network. If not, you can leave it unprotected (and unavailbale from outside/or only available for some specific IPs). If it is going to be available from outside/or you want to protect it with keycloack anyway, you can have either a "confidential" or a "bearer only" type of client. I'd suggest you to look into CORS and token sharing, so that you can reuse your already created "access-token" for your other endpoints without the need to authenticate again.
Should I rely on token claims to verify user permissions on each request in my resource server?
Not exactly sure what you mean. In keycloak the resource server isn't doing extra resource authorization like in a typical oAuth2 dance (unless your policy enforcer is activated but I believe you didn't go with this approach, but rather a mapper SPI #auth server for getting your roles right?)
In oAuth2 the "resource server" has 2 responsibilities: 1-providing the resource and 2-doing an extra authorization step. In the keycloak world those 2 steps are done by different actors. Step 1 is done by your application, and step2 is only done when policy enforcing is activated by keycloak also (that means Keycloak is the auth server and also part of the "resource server" from the oAuth2 perspective)
Now back to your question, if by resource server you just meant your application providing the content, then yes you can use the claims there, remember that the claims (and the whole access-token) was generated and digitaly-signed by the auth server, so you can use those claims in your app with no problem (and wouldn't know how to do it otherwise either).
Is there any other clean solution / best practices to handle user permissions from external source in keycloak ?
Hard to say, as you probably noticed; documentation in the web for your specific usecase is very limited; so not a lot of work of best practices exist there, you only real alternative would have been using policies with a custom Policy SPI, and that would have brought in other challenges. I'd say your solution is fine.
Best regards.

Spring authentication through REST Service

I have a Webapp that consists of a REST API, and then another app that represents a frontend of this API. Both of this apps are developed using Spring.
Currently my REST api is not secured and data can be accessed directly by calling the REST endpoint without additional security info.
My frontend does have a login form (I'm using Spring Security for that), but does not have access to a database (the only access is through the REST endpoint). So the login process is done through an extension of the AuthenticationProvider that calls the REST api with the user and password and then responds with the authentication result. No authentication/authorization is kept on the REST side since to my knowledge this protocol should be stateless.
The problem is I need to incorporate ACL into my app, so that a user can only see those resources he's authorized to see (i.e. those he created). But given that my authentication process takes place on the frontend layer (which is where I keep a session attribute with the user info), I have two main problems:
How can I secure my REST channel?
How can I know which user is making the request on every communication, without explicitly passing the userdetails in each API request? is this even possible?
Doing it stateless and making two separate web application usually is overkill.
What I usually end up doing is.
Make my RestAPI stateful, because usually scaling is not an issue and simple form authentication will suffice.
Combine a Rest API/HTML Client in one Webapplication. If you want to keep it modular, you could create a Rest API module and integrate it as a JAR file in the lib folder of your web app.
Here is also some thread which goes through different alternatives for a rest API.
How to do authentication with a REST API right? (Browser + Native clients)

How to achieve long lived login session with Oauth2 and javascript client(Spring Oauth2 + Angularjs)

I've a spring backend with Spring OAuth2 and Angular client.
What is the proper way to achieve long lived logins which is still arguably secure.
I guess I can use password flow and refresh tokens, but this doesn't seem any safer than using long lived access tokens with implicit flow for browser clients. I think I can use:
Redirects - which will interfere with whatever user was doing
Popups - which will get blocked without user interaction
on the client level. But is there any better approach?
P.S: Cloudfoundry's new UI seems to have achieved exactly what I want.
The auth code flow is always superior (more secure and less chance of leaking user cerdentials). If you are writing a browser-hosted client contacting the OAuth2 service directly then unfortunately you won't be able to get hold of the access token from the auth code flow. For that reason I think I would prefer to use access tokens between machine (non-browser) clients, and standard cookie-based authentication between the browser and the front end server. You can still use OAuth2 on the front end server to do the authentication (I'm pretty sure that's what the CloudFoundry server is doing) if you expose a /me or /user_info type endpoint.
Or if you really need to get the access token in your client (I guess there are libraries for dealing with it), you can use password or implicit grant. Implicit is strongly preferred on security grounds (since the user only types his password into the auth server authentication UI), but in both cases you need to take care to segregate your client data so the (unauthenticated) clients don't get access to anything they shouldn't.
Solution to me was to use hidden iframes with implicit grant.

How to design authentication and authorization system for REST backend / Ajax front End Application

I am starting a new project where we are planing to build a restful back end and an AJAX font end. I am approaching the problem by focusing on Identifying all the resources that I have and what the various HTTP verbs will do them, their URI and the JSON representations of those resources.
I am looking for the best design for securing the backend. Here is the list of designs I have considered. I am looking for alternative designs not listed below, and pros, cons recommendations. The system will be implemented with Spring 3.0 and possibly Spring Security 3.0, SSL will be used for many parts of the system but not for all of them, so some requests may come on SSL and some might not.
Option 1: Use the HTTP session
Show a standard login screen, create a server side session and let tomcat send back a jsessionid cookie and have the ajax client include the JSESSIONID cookie on every XHR request. This options just feels like it's the wrong approach for the following reasons.
The connection becomes statefull which is against the rules of REST
I want to be able to split the bakcend into multiple seperate WAR files which means i could have multiple HTTP sessions on the backend, if that is the case then this approach does not work. While I don't need the ability to split the backend into multiple apps today, I would prefer a design that allows for that possibility.
Option 2: Find an open source Java based security library that does this
Other than Spring security I have not found any other Java libraries, any recommendations are highly appreciated.
Option 3: Try to use an existing protocol like OAuth
In my very brief look at OAuth it seems that it is designed for authentication across sites where each site has it's own user database. In this system i want a global user database shared across all the backend ajax services.
Option 4: Use SAML and Shiboleth
This options seems over kill and hugely complex to setup and maintain.
Option 5: Send the username and password with every request
This requires that user sends their username and password with every request, which means that the front end AJAX app must store the username and password as a JavaScript object and if the user navigates away from the page then back the username/password combo will be gone and the user might be forced to log in again. I don't want the front end to try and put the username and password into cookie as that would comprise security.
Option 6: Implement my own authentication / Authorization protocol
Create a REST service that users can present their username/password combination to and then get back and security token, which they must send back to the service with every request. The security token would be digitally signed by the service and would have an expiry time. The token would be only good for most operations high security operations would require a new login screen as port of confirming the operation.
Problem with this approach is I have to invent yet another security protocol which seems like a total waste of time.
I am sure I am not the only person up against this problem, I hope the stack overflow community can point to some options and tools that I have not found yet.
Take a look at Apache Shiro. It is an authentication system that has a session management feature that can be used to share sessions across applications. This may be the easiest thing to do.
Or you could use Spring Security (or Shiro) with a Remember Me cookie that is shared across the webapps (as long as they are in the same HTTP domain). The remember me cookie would be analogous to your token in option 6. You can set the expiration on the cookie that so it is short lived like a session cookie or long lived like a regular remember me.
You might also want to take a look at Jasig CAS - Single Sign-On for the Web. It has a REST API and a protocol (Proxy Tickets) that allows services to proxy user AuthN to backend services like you described in option 6. http://www.jasig.org/cas
Briefly...the application that serves up the AJAX client is protected with Spring Security (supports CAS out of the box) and gets a Proxy Granting Ticket that you embed in the AJAX client. The AJAX client uses the PGT to get Proxy Tickets for your REST services...protected with Spring Security too. The REST services get an authenticated userId without every touching primary credentials.
Alternative, you could keep the PGT on the server and use AJAX calls to retrieve Proxy Tickets that are then used by the AJAX client to call you REST services.
As I understood you are going to secure a rest application, to preface you must know that a security provider consisd of three concepts (3A):
-Authentication
-Authorization
-Auditing
to implement these three together you must provide bunch of tools such as :
-SSO provider
-Session Store
-Open Id pattern
-user credentials integration
....
I have used ACL(Spring ACL) to provide authorization services and oauth2 for authentication.
there is one channel to connect these two together and its scopes(oauth2 scopes) but the problem is scopes are not flexible(pure strings) enough to implement authorization modules such as role_voter, cache_strategy, black_list or,Role_base strategy, exceptional permissions, white_list... (but you can use #EnableGlobalMethodSecurity)
In my case I used authorization server as a resource for oauth2 authentication server(take a look at http://projects.spring.io/spring-security-oauth/docs/oauth2.html), then I considered two spots to check authorization, the first I issued ACL to front-end and forced programmer to design her page dynamically up to ACL concept, the second is in back-end on service layer(BLL) using Aspect when one rest is going to be called. I sent the service key as an actee to check if current user has enough access control to do that. and for auditing you must monitor all requests I mean you must use an listener in your gateway or broker...

Resources