Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix management of tokens lifetime following RFC9068 #620

Merged
merged 21 commits into from
Sep 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import it.infn.mw.iam.api.common.client.RegisteredClientDTO;
import it.infn.mw.iam.api.common.client.TokenEndpointAuthenticationMethod;
import it.infn.mw.iam.config.IamProperties;
import it.infn.mw.iam.config.client_registration.ClientRegistrationProperties;

@Component
public class ClientConverter {
Expand All @@ -46,11 +47,14 @@ public class ClientConverter {

private final String clientRegistrationBaseUrl;

private final ClientRegistrationProperties clientProperties;

@Autowired
public ClientConverter(IamProperties properties) {
public ClientConverter(IamProperties properties, ClientRegistrationProperties clientProperties) {
this.iamProperties = properties;
clientRegistrationBaseUrl =
String.format("%s%s", iamProperties.getBaseUrl(), ClientRegistrationApiController.ENDPOINT);
this.clientProperties = clientProperties;
}

private <T> Set<T> cloneSet(Set<T> stringSet) {
Expand All @@ -67,18 +71,17 @@ public ClientDetailsEntity entityFromClientManagementRequest(RegisteredClientDTO
ClientDetailsEntity client = entityFromRegistrationRequest(dto);

if (dto.getAccessTokenValiditySeconds() != null) {
if (dto.getAccessTokenValiditySeconds() <= 0) {
client.setAccessTokenValiditySeconds(null);
} else {
client.setAccessTokenValiditySeconds(dto.getAccessTokenValiditySeconds());
}
client.setAccessTokenValiditySeconds(dto.getAccessTokenValiditySeconds());
} else {
client.setAccessTokenValiditySeconds(
clientProperties.getClientDefaults().getDefaultAccessTokenValiditySeconds());
}

if (dto.getRefreshTokenValiditySeconds() != null) {
if (dto.getRefreshTokenValiditySeconds() <= 0) {
client.setRefreshTokenValiditySeconds(null);
} else {
client.setRefreshTokenValiditySeconds(dto.getRefreshTokenValiditySeconds());
}
client.setRefreshTokenValiditySeconds(dto.getRefreshTokenValiditySeconds());
} else {
client.setRefreshTokenValiditySeconds(
clientProperties.getClientDefaults().getDefaultRefreshTokenValiditySeconds());
}

if (dto.getIdTokenValiditySeconds() != null) {
Expand Down Expand Up @@ -193,19 +196,16 @@ public ClientDetailsEntity entityFromRegistrationRequest(RegisteredClientDTO dto

client.setLogoUri(dto.getLogoUri());
client.setPolicyUri(dto.getPolicyUri());

client.setRedirectUris(cloneSet(dto.getRedirectUris()));

client.setScope(cloneSet(dto.getScope()));
client.setGrantTypes(new HashSet<>());

client.setGrantTypes(new HashSet<>());

if (!isNull(dto.getGrantTypes())) {
client.setGrantTypes(
dto.getGrantTypes()
.stream()
.map(AuthorizationGrantType::getGrantType)
.collect(toSet()));
dto.getGrantTypes().stream().map(AuthorizationGrantType::getGrantType).collect(toSet()));
}

if (dto.getScope().contains("offline_access")) {
Expand All @@ -231,6 +231,11 @@ public ClientDetailsEntity entityFromRegistrationRequest(RegisteredClientDTO dto
client.setCodeChallengeMethod(pkceAlgo);
}

client.setAccessTokenValiditySeconds(
clientProperties.getClientDefaults().getDefaultAccessTokenValiditySeconds());
client.setRefreshTokenValiditySeconds(
clientProperties.getClientDefaults().getDefaultRefreshTokenValiditySeconds());

return client;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,33 +58,18 @@ public ClientDetailsEntity setupClientDefaults(ClientDetailsEntity client) {
client.setClientId(UUID.randomUUID().toString());
}

client.setAccessTokenValiditySeconds(
properties.getClientDefaults().getDefaultAccessTokenValiditySeconds());

client
.setIdTokenValiditySeconds(properties.getClientDefaults().getDefaultIdTokenValiditySeconds());

client.setDeviceCodeValiditySeconds(
properties.getClientDefaults().getDefaultDeviceCodeValiditySeconds());

final int rtSecs = properties.getClientDefaults().getDefaultRefreshTokenValiditySeconds();

if (rtSecs < 0) {
client.setRefreshTokenValiditySeconds(null);
} else {
client.setRefreshTokenValiditySeconds(rtSecs);
}

client.setAllowIntrospection(true);

if (isNull(client.getContacts())) {
client.setContacts(new HashSet<>());
}

if (isNull(client.getClientId())) {
client.setClientId(UUID.randomUUID().toString());
}

if (AUTH_METHODS_REQUIRING_SECRET.contains(client.getTokenEndpointAuthMethod())) {
client.setClientSecret(generateClientSecret());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

import java.util.concurrent.TimeUnit;

import javax.validation.constraints.NotNull;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

Expand All @@ -28,10 +30,14 @@ public class ClientRegistrationProperties {

public static class ClientDefaultsProperties {

private int defaultAccessTokenValiditySeconds = (int) TimeUnit.HOURS.toSeconds(1);
@NotNull(message = "Provide a default access token lifetime")
private int defaultAccessTokenValiditySeconds;

@NotNull(message = "Provide a default refresh token lifetime")
private int defaultRefreshTokenValiditySeconds;

private int defaultIdTokenValiditySeconds = (int) TimeUnit.MINUTES.toSeconds(10);
private int defaultDeviceCodeValiditySeconds = (int) TimeUnit.MINUTES.toSeconds(10);
private int defaultRefreshTokenValiditySeconds = (int) TimeUnit.DAYS.toSeconds(30);

private int defaultRegistrationAccessTokenValiditySeconds = -1;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.springframework.web.servlet.HandlerInterceptor;

import it.infn.mw.iam.config.IamProperties;
import it.infn.mw.iam.config.client_registration.ClientRegistrationProperties;
import it.infn.mw.iam.config.saml.IamSamlProperties;
import it.infn.mw.iam.core.web.loginpage.LoginPageConfiguration;
import it.infn.mw.iam.rcauth.RCAuthProperties;
Expand All @@ -39,8 +40,8 @@ public class IamViewInfoInterceptor implements HandlerInterceptor {
public static final String GIT_COMMIT_ID_KEY = "gitCommitId";
public static final String SIMULATE_NETWORK_LATENCY_KEY = "simulateNetworkLatency";
public static final String RCAUTH_ENABLED_KEY = "iamRcauthEnabled";

public static final String RESOURCES_PATH_KEY = "resourcesPrefix";
public static final String CLIENT_DEFAULTS_PROPERTIES_KEY = "clientDefaultsProperties";

@Value("${iam.version}")
String iamVersion;
Expand All @@ -62,7 +63,10 @@ public class IamViewInfoInterceptor implements HandlerInterceptor {

@Autowired
IamProperties iamProperties;


@Autowired
ClientRegistrationProperties clientRegistrationProperties;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
Expand All @@ -78,6 +82,7 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons

request.setAttribute(RCAUTH_ENABLED_KEY, rcAuthProperties.isEnabled());

request.setAttribute(CLIENT_DEFAULTS_PROPERTIES_KEY, clientRegistrationProperties.getClientDefaults());

if (iamProperties.getVersionedStaticResources().isEnableVersioning()) {
request.setAttribute(RESOURCES_PATH_KEY, String.format("/resources/%s", gitCommitId));
Expand Down
4 changes: 4 additions & 0 deletions iam-login-service/src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,10 @@ task:
client-registration:
allow-for: ${IAM_CLIENT_REGISTRATION_ALLOW_FOR:ANYONE}
enable: ${IAM_CLIENT_REGISTRATION_ENABLE:true}
client-defaults:
default-access-token-validity-seconds: ${DEFAULT_ACCESS_TOKEN_VALIDITY_SECONDS:3600}
default-refresh-token-validity-seconds: ${DEFAULT_REFRESH_TOKEN_VALIDITY_SECONDS:108000}


management:
health:
Expand Down
8 changes: 8 additions & 0 deletions iam-login-service/src/main/webapp/WEB-INF/tags/iamHeader.tag
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,14 @@ function getOrganisationName() {
return '${iamOrganisationName}';
}

function getAccessTokenValiditySeconds() {
return ${clientDefaultsProperties.defaultAccessTokenValiditySeconds};
}

function getRefreshTokenValiditySeconds() {
return ${clientDefaultsProperties.defaultRefreshTokenValiditySeconds};
}

function getOidcEnabled() {
return ${loginPageConfiguration.oidcEnabled};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,7 @@
<div class="form-group">
<label for="at_timeout">Access token timeout (seconds)</label>
<input id="at_timeout" class="form-control" type="text"
ng-model="$ctrl.client.access_token_validity_seconds" placeholder="3600"
ng-disabled="$ctrl.client.access_token_validity_seconds <= 0">
</div>

<div class="checkbox">
<label>
<input type="checkbox" ng-model="$ctrl.client.access_token_validity_seconds" ng-true-value="0"
ng-false-value="3600">
Access tokens do not expire
</label>
ng-model="$ctrl.client.access_token_validity_seconds">
</div>

</div>
Expand Down Expand Up @@ -66,15 +57,11 @@
<label for="rt_timeout">Refresh token timeout (seconds)</label>

<input id="rt_timeout" class="form-control" type="text" ng-model="$ctrl.client.refresh_token_validity_seconds"
placeholder="259200" ng-required ng-min="30" ng-disabled="$ctrl.client.refresh_token_validity_seconds <= 0">

<div class="checkbox">
<label>
<input type="checkbox" ng-model="$ctrl.client.refresh_token_validity_seconds" ng-true-value="0"
ng-false-value="259200">
Refresh tokens do not expire
</label>
</div>
ng-required ng-min="30">
<p class="help-block">
This will setup after how many seconds the refresh token
expires. Type 0 to set an infinite lifetime.
</p>

</div>
<div class="form-group">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,25 +26,27 @@
self.toggleOfflineAccess = toggleOfflineAccess;
self.canIssueRefreshTokens = false;
self.hasDeviceCodeGrantType = false;

self.accessTokenValiditySeconds = getAccessTokenValiditySeconds();
self.refreshTokenValiditySeconds = getRefreshTokenValiditySeconds();

self.$onInit = function () {
console.debug('TokenSettingsController.self', self);
if (!self.client.access_token_validity_seconds) {
self.client.access_token_validity_seconds = 0;
if (self.client.access_token_validity_seconds == null) {
self.client.access_token_validity_seconds = self.accessTokenValiditySeconds;
}
if (!self.client.refresh_token_validity_seconds) {
self.client.refresh_token_validity_seconds = 0;

if (self.client.refresh_token_validity_seconds == null) {
self.client.refresh_token_validity_seconds = self.refreshTokenValiditySeconds;
}

$scope.$watch('$ctrl.client.access_token_validity_seconds', function handleChange(newVal, oldVal) {
if (!self.client.access_token_validity_seconds) {
if (newVal <= 0) {
self.client.access_token_validity_seconds = 0;
}
});

$scope.$watch('$ctrl.client.refresh_token_validity_seconds', function handleChange(newVal, oldVal) {
if (!self.client.refresh_token_validity_seconds) {
if (newVal <= 0) {
self.client.refresh_token_validity_seconds = 0;
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertTrue;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
Expand Down Expand Up @@ -144,4 +145,85 @@ public void ratRotationWorks() throws Exception {
client = mapper.readValue(responseJson, RegisteredClientDTO.class);
assertThat(client.getRegistrationAccessToken(), notNullValue());
}

@Test
public void setTokenLifetimesWorks() throws Exception {

String clientJson = ClientJsonStringBuilder.builder()
.scopes("openid")
.accessTokenValiditySeconds(null)
.refreshTokenValiditySeconds(null)
.build();

String responseJson = mvc
.perform(post(ClientManagementAPIController.ENDPOINT).contentType(APPLICATION_JSON)
.content(clientJson))
.andExpect(CREATED)
.andReturn()
.getResponse()
.getContentAsString();

RegisteredClientDTO client = mapper.readValue(responseJson, RegisteredClientDTO.class);
assertTrue(client.getAccessTokenValiditySeconds().equals(3600));
assertTrue(client.getRefreshTokenValiditySeconds().equals(108000));

clientJson = ClientJsonStringBuilder.builder()
.scopes("openid")
.accessTokenValiditySeconds(0)
.refreshTokenValiditySeconds(0)
.build();

responseJson = mvc
.perform(post(ClientManagementAPIController.ENDPOINT).contentType(APPLICATION_JSON)
.content(clientJson))
.andExpect(CREATED)
.andReturn()
.getResponse()
.getContentAsString();

client = mapper.readValue(responseJson, RegisteredClientDTO.class);
assertTrue(client.getAccessTokenValiditySeconds().equals(0));
assertTrue(client.getRefreshTokenValiditySeconds().equals(0));

clientJson = ClientJsonStringBuilder.builder()
.scopes("openid")
.accessTokenValiditySeconds(10)
.refreshTokenValiditySeconds(10)
.build();

responseJson = mvc
.perform(post(ClientManagementAPIController.ENDPOINT).contentType(APPLICATION_JSON)
.content(clientJson))
.andExpect(CREATED)
.andReturn()
.getResponse()
.getContentAsString();

client = mapper.readValue(responseJson, RegisteredClientDTO.class);
assertTrue(client.getAccessTokenValiditySeconds().equals(10));
assertTrue(client.getRefreshTokenValiditySeconds().equals(10));

}

@Test
public void negativeTokenLifetimesNotAllowed() throws Exception {

String clientJson =
ClientJsonStringBuilder.builder().scopes("openid").accessTokenValiditySeconds(-1).build();

mvc
.perform(post(ClientManagementAPIController.ENDPOINT).contentType(APPLICATION_JSON)
.content(clientJson))
.andExpect(BAD_REQUEST)
.andExpect(jsonPath("$.error", containsString("must be greater than or equal to 0")));

clientJson =
ClientJsonStringBuilder.builder().scopes("openid").refreshTokenValiditySeconds(-1).build();

mvc
.perform(post(ClientManagementAPIController.ENDPOINT).contentType(APPLICATION_JSON)
.content(clientJson))
.andExpect(BAD_REQUEST)
.andExpect(jsonPath("$.error", containsString("must be greater than or equal to 0")));
}
}
Loading
Loading