SpringBoot + Keycloak adapter setup failed - spring-boot

I try to secure a SpringBoot backend with Keycloak adapter.
SprinBoot 2.1.9
Keycloak 6.0.1
I'm just scratching my head over lot of bug and missing documentation. Currently, i try to make the keycloak adapter to correctly respond with Cors Header for a 401 WWW-authenticate error.
I've investigated and found that securityContext is null in the class org.keycloak.adapters.AuthenticatedActionsHandler, resulting in header not set in response.
protected boolean corsRequest() {
if (!deployment.isCors()) return false;
KeycloakSecurityContext securityContext = facade.getSecurityContext(); // This return null
String origin = facade.getRequest().getHeader(CorsHeaders.ORIGIN);
String exposeHeaders = deployment.getCorsExposedHeaders();
if (deployment.getPolicyEnforcer() != null) {
if (exposeHeaders != null) {
exposeHeaders += ",";
} else {
exposeHeaders = "";
}
exposeHeaders += "WWW-Authenticate";
}
String requestOrigin = UriUtils.getOrigin(facade.getRequest().getURI());
log.debugv("Origin: {0} uri: {1}", origin, facade.getRequest().getURI());
if (securityContext != null && origin != null && !origin.equals(requestOrigin)) {
Following the code, i found that :
public class OIDCCatalinaHttpFacade extends CatalinaHttpFacade implements OIDCHttpFacade{
public OIDCCatalinaHttpFacade(org.apache.catalina.connector.Request request, HttpServletResponse response) {
super(response, request);
}
#Override
public KeycloakSecurityContext getSecurityContext() {
return (KeycloakSecurityContext)request.getAttribute(KeycloakSecurityContext.class.getName());
}
}
getSecurityContext return null.
So what i'm missing to make it work?
This is my springboot application.propertie
server.port = 8081
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create-drop
spring.h2.console.enabled=true
spring.main.allow-bean-definition-overriding=true
logging.level.org.springframework.security=DEBUG
logging.level.org.keycloak=TRACE
keycloak.realm = spring
keycloak.bearer-only = true
keycloak.auth-server-url=http://localhost:8080/auth
keycloak.ssl-required = none
keycloak.resource = spring-boot-elide
keycloak.credentials.secret = *********************
keycloak.confidential-port = 0
keycloak.enabled = true
keycloak.cors = true

You can use keycloak adaptor with keycloak spring starter and spring security. And use a WebSecurityConfigurerAdapter Config to handle CORS in the overriding configure method.
Refer this doc : https://www.keycloak.org/docs/6.0/securing_apps/index.html#_spring_boot_adapter

Related

How to pass cookie through open feign

I have two spring boot projects and want to pass the cookie from one project to another
1st spring boot project:
class SomeClass() {
#Autowired
private MyClient myClient;
someMethod1() {
myClient.getDetails();
}
}
#FeignClient(value = "abc", url = "http://someexample.com/emp/user")
public interface MyClient {
#GetMapping(value = "/details")
void getDetails();
}
2nd spring boot project:
#GetMapping("/details")
void someDetails(HttpServletRequest request, HttpServletResponse response) {
Cookie cookie = WebUtils.getCookie(request, "user");
if (cookie != null) {
}
}
Problem is that the cookie is available in the 1st project. When the feign calls the other project method, the someDetails method does not have the cookie with the name "user" has such the cookie value is null and the if condition fails. How can I pass it?

Spring Boot add additional attribute to WebClient request in ServerOAuth2AuthorizedClientExchangeFilterFunction

I am trying to implement the client_credentials grant to get a token in my spring boot resource server.
I am using Auth0 as an Authorization server. They seem to require an extra parameter in the request body to be added called audience.
I have tried to do the request through postman and it works. I am now trying to reproduce it within Spring. Here is the working postman request
curl -X POST \
https://XXX.auth0.com/oauth/token \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'grant_type=client_credentials&audience=https%3A%2F%2Fxxxxx.auth0.com%2Fapi%2Fv2%2F&client_id=SOME_CLIENT_ID&client_secret=SOME_CLIENT_SECRET'
The problem I am facing is that i have no way to add the missing audience parameter to the token request.
I have a configuration defined in my application.yml
client:
provider:
auth0:
issuer-uri: https://XXXX.auth0.com//
registration:
auth0-client:
provider: auth0
client-id: Client
client-secret: Secret
authorization_grant_type: client_credentials
auth0:
client-id: Client
client-secret: Secret
I have the web client filter configured like this.
#Bean
WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations,
ServerOAuth2AuthorizedClientRepository authorizedClients) {
ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2 = new ServerOAuth2AuthorizedClientExchangeFilterFunction(
clientRegistrations, authorizedClients);
oauth2.setDefaultClientRegistrationId("auth0");
return WebClient.builder()
.filter(oauth2)
.build();
}
I am injecting the instance and trying to do a request to get the user by email
return this.webClient.get()
.uri(this.usersUrl + "/api/v2/users-by-email?email={email}", email)
.attributes(auth0ClientCredentials())
.retrieve()
.bodyToMono(User.class);
The way i understand it, the filter intercepts this userByEmail request and before it executes it it tries to execute the /oauth/token request to get JWT Bearer token which it can append to the first one and execute it.
Is there a way to add a parameter to the filter? It has been extremely difficult to step through it and figure out where exactly the parameters are being appended since its reactive and am quite new at this. Even some pointers to where to look would be helpful.
I was having the same problem where access token response and request for it wasn't following oAuth2 standards. Here's my code (it's in kotlin but should be understandable also for java devs) for spring boot version 2.3.6.RELEASE.
Gradle dependencies:
implementation(enforcedPlatform("org.springframework.boot:spring-boot-dependencies:${springBootVersion}"))
implementation("org.springframework.boot:spring-boot-starter-webflux")
implementation("org.springframework.boot:spring-boot-starter-oauth2-client")
After adding them you have to firstly create your custom token request/response client which will implement ReactiveOAuth2AccessTokenResponseClient interface:
class CustomTokenResponseClient : ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> {
private val webClient = WebClient.builder().build()
override fun getTokenResponse(
authorizationGrantRequest: OAuth2ClientCredentialsGrantRequest
): Mono<OAuth2AccessTokenResponse> =
webClient.post()
.uri(authorizationGrantRequest.clientRegistration.providerDetails.tokenUri)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.bodyValue(CustomTokenRequest(
clientId = authorizationGrantRequest.clientRegistration.clientId,
clientSecret = authorizationGrantRequest.clientRegistration.clientSecret
))
.exchange()
.flatMap { it.bodyToMono<NotStandardTokenResponse>() }
.map { it.toOAuth2AccessTokenResponse() }
private fun NotStandardTokenResponse.toOAuth2AccessTokenResponse() = OAuth2AccessTokenResponse
.withToken(this.accessToken)
.refreshToken(this.refreshToken)
.expiresIn(convertExpirationDateToDuration(this.data.expires).toSeconds())
.tokenType(OAuth2AccessToken.TokenType.BEARER)
.build()
}
As you can see above, in this class you can adjust token request/response handling to your specific needs.
Note: authorizationGrantRequest param inside getTokenResponse method. Spring is passing here data from you application properties, so follow the standards when defining them, e.g. they may look like this:
spring:
security:
oauth2:
client:
registration:
name-for-oauth-integration:
authorization-grant-type: client_credentials
client-id: id
client-secret: secret
provider:
name-for-oauth-integration:
token-uri: https://oauth.com/token
The last step is to use your CustomTokenResponseClient inside oAuth2 configuration, it may look like this:
#Configuration
class CustomOAuth2Configuration {
#Bean
fun customOAuth2WebWebClient(clientRegistrations: ReactiveClientRegistrationRepository): WebClient {
val clientRegistryRepo = InMemoryReactiveClientRegistrationRepository(
clientRegistrations.findByRegistrationId("name-for-oauth-integration").block()
)
val clientService = InMemoryReactiveOAuth2AuthorizedClientService(clientRegistryRepo)
val authorizedClientManager =
AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(clientRegistryRepo, clientService)
val authorizedClientProvider = ClientCredentialsReactiveOAuth2AuthorizedClientProvider()
authorizedClientProvider.setAccessTokenResponseClient(CustomTokenResponseClient())
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
val oauthFilter = ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager)
oauthFilter.setDefaultClientRegistrationId("name-for-oauth-integration")
return WebClient.builder()
.filter(oauthFilter)
.build()
}
}
Right now, this is possible, but not elegant.
Note that you can provide a custom ReactiveOAuth2AccessTokenResponseClient to ServerOAuth2AuthorizedClientExchangeFilterFunction.
You can create your own implementation of this - and thereby add any other parameters you need - by copying the contents of WebClientReactiveClientCredentialsTokenResponseClient.
That said, it would be better if there were a setter to make that more convenient. You can follow the corresponding issue in Spring Security's backlog.
Here is what i found out after further investigation. The code described in my question was never going to call the client_credentials and fit my use-case. I think (not 100% sure on this) it will be very useful in the future if i am trying to propagate the user submitted token around multiple services in a micro-service architecture. A chain of actions like this comes to mind:
User calls Service A -> Service A calls Service B -> Service B responds -> Service A responds back to user request.
And using the same token to begin with through the whole process.
My solution to my use-case:
What i did was create a new Filter class largely based on the original and implement a step before executing the request where i check if i have a JWT token stored that can be used for the Auth0 Management API. If i don't i build up the client_credentials grant request and get one, then attach this token as a bearer to the initial request and execute that one. I also added a small token in-memory caching mechanism so that if the token is valid any other requests at a later date will just use it. Here is my code.
Filter
public class Auth0ClientCredentialsGrantFilterFunction implements ExchangeFilterFunction {
private ReactiveClientRegistrationRepository clientRegistrationRepository;
/**
* Required by auth0 when requesting a client credentials token
*/
private String audience;
private String clientRegistrationId;
private Auth0InMemoryAccessTokenStore auth0InMemoryAccessTokenStore;
public Auth0ClientCredentialsGrantFilterFunction(ReactiveClientRegistrationRepository clientRegistrationRepository,
String clientRegistrationId,
String audience) {
this.clientRegistrationRepository = clientRegistrationRepository;
this.audience = audience;
this.clientRegistrationId = clientRegistrationId;
this.auth0InMemoryAccessTokenStore = new Auth0InMemoryAccessTokenStore();
}
public void setAuth0InMemoryAccessTokenStore(Auth0InMemoryAccessTokenStore auth0InMemoryAccessTokenStore) {
this.auth0InMemoryAccessTokenStore = auth0InMemoryAccessTokenStore;
}
#Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
return auth0ClientCredentialsToken(next)
.map(token -> bearer(request, token.getTokenValue()))
.flatMap(next::exchange)
.switchIfEmpty(next.exchange(request));
}
private Mono<OAuth2AccessToken> auth0ClientCredentialsToken(ExchangeFunction next) {
return Mono.defer(this::loadClientRegistration)
.map(clientRegistration -> new ClientCredentialsRequest(clientRegistration, audience))
.flatMap(request -> this.auth0InMemoryAccessTokenStore.retrieveToken()
.switchIfEmpty(refreshAuth0Token(request, next)));
}
private Mono<OAuth2AccessToken> refreshAuth0Token(ClientCredentialsRequest clientCredentialsRequest, ExchangeFunction next) {
ClientRegistration clientRegistration = clientCredentialsRequest.getClientRegistration();
String tokenUri = clientRegistration
.getProviderDetails().getTokenUri();
ClientRequest clientCredentialsTokenRequest = ClientRequest.create(HttpMethod.POST, URI.create(tokenUri))
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.body(clientCredentialsTokenBody(clientCredentialsRequest))
.build();
return next.exchange(clientCredentialsTokenRequest)
.flatMap(response -> response.body(oauth2AccessTokenResponse()))
.map(OAuth2AccessTokenResponse::getAccessToken)
.doOnNext(token -> this.auth0InMemoryAccessTokenStore.storeToken(token));
}
private static BodyInserters.FormInserter<String> clientCredentialsTokenBody(ClientCredentialsRequest clientCredentialsRequest) {
ClientRegistration clientRegistration = clientCredentialsRequest.getClientRegistration();
return BodyInserters
.fromFormData("grant_type", AuthorizationGrantType.CLIENT_CREDENTIALS.getValue())
.with("client_id", clientRegistration.getClientId())
.with("client_secret", clientRegistration.getClientSecret())
.with("audience", clientCredentialsRequest.getAudience());
}
private Mono<ClientRegistration> loadClientRegistration() {
return Mono.just(clientRegistrationId)
.flatMap(r -> clientRegistrationRepository.findByRegistrationId(r));
}
private ClientRequest bearer(ClientRequest request, String token) {
return ClientRequest.from(request)
.headers(headers -> headers.setBearerAuth(token))
.build();
}
static class ClientCredentialsRequest {
private final ClientRegistration clientRegistration;
private final String audience;
public ClientCredentialsRequest(ClientRegistration clientRegistration, String audience) {
this.clientRegistration = clientRegistration;
this.audience = audience;
}
public ClientRegistration getClientRegistration() {
return clientRegistration;
}
public String getAudience() {
return audience;
}
}
}
Token Store
public class Auth0InMemoryAccessTokenStore implements ReactiveInMemoryAccessTokenStore {
private AtomicReference<OAuth2AccessToken> token = new AtomicReference<>();
private Clock clock = Clock.systemUTC();
private Duration accessTokenExpiresSkew = Duration.ofMinutes(1);
public Auth0InMemoryAccessTokenStore() {
}
#Override
public Mono<OAuth2AccessToken> retrieveToken() {
return Mono.justOrEmpty(token.get())
.filter(Objects::nonNull)
.filter(token -> token.getExpiresAt() != null)
.filter(token -> {
Instant now = this.clock.instant();
Instant expiresAt = token.getExpiresAt();
if (now.isBefore(expiresAt.minus(this.accessTokenExpiresSkew))) {
return true;
}
return false;
});
}
#Override
public Mono<Void> storeToken(OAuth2AccessToken token) {
this.token.set(token);
return Mono.empty();
}
}
Token Store Interface
public interface ReactiveInMemoryAccessTokenStore {
Mono<OAuth2AccessToken> retrieveToken();
Mono<Void> storeToken(OAuth2AccessToken token);
}
And finally defining the beans and using it.
#Bean
public Auth0ClientCredentialsGrantFilterFunction auth0FilterFunction(ReactiveClientRegistrationRepository clientRegistrations,
#Value("${auth0.client-registration-id}") String clientRegistrationId,
#Value("${auth0.audience}") String audience) {
return new Auth0ClientCredentialsGrantFilterFunction(clientRegistrations, clientRegistrationId, audience);
}
#Bean(name = "auth0-webclient")
WebClient webClient(Auth0ClientCredentialsGrantFilterFunction filter) {
return WebClient.builder()
.filter(filter)
.build();
}
There is a slight problem with the token store at this time as the client_credentials token request will be executed multiple on parallel requests that come at the same time, but i can live with that for the foreseeable future.
Your application.yml is missing one variable:
client-authentication-method: post
it should be like this:
spring:
security:
oauth2:
client:
provider:
auth0-client:
token-uri: https://XXXX.auth0.com//
registration:
auth0-client:
client-id: Client
client-secret: Secret
authorization_grant_type: client_credentials
client-authentication-method: post
Without it I was getting "invalid_client" response all the time.
Tested in spring-boot 2.7.2

How can we remove x-forwarded-* header in Netflix Zuul filter?

I m building a simple PoC to strip-off the X-FORWARDED-* header while invoking microservice through Zuul gateway. I tried with route filter, but I couldnt find those headers there.
Where are the default headers are added and how can we remove it?
Found out. Add the below in application.properties
zuul.add-proxy-headers=false
Works for me
RequestContext.getCurrentContext().getZuulRequestHeaders().remove("name of the header to be remove");
or
return new HttpServletRequestWrapper(request) {
private Set<String> headerNameSet;
#Override
public Enumeration<String> getHeaderNames() {
if (headerNameSet == null) {
// first time this method is called, cache the wrapped request's header names:
headerNameSet = new HashSet<>();
Enumeration<String> wrappedHeaderNames = super.getHeaderNames();
while (wrappedHeaderNames.hasMoreElements()) {
String headerName = wrappedHeaderNames.nextElement();
if (!headerName.contains("x-forwarded")) {
headerNameSet.add(headerName);
}
}
}
return Collections.enumeration(headerNameSet);
}
#Override
public Enumeration<String> getHeaders(String name) {
if (name.contains("x-forwarded")) {
return Collections.<String>emptyEnumeration();
}
return super.getHeaders(name);
}
#Override
public String getHeader(String name) {
if (name.contains("x-forwarded")) {
return null;
}
return super.getHeader(name);
}
};
Simple one through the configuration file
zuul:
#mentioned header are ignored while build the request in zuul
ignored-header: header_name1, header_name2
#Will ignore all the x-forward-* headers
add-proxy-headers: false

Migrating to keycloak for an app that uses spring security

I'm looking for steps to keycloak for an Spring MVC app that uses spring security currently.
I wanted to use keycloak in Sitewhere.
I guess this is so simple if I would have read keycloak's document fully:). Any how here are the steps that I followed while migrating to keycloak in Sitewhere .
Follow the steps as given in keycloak doc for spring-security
Add the dependency to sitewhere-core & sitewhere-web pom.xml as stated in adapter installation
Also add the jboss-logging dependency in sitewhere-web's pom.xml since, keycloak spring adapter has a hardcode dependency for jboss-logging.
Modify applicationcontext.xml so that it can uses keycloak for both web & api, following the sample for api
<sec:http pattern="/api/**" entry-point-ref="keycloakAuthenticationEntryPoint">
<sec:custom-filter ref="keycloakPreAuthActionsFilter" before="LOGOUT_FILTER" />
<sec:custom-filter ref="keycloakAuthenticationProcessingFilter" before="FORM_LOGIN_FILTER" />
Modify LoginManager.java as follows
public static IUser getCurrentlyLoggedInUser() throws SiteWhereException {
Authentication KeyCloakAuth = SecurityContextHolder.getContext().getAuthentication();
if (KeyCloakAuth == null) {
throw new SiteWhereSystemException(ErrorCode.NotLoggedIn, ErrorLevel.ERROR,
HttpServletResponse.SC_FORBIDDEN);
}
KeycloakAccount keyAccount = ((KeycloakAuthenticationToken) KeyCloakAuth).getAccount();
String username = keyAccount.getKeycloakSecurityContext().getIdToken().getPreferredUsername();
String password = "";
IUser user = SiteWhere.getServer().getUserManagement().authenticate(username, password);
List<IGrantedAuthority> auths =
SiteWhere.getServer().getUserManagement().getGrantedAuthorities(user.getUsername());
SitewhereUserDetails details = new SitewhereUserDetails(user, auths);
Authentication auth = new SitewhereAuthentication(details, password);
if (!(auth instanceof SitewhereAuthentication)) {
throw new SiteWhereException("Authentication was not of expected type: "
+ SitewhereAuthentication.class.getName() + " found " + auth.getClass().getName()
+ " instead.");
}
return (IUser) ((SitewhereAuthentication) auth).getPrincipal();
}
Since, we have migrated our authentication to keycloak and for the fact that we will not get credentials of user in siterwhere it's better to void the code related to password validation in authentication method of IUserManagement. Following is the sample from MongoUserManagement.java
public IUser authenticate(String username, String password) throws SiteWhereException {
if (password == null) {
throw new SiteWhereSystemException(ErrorCode.InvalidPassword, ErrorLevel.ERROR,
HttpServletResponse.SC_BAD_REQUEST);
}
DBObject userObj = assertUser(username);
String inPassword = SiteWherePersistence.encodePassoword(password);
User match = MongoUser.fromDBObject(userObj);
//nullify authentication since we are using keycloak
/*if (!match.getHashedPassword().equals(inPassword)) {
throw new SiteWhereSystemException(ErrorCode.InvalidPassword, ErrorLevel.ERROR,
HttpServletResponse.SC_UNAUTHORIZED);
}*/
// Update last login date.
match.setLastLogin(new Date());
DBObject updated = MongoUser.toDBObject(match);
DBCollection users = getMongoClient().getUsersCollection();
BasicDBObject query = new BasicDBObject(MongoUser.PROP_USERNAME, username);
MongoPersistence.update(users, query, updated);
return match;}
Make sure you have respective roles for the users in keycloak that are more specific to sitewhere.
Change your home page so that it redirects to keycloak for authentication purpose. Following is the sample for redirection:
Tracer.start(TracerCategory.AdminUserInterface, "login", LOGGER);
try {
Map<String, Object> data = new HashMap<String, Object>();
data.put("version", VersionHelper.getVersion());
String keycloakConfig = environment.getProperty("AUTHSERVER_REDIRECTION_URL");
if (SiteWhere.getServer().getLifecycleStatus() == LifecycleStatus.Started) {
return new ModelAndView("redirect:"+keycloakConfig);
} else {
ServerStartupException failure = SiteWhere.getServer().getServerStartupError();
data.put("subsystem", failure.getDescription());
data.put("component", failure.getComponent().getLifecycleError().getMessage());
return new ModelAndView("noserver", data);
}
} finally {
Tracer.stop(LOGGER);
}

Spring Security: How to get the initial target url

I am using the spring security to restricted urls. I am trying to provide signup and login page, on the same page.
On login spring security transfers to the restricted page. However i am trying to pass the target url to the signup process, so that after signup we can redirect to the restricted page.
How to get the actual URL that user was redirected from.
Any Ideas?
This is how i got the URL from the Spring Security.
SavedRequest savedRequest = (SavedRequest)session.getAttribute(
AbstractProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY);
String requestUrl = savedRequest.getFullRequestUrl();
They moved things around a bit in spring security 3.0, so the above code snippet doesn't work anymore. This does the trick, though:
protected String getRedirectUrl(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if(session != null) {
SavedRequest savedRequest = (SavedRequest) session.getAttribute(WebAttributes.SAVED_REQUEST);
if(savedRequest != null) {
return savedRequest.getRedirectUrl();
}
}
/* return a sane default in case data isn't there */
return request.getContextPath() + "/";
}
with spring security 4.1.4:
#Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
if (savedRequest != null) {
response.sendRedirect(savedRequest.getRedirectUrl());
}
else{
response.sendRedirect("some/path");
}
}
DefaultSavedRequest savedRequest = (DefaultSavedRequest)session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
String requestURL = savedRequest.getRequestURL(); // URL <br>
String requestURI = savedRequest.getRequestURI(); // URI

Resources