OAuth2 Open ID client authentication followed by LDAP user details & authorities - spring

Our app is currently set up with OAuth OpenID connect authentication with an external (third-party) server. The requirement is to use user details service that loads the user from LDAP (along with the authorities/roles) to complete the authentication. So authentication.getPrincipal() should be returning the custom UserDetails object we use that gets generated by querying LDAP using the username obtained from the Open ID authentication.
I have tried the following:
Followed Similar Issue but it seems like in the answer it's setting up the server-side and it doesn't work either
Tried adding custom UserDetailsService in WebSecurityConfig
#Configuration
public class OAuth2Config extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.oauth2Login().and().userDetailsService(myCustomUserDetailsService());
}
}
where myCustomUserDetailsService() handles the call to LDAP and fetches the user details info, including the authorities.
I'm not too familiar with the spring oauth2 framework, correct me if I'm wrong: I'm guessing I need to implement my own user info endpoint to make a call to LDAP, and not the user info endpoint provided to me by the OpenID service?

You could add a new filter in the security filter chain right after that one. The second filter could retrieve the principal/name from authentication and query for users.
Like a two steps authentication

Not as clean as I hoped, but I registered an application listener on InteractiveAuthenticationSuccessEvent and manually updated the authentication after login (similar post's answer https://stackoverflow.com/a/10747856/11204609)
If anyone has better suggestions?
UPDATE: The identity provider agreed to include LDAP info in their claims so I can directly obtain via the token without having to do a call-back (still an on-going discussion at the moment). That being said, having a auth success callback app listener is only way I could solve the problem.

Related

How to specify custom return Url after receiving the token or on failure?

I have the following setup:
I'm having an Angular frontend and Spring-Boot backend
Users are logging in to my backend via normal Form login
I'm integrating a third party API which needs oauth2 authentication, so Users need to grant permissions to my App so I can load data on their behalf from that third party
I configured oauth2Client() in my HttpSecurity config to enable oauth2
What currently happens is:
The frontend is calling an endpoint to get data from the third party, lets say /api/get-library which tries to access a protected resource at the third party.
This will lead to a 401 from the third party and trigger the oauth flow in Spring
The User is redirected to the third party to grant permissions to my App
After granting permissions the User is first redirected to the Url I specified as spring.security.oauth2.client.registration.foobar.redirect-uri
Spring Boot then retrieves the token and stores it for my Principal
After that Spring Boot redirects to the original url /api/get-library
But this is just some RestController so the User is presented with some JSON data in the Browser
So point 6 is my problem. I don't want that the User is in the end redirected to some API endpoint, I want him to be redirected to a page of my Angular application.
A similar problem arises if the user rejects the permission grant. Then the user is redirected to spring.security.oauth2.client.registration.foobar.redirect-uri with an query param ?error=true. Also in this case I want a redirect to my Angular application.
Initially I thought I could also configure oauth2Login() which has an failureHandler and successHandler, but those aren't called in my case, since I'm not doing a Login here.
So can somebody help me? How can I configure my own redirects for oauth2Client? In case of success, and on failure? What are relevant Beans here?
I found a solution:
The main Spring class to check is OAuth2AuthorizationCodeGrantFilter. This Filter is invoked when the user granted/rejected the permissions at the OAuth Provider.
Unfortunately there is no way to configure a custom redirect Url for this Filter, so I implemented a hacky solution:
I copied the implementation of OAuth2AuthorizationCodeGrantFilter to an own class and extended it with 2 parameters: success and error return Url. I then used those Urls in the processAuthorizationResponse Method to redirect to my Urls
I then put my ownAppOAuth2AuthorizationCodeGrantFilter before the Spring Filter in the HttpSecurityConfig, so it is used instead of the Spring version
In my Angular App I'm storing the exact location in the App before calling an Endpoint that potentially requires OAuth authentication. So when the User agent returns to the Angular App I can navigate back to the origin location.
It feels very hacky, so if somebody comes up with a better solution I'd be glad to hear it. :-)
Some Code snippets for Spring:
#Override
protected void configure(HttpSecurity http) throws Exception {
...
http.addFilterBefore(oAuth2AuthorizationCodeGrantFilter(), OAuth2AuthorizationCodeGrantFilter.class);
...
}
#Bean #Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public AppOAuth2AuthorizationCodeGrantFilter oAuth2AuthorizationCodeGrantFilter() throws Exception {
return new AppOAuth2AuthorizationCodeGrantFilter(
clientRegistrationRepository,
oAuth2AuthorizedClientRepository,
authenticationManagerBean(),
oauthSuccessRedirectUrl,
oauthErrorRedirectUrl);
}

Spring Authorization Server - Configure User Info Endpoint - Spring Roles in Resource Server

I have an existing resource server that is configured to use Spring user rules as security methods. I am trying to migrate onto the Spring Authorization server and trying to figure out how these roles can be accessed in the resource server.
When the user is authentication, I can see in debug logs that my roles are part of the authorized user details. But in the resource server, I am getting default roles from OidcService and scopes as granted authorities.
I know Spring Authorization server 0.21 has implemented the User Info endpoint, but there seems to be no sample or documentation available on how to configure that, and I am sure implementing it will solve my issue.
Another option that I am thinking about is to configure oauth2TokenCustomizer in the server and then add roles in JWT's claims. Then in the resource server think about overriding default OidcService and parse claims to add roles as granted authorities. But issue is with OidcUserService i don't see any code which can give me access to JWT claims.
public class CustomOAuth2Token implementsOAuth2TokenCustomizer<JwtEncodingContext> {
#Override
public void customize(JwtEncodingContext context) {
// Load user details and add roles to claims
}
}
Probably will have to provide a custom extension for OidcAuthorizationCodeAuthenticationProvider and then modify authenticated principal details.
I was facing the same issue.
Customizing the response of the "well-known" openid-configuration endpoint is somewhat tricky because the filter handling this endpoint has hardcoded mappings for which field go and do not go in the response.
I worked around this by:
copying this class into my codebase and giving it another name, in my case CustomOidcProviderConfigurationEndpointFilter
using my custom class as an objectPostProcessor for OidcProviderConfigurationEndpointFilter replacing it entirely instead of just customizing it.
This means your custom filter will supply the OidcProviderConfiguration object from now on.
You could then call the claim method on this object to add properties such as "userinfo_endpoint".
Note: I was unable to properly format the code snippet in the second link inside this post. If someone with administrative rights could edit this in, this would be nice.

Spring security - specific users

I am using ldap for authentication of requests.
I have configured by extending WebSecurityConfigurerAdapter and overriding configure(HttpSecurity) and configure(AuthenticationManagerBuilder) methods.
The credentials will be verified using ldap and on top of that, I need to maintain a static list that contains specific usernames to be allowed to access.
Can anyone help with the usernames validation part - do I need to write an extension of AuthenticationProvider to validate credentials and check for username? Just by configurations, I am able to take care of credentials verification.
do I need to write an extension of AuthenticationProvider to validate credentials and check for username
Yes. You need to have two different authentication provider. One to validate LDAP user's credential and other for static user list.
So, your configure method looks similar like below,
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(LDAPProvider);
auth.authenticationProvider(StaticUserProvider);
}
Here, an order is important because, user's credentials would validate according to above mentioned provider order.i.e first with LDAPProvider then with StaticUserProvider.

How to get auth handler info in Spring Security

In my application I am using multiple authentication handlers like application DB, LDAP and SAML. Now after successful authentication I am using CustomAuthenticationSuccessHandler.java which extends SimpleUrlAuthenticationSuccessHandler class which will be called after successful authentication. My question is how to get information about which handler has a successful authentication. I need this information because if it is an external user (LDAP, SAML) then I have to write a logic to replicate the user in application DB.
My configuation in configure global method:
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
auth
.ldapAuthentication()
.ldapAuthoritiesPopulator(ldapAuthoritiesPopulator)
.userDnPatterns("uid={0},ou=people")
.userDetailsContextMapper(ldapUserDetailsContextMapper)
.contextSource(getLDAPContextSource());`
You can set the info to authentication detail when do authenticated, or you can use different Authentication instances, e.g UsernamePasswordAuthenticationToken for DB and LDAP(maybe need to create a new Authentication to separate them), SAMLAuthenticationToken for SAML.

How do I setup login service for Spring-social and spring-security over a REST API?

I want to have a JS application in on client-side (no jsps) that will communicate with back-end only with REST calls. I want also to enable users to be able to login with FB, Twitter accounts. In addition, I also want to enable users to register their own accounts. For this purpose I want to use Spring-security and spring-social on backend and Javascript SDK in front to get access_token from the FB, which will be then passed to backend.
The question is: how do I create a REST controller that would authenticate using spring-social and spring-security facilities?
I read through the examples in:
https://github.com/spring-projects/spring-social-samples
but couldn't really find how I could make use of ProviderSignInController or SpringSocialConfigurer for this purpose. I guess I cannot use the SocialAuthenticationFilter in my case since the "/auth/{providerid}" url is not what I'm looking for. However, I guess the ProviderSingInController seems to be of use here neither. Please correct me if I'm wrong. Ideally I would like to benefit from all capabilities of Spring Security framework.
I will appreciate any suggestions.
Best regards
EDIT
I would like to follow a flow like here: http://porterhead.blogspot.com/2013/01/writing-rest-services-in-java-part-4.html but using the Spring Social and Spring Security combined.
The front-end application is written in AngularJS
2nd EDIT
It turns out that you can simply make use of all the Spring Social modules benefits out of the box. The only thing a client has to do is call a GET on the auth/facebook or whatever link to fire entire 0auth dance which will eventually return the authentication result. Then you can control the flow easily (register account or return some relevant information to the client to let know registration is needed). So the SpringSocialConfigurer works well in this case (apart from the fact that it doesn't support scope setting yet, however, this can be changed manually, check my pull request # github.com/spring-projects/spring-social/pull/141)
3rd EDIT - 14.10.2014
As requested, I will share how I managed to make it work.
Given I have configured my security filter in the following way:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
#Override
public void configure(final HttpSecurity http) throws Exception {
http.formLogin()
...
.and().apply(getSpringSocialConfigurer());
}
private SpringSocialConfigurer getSpringSocialConfigurer() {
final SpringSocialConfigurer config = new SpringSocialConfigurer();
config.alwaysUsePostLoginUrl(true);
config.postLoginUrl("http://somehost.com:1000/myApp");
return config;
}
Once my application is set up, the only thing I need to call is http://somehost.com:1000/myApp/auth/facebook
with GET request.
"In addition, I also want to enable users to register their own
accounts"
If you say that you want to allow users to login with their own credentials (without FB/twiter), you need to let them also to create account, and to support forgot password, etc...
If that is the case, maybe this SO thread might be helpful. The auth-flows package also supports REST API.
Create Account, Forgot Password and Change Password

Resources