Add support for One-Time Token Login

Closes gh-15114
This commit is contained in:
Marcus Hert Da Coregio
2024-07-18 09:37:03 -03:00
parent 5c56bddbdd
commit 00e4a8fb54
28 changed files with 2116 additions and 2 deletions

View File

@@ -0,0 +1,60 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.authentication.ott;
import java.time.Instant;
import org.springframework.util.Assert;
/**
* A default implementation of {@link OneTimeToken}
*
* @author Marcus da Coregio
* @since 6.4
*/
public class DefaultOneTimeToken implements OneTimeToken {
private final String token;
private final String username;
private final Instant expireAt;
public DefaultOneTimeToken(String token, String username, Instant expireAt) {
Assert.hasText(token, "token cannot be empty");
Assert.hasText(username, "username cannot be empty");
Assert.notNull(expireAt, "expireAt cannot be null");
this.token = token;
this.username = username;
this.expireAt = expireAt;
}
@Override
public String getTokenValue() {
return this.token;
}
@Override
public String getUsername() {
return this.username;
}
public Instant getExpiresAt() {
return this.expireAt;
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.authentication.ott;
import org.springframework.util.Assert;
/**
* Class to store information related to an One-Time Token authentication request
*
* @author Marcus da Coregio
* @since 6.4
*/
public class GenerateOneTimeTokenRequest {
private final String username;
public GenerateOneTimeTokenRequest(String username) {
Assert.hasText(username, "username cannot be empty");
this.username = username;
}
public String getUsername() {
return this.username;
}
}

View File

@@ -0,0 +1,83 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.authentication.ott;
import java.time.Clock;
import java.time.Instant;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.lang.NonNull;
import org.springframework.util.Assert;
/**
* Provides an in-memory implementation of the {@link OneTimeTokenService} interface that
* uses a {@link ConcurrentHashMap} to store the generated {@link OneTimeToken}. A random
* {@link UUID} is used as the token value. A clean-up of the expired tokens is made if
* there is more or equal than 100 tokens stored in the map.
*
* @author Marcus da Coregio
* @since 6.4
*/
public final class InMemoryOneTimeTokenService implements OneTimeTokenService {
private final Map<String, OneTimeToken> oneTimeTokenByToken = new ConcurrentHashMap<>();
private Clock clock = Clock.systemUTC();
@Override
@NonNull
public OneTimeToken generate(GenerateOneTimeTokenRequest request) {
String token = UUID.randomUUID().toString();
Instant fiveMinutesFromNow = this.clock.instant().plusSeconds(300);
OneTimeToken ott = new DefaultOneTimeToken(token, request.getUsername(), fiveMinutesFromNow);
this.oneTimeTokenByToken.put(token, ott);
cleanExpiredTokensIfNeeded();
return ott;
}
@Override
public OneTimeToken consume(OneTimeTokenAuthenticationToken authenticationToken) {
OneTimeToken ott = this.oneTimeTokenByToken.remove(authenticationToken.getTokenValue());
if (ott == null || isExpired(ott)) {
return null;
}
return ott;
}
private void cleanExpiredTokensIfNeeded() {
if (this.oneTimeTokenByToken.size() < 100) {
return;
}
for (Map.Entry<String, OneTimeToken> entry : this.oneTimeTokenByToken.entrySet()) {
if (isExpired(entry.getValue())) {
this.oneTimeTokenByToken.remove(entry.getKey());
}
}
}
private boolean isExpired(OneTimeToken ott) {
return this.clock.instant().isAfter(ott.getExpiresAt());
}
void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.authentication.ott;
import org.springframework.security.core.AuthenticationException;
/**
* An {@link AuthenticationException} that indicates an invalid one-time token.
*
* @author Marcus da Coregio
* @since 6.4
*/
public class InvalidOneTimeTokenException extends AuthenticationException {
public InvalidOneTimeTokenException(String msg) {
super(msg);
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.authentication.ott;
import java.time.Instant;
/**
* Represents a one-time use token with an associated username and expiration time.
*
* @author Marcus da Coregio
* @since 6.4
*/
public interface OneTimeToken {
/**
* @return the one-time token value, never {@code null}
*/
String getTokenValue();
/**
* @return the username associated with this token, never {@code null}
*/
String getUsername();
/**
* @return the expiration time of the token
*/
Instant getExpiresAt();
}

View File

@@ -0,0 +1,67 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.authentication.ott;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.Assert;
/**
* An {@link AuthenticationProvider} responsible for authenticating users based on
* one-time tokens. It uses an {@link OneTimeTokenService} to consume tokens and an
* {@link UserDetailsService} to fetch user authorities.
*
* @author Marcus da Coregio
* @since 6.4
*/
public final class OneTimeTokenAuthenticationProvider implements AuthenticationProvider {
private final OneTimeTokenService oneTimeTokenService;
private final UserDetailsService userDetailsService;
public OneTimeTokenAuthenticationProvider(OneTimeTokenService oneTimeTokenService,
UserDetailsService userDetailsService) {
Assert.notNull(oneTimeTokenService, "oneTimeTokenService cannot be null");
Assert.notNull(userDetailsService, "userDetailsService cannot be null");
this.userDetailsService = userDetailsService;
this.oneTimeTokenService = oneTimeTokenService;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OneTimeTokenAuthenticationToken otpAuthenticationToken = (OneTimeTokenAuthenticationToken) authentication;
OneTimeToken consumed = this.oneTimeTokenService.consume(otpAuthenticationToken);
if (consumed == null) {
throw new InvalidOneTimeTokenException("Invalid token");
}
UserDetails user = this.userDetailsService.loadUserByUsername(consumed.getUsername());
OneTimeTokenAuthenticationToken authenticated = OneTimeTokenAuthenticationToken.authenticated(user,
user.getAuthorities());
authenticated.setDetails(otpAuthenticationToken.getDetails());
return authenticated;
}
@Override
public boolean supports(Class<?> authentication) {
return OneTimeTokenAuthenticationToken.class.isAssignableFrom(authentication);
}
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.authentication.ott;
import java.util.Collection;
import java.util.Collections;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
/**
* Represents a One-Time Token authentication that can be authenticated or not.
*
* @author Marcus da Coregio
* @since 6.4
*/
public class OneTimeTokenAuthenticationToken extends AbstractAuthenticationToken {
private final Object principal;
private String tokenValue;
public OneTimeTokenAuthenticationToken(Object principal, String tokenValue) {
super(Collections.emptyList());
this.tokenValue = tokenValue;
this.principal = principal;
}
public OneTimeTokenAuthenticationToken(String tokenValue) {
this(null, tokenValue);
}
public OneTimeTokenAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
setAuthenticated(true);
}
/**
* Creates an unauthenticated token
* @param tokenValue the one-time token value
* @return an unauthenticated {@link OneTimeTokenAuthenticationToken}
*/
public static OneTimeTokenAuthenticationToken unauthenticated(String tokenValue) {
return new OneTimeTokenAuthenticationToken(null, tokenValue);
}
/**
* Creates an unauthenticated token
* @param principal the principal
* @param tokenValue the one-time token value
* @return an unauthenticated {@link OneTimeTokenAuthenticationToken}
*/
public static OneTimeTokenAuthenticationToken unauthenticated(Object principal, String tokenValue) {
return new OneTimeTokenAuthenticationToken(principal, tokenValue);
}
/**
* Creates an unauthenticated token
* @param principal the principal
* @param authorities the principal authorities
* @return an authenticated {@link OneTimeTokenAuthenticationToken}
*/
public static OneTimeTokenAuthenticationToken authenticated(Object principal,
Collection<? extends GrantedAuthority> authorities) {
return new OneTimeTokenAuthenticationToken(principal, authorities);
}
/**
* Returns the one-time token value
* @return
*/
public String getTokenValue() {
return this.tokenValue;
}
@Override
public Object getCredentials() {
return this.tokenValue;
}
@Override
public Object getPrincipal() {
return this.principal;
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.authentication.ott;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
/**
* Interface for generating and consuming one-time tokens.
*
* @author Marcus da Coregio
* @since 6.4
*/
public interface OneTimeTokenService {
/**
* Generates a one-time token based on the provided generate request.
* @param request the generate request containing the necessary information to
* generate the token
* @return the generated {@link OneTimeToken}, never {@code null}.
*/
@NonNull
OneTimeToken generate(GenerateOneTimeTokenRequest request);
/**
* Consumes a one-time token based on the provided authentication token.
* @param authenticationToken the authentication token containing the one-time token
* value to be consumed
* @return the consumed {@link OneTimeToken} or {@code null} if the token is invalid
*/
@Nullable
OneTimeToken consume(OneTimeTokenAuthenticationToken authenticationToken);
}