I have been following #Dave Syers' excellent tutorial on Spring boot and oAuth2
I have been able to create a log in function, so that protected resources need a login to facebook before they can be accessed.
But now I am trying to create a "sign up" page. On stackoverflow, for example, there is an option to sign up with facebook, so your details are sent to Stackoverflow.com from facebook. How can this be performed with oAuth2? I was able to do this with spring-social, but I cannot wrap my head around how to do this with a direct oauth2 approach.
Please help?
The answer was simpler than I expected. All I needed to do was add my custom AuthenticationSuccessHandler to the filter:
All I had to do was add an AuthenticationSuccessHandler handle to the method that returns a Filter ssoFilter()
#Autowired
private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
private Filter ssoFilter() {
OAuth2ClientAuthenticationProcessingFilter facebookFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/facebook");
OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(facebook(), oauth2ClientContext);
facebookFilter.setRestTemplate(facebookTemplate);
facebookFilter.setTokenServices(new UserInfoTokenServices(facebookResource().getUserInfoUri(), facebook().getClientId()));
facebookFilter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler);
return facebookFilter;
}
And my CustomAuthenticationSuccessHandler was just a component that extended AuthenticationSuccessHandler
#Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
//implementation
}
}
So in my sign up page, I could simply use the same login action, but in the success handler I created the User and stored her in the DB
Make a integrated jwt-oauth2-signup-login is difficult. There are some easy way:
1, to use satellizer-spring-boot, or satellizer.
2,to use spring social.
3, add jwt to spring oauth2 as separate provider:
This is how to do with 3:
I have not use signup+oauth2 yet(Because I like spring social and it can do same function), but in theory it can be done in a very easy and can be done as follow:
First, when user login (Register on facebook will also lead to login page) form facebook, just import the user's information and write the information to user model. It is can be done with a controller and a view.
On front page, it is easy to make user choose to login, or register a new account: As Spring boot support multiple filter and multiple AuthenticationProvider,That means you can use two filters, one for oauth2,and another (jwt local server) filter for local server register.
1,download a standard spring boot jwtFilter.java file and put it in your config directory.
2,Make a controller for register new user.
3, make a /login to return jwt token.
3, make two filter, one for oauth2, one for local jwt.
4, make a Sign up link to /register. and a login tag link to /login.
ps: you can copy all the lines form a standard spring boot jwt project, here is one: https://github.com/mrmodise/senepe
Related
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);
}
We are using Spring Gateway (Spring Boot 2.4.6) which uses Spring Security 5 and the Weblux/ reactive model within that to provide OAuth2 security and Keycloak as the IDP.
Refreshing of the Access Token is an issue when our front-end application, which has already [successfully] authenticated against the gateway/ IDP, issues multiple API calls after the session's access token has expired.
It appears that out of (for example) five API calls, only the last one gets re-authenticated against the Keycloak provider and the other four get 'lost', thereby causing issues within the front-end.
If the user refreshes the UI's page then the proper authentication flow happens seamlessly and the token stored in the session is refreshed, without a redirect to the Keycloak login screen (as expected), therefore the problem is only with synchronous API calls.
The SecurityWebFilterChain is setup with:
/*
* Enable oauth2 authentication on all requests, but use our custom
* RegistrationRepository
*/
.and()
.oauth2Login()
.authenticationSuccessHandler(new AuthSuccessHandler(requestCache)) // handle success login
.authenticationFailureHandler((exchange, excep) -> {
LOGGER.debug("Authentication failure: {}", excep.getMessage());
return Mono.empty();
})
.clientRegistrationRepository(clientReg);
// Add our custom filter to the security chain
final KeycloakClientLoginFilter keyclockLogin = new KeycloakClientLoginFilter(
clientReg,
redirectStrategy,
requestCache,
authClientService);
clientReg.setKeycloakClientLoginFilter(keyclockLogin);
http.addFilterBefore(keyclockLogin, SecurityWebFiltersOrder.LOGIN_PAGE_GENERATING);
return http.build();
With the ServerAuthenticationSuccessHandler configured with this:
private class AuthSuccessHandler implements ServerAuthenticationSuccessHandler {
private final ServerRequestCache requestCache;
private final URI defaultLocation = URI.create("/login");
private AuthSuccessHandler(ServerRequestCache requestCache) {
this.requestCache = requestCache;
}
#Override
public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
final ServerWebExchange exchange = webFilterExchange.getExchange();
return requestCache.getRedirectUri(exchange)
.defaultIfEmpty(defaultLocation)
.flatMap(location -> {
LOGGER.debug("Authentication success. Redirecting request to {}", location.toASCIIString());
return redirectStrategy.sendRedirect(exchange, location);
});
}
}
Within the KeycloakClientLoginFilter there is a ServerWebExchangeMatcher that checks if the required details are present on the inbound exchange, and whether the AccessToken has (or is about to) expire. If it is, it runs through this code to redirect the request off to Keycloak for authentication and/ or refresh:
final ClientRegistration keycloakReg = clientReg.getRegistration(tenantId, appId);
if (!isError && loginRedirects.containsKey(keycloakReg.getRegistrationId())) {
final String contextPath = exchange.getRequest().getPath().contextPath().value();
final URI redirect = URI.create(contextPath + loginRedirects.get(keycloakReg.getRegistrationId()));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("About to redirect to keycloak; for method {}, tenant={}",
exchange.getRequest().getMethod(),
tenantId);
}
// Save the request so the URL can be retreived on successful login
return requestCache.saveRequest(exchange)
.then(redirectStrategy.sendRedirect(exchange, redirect));
}
So, all API calls hit the above code, require a refresh, have their original exchanges saved in the requestCache and are then directed to Keycloak. When Keycloak responds with the updated token, the exchange(s) run through the AuthSuccessHandler, which pulls the original request URL from the requestCache and redirects the call to that original URL.
This part works for web requests and the one in five API calls.
The other four API calls never make it to the AuthSuccessHandler - They simply get 'lost'.
There are some ugly hacks that could be done, like blocking all calls until the one first one is re-authenticated, but that just isn't right and would be hard to get right anyway.
So can the gateway, CookieServerRequestCache or AuthenticationWebFilter only handle one request at a time? Is there a 'simple' implementation of waiting on one call from the same session to re-authenticate?
Any help would be greatly appreciated as the application simply doesn't work (from a user's perspective) until this is resolved.
I know quite some tutorials do so, but in my opinion, authenticating against the gateway is a mistake (see this answer for details why). Why not using an OAuth2 client library on your client(s) instead?
I personnaly use angular-auth-oidc-client, and I am convinced that there must be equivalents for React, Vue, Flutter, Android or iOS.
Such libraries can handle access-tokens refreshing for you (provided that you requested the offline_access scope and that the authorization-server supports refresh-token for your client).
Authenticate users on the client(s) with the help of a certified lib, have your gateway just forward Authorization header and configure your micro-services as resource-servers.
I have a Spring Boot application that is "invitation only". Ie. users are sent a signup link and there is no "Sign up" functionality. This works fine and users log on with their username and password.
I would like to allow logon with FaceBook and Google using OAuth2 as a supplementary logon method. This would involve mapping the existing users to their social account in some way. The users and their passwords are stored in a MySQL database. I have found a number of articles on OAuth2 and Spring Boot, but none that address this exact use-case.
I can create the Google OAuth2 token/client secret etc, but how do I design the flow to allow only the existing users to logon with their social accounts?
The usernames have been chosen by the users themselves, and are therefore not necessarily the same as their email.
Do I need to create a custom authentication flow in this case?
And do I need to change the authentication mechanism from cookies to JWT tokens?
I found myself in a similar situation, where I needed to know if the OAuth request that I'm receiving is coming from an already authenticated user or not.
Although in my case I needed to know that because I want users to be able to "link" their existing account to social ones.
What I ended up doing was implementing an OAuth2UserService which would have a single method:
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException{
// this will be null if the OAuth2UserRequest is not from an authenticated user
// otherwise, it would contain the current user's principle which you can use to check if the OAuth request should be handled or not
Authentication currentAuth = SecurityContextHolder.getContext().getAuthentication();
// for example:
// if(currentAuth == null)
// throw new OAuth2AuthenticationException(OAuth2ErrorCodes.ACCESS_DENIED);
// Use the default service to load the user
DefaultOAuth2UserService defaultService = new DefaultOAuth2UserService();
OAuth2User defaultOAuthUser = defaultService.loadUser(userRequest);
// here you might have extra logic to map the defaultOAuthUser's info to the existing user
// and if you're implementing a custom OAuth2User you should also connect them here and return the custom OAuth2User
return defaultOAuthUser;
}
then just register the custom OAuth2UserService in your security configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
// your existing config
.oauth2Login()
.userInfoEndpoint()
.userService(oauthUserService())
;
}
#Bean
public OAuth2UserService oauthUserService(){
return new MyCustomOAuth2UserService();
}
I have a REST service, written using Spring MVC. The server is an OAuth2 resource server and I am using the JwtAuthenticationProvider to have the JWT parsed and turned into the Principal. This all works fine.
However, what I really want to do is to load user details from a database, using the username provided from a Claim in the JWT. Then that new Principal should replace or (ideally) wrap the Jwt so that it is available directly from the SecurityContext.
I am really struggling to see how to do this. The JwtAuthenticationProvider does not seem to work with a UserDetailsService. I also looked at doing this with a Converter - but it is not easy to extend JwtAuthenticationConverter because the convert method is final (why?).
So to be very clear, here is what I ideally want to happen:
Bearer token is presented to service.
Parse Jwt and extract claims
Use one of these claims as a key to my user database, where I can look up attributes, entitlements etc
Turn these into a new Principal object which is available in the SecurityContext's Authentication object.
The configure method in my WebSecurityConfigurerAdapter has this:
http.authorizeRequests().antMatchers("/api/*").authenticated().and().oauth2ResourceServer().jwt();
I cannot be the only person who wants to use a user database along with OAuth2, so I must be missing something fundamental? I am using Spring Security 5.2.0.
The JwtAuthenticationProvider does not support an UserDetailsService because in theory you are not supposed to have UserDetails in an application that does not manage credentials. I'm not saying that you cannot have any type of user, but the UserDetailsService will not be used or autowired by Spring Security.
You could register a bean of type JwtAuthenticationConverter, do whatever you need in the convert method and return your custom authentication token, like so:
#Component
public class JwtAuthenticationConverterAdapter implements Converter<Jwt, AbstractAuthenticationToken> {
private JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
#Override
public AbstractAuthenticationToken convert(Jwt jwt) {
var token = this.jwtAuthenticationConverter.convert(jwt);
// build your custom token with the properties from the token above
return customToken;
}
}
I agree with your concerns - and I have found it useful to override Spring's default processing. There is a claims extensibility pattern I use with some providers, where JWT handling is only one part.
I have a Spring Boot code sample that you can run - it uses a custom filter and Connect2Id classes - OAuth integration is described here. Happy to answer any follow up questions if it helps
I'm having some trouble regarding the authorization endpoint of my Spring based OAuth2 provider. I need more information from the client than there is currently possible. This is what I want to achieve:
I need the custom parameter in the authentication process later on. Is there any simple way to extend the default parameters with my custom one or do I need to implement a certain class myself?
Did some research on how the authentication endpoint works in the current Spring code. I found that the Authorization Endpoint uses a method named authorize that takes all the parameter that are being set and converts then into an AuthorizationRequest. While looking further into the AuthorizationRequest class I found that it holds a map with extensions that is being filled throughout the authorization process. But it does not seem to get filled with my custom parameter (as shown above). This is in fact by only looking at the code, so I might be wrong.
Would it be a good idea to extend the AuthorizationEndpoint with my custom implementation or is there a better and cleaner way to do this?
Update #1 (07-10-2015)
The place where I'd like to use the custom parameter is in my own implementation of the AuthenticationProvider. I need to information to be available inside the authenticate method of this class.
Update #2 (07-10-2015)
It seems that the AuthorizationProvider gets called before the AuthorizationEndpoint. This means that the custom parameter is obtained after the class where I need it (so that's too late).
Maybe I can get the referral Url by either extending part of the Spring security classes or by obtaining it in the HTML through JavaScript. Is this a good idea or should I use another approach?
So I managed to fix the problem myself by searching some more on Google.
What you need to do is speak to the HttpSessionRequestCache to get the referral URL. This is how I solved it in my own implementation of the AuthenticationProvider
#Component
public class CustomProvider implements AuthenticationProvider {
#Autowired
private HttpServletRequest httpRequest;
#Autowired
private HttpServletResponse httpResponse;
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(httpRequest, httpResponse);
logger.info("Referral URL: " + savedRequest.getRedirectUrl());
logger.info("Parameters: " + savedRequest.getParameterMap().keySet().toString());
}
}
This will print out the URL of the request that was called before heading to the login page of spring security. The second log method prints out the parameters that where found in this URL. This question and answer helped me in creating a solution for my problem.