repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/Http403ForbiddenEntryPoint.java | /*
* Copyright 2002-2016 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.web.authentication;
import java.io.IOException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
/**
* <p>
* In the pre-authenticated authentication case (unlike CAS, for example) the user will
* already have been identified through some external mechanism and a secure context
* established by the time the security-enforcement filter is invoked.
* <p>
* Therefore this class isn't actually responsible for the commencement of authentication,
* as it is in the case of other providers. It will be called if the user is rejected by
* the AbstractPreAuthenticatedProcessingFilter, resulting in a null authentication.
* <p>
* The <code>commence</code> method will always return an
* <code>HttpServletResponse.SC_FORBIDDEN</code> (403 error).
*
* @author Luke Taylor
* @author Ruud Senden
* @since 2.0
* @see org.springframework.security.web.access.ExceptionTranslationFilter
*/
public class Http403ForbiddenEntryPoint implements AuthenticationEntryPoint {
private static final Log logger = LogFactory.getLog(Http403ForbiddenEntryPoint.class);
/**
* Always returns a 403 error code to the client.
*/
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2)
throws IOException {
logger.debug("Pre-authenticated entry point called. Rejecting access");
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
}
}
| 2,349 | 36.903226 | 109 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/ExceptionMappingAuthenticationFailureHandler.java | /*
* Copyright 2002-2018 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.web.authentication;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;
/**
* Uses the internal map of exceptions types to URLs to determine the destination on
* authentication failure. The keys are the full exception class names.
* <p>
* If a match isn't found, falls back to the behaviour of the parent class,
* {@link SimpleUrlAuthenticationFailureHandler}.
* <p>
* The map of exception names to URLs should be injected by setting the
* <tt>exceptionMappings</tt> property.
*
* @author Luke Taylor
* @since 3.0
*/
public class ExceptionMappingAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
private final Map<String, String> failureUrlMap = new HashMap<>();
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
String url = this.failureUrlMap.get(exception.getClass().getName());
if (url != null) {
getRedirectStrategy().sendRedirect(request, response, url);
}
else {
super.onAuthenticationFailure(request, response, exception);
}
}
/**
* Sets the map of exception types (by name) to URLs.
* @param failureUrlMap the map keyed by the fully-qualified name of the exception
* class, with the corresponding failure URL as the value.
* @throws IllegalArgumentException if the entries are not Strings or the URL is not
* valid.
*/
public void setExceptionMappings(Map<?, ?> failureUrlMap) {
this.failureUrlMap.clear();
for (Map.Entry<?, ?> entry : failureUrlMap.entrySet()) {
Object exception = entry.getKey();
Object url = entry.getValue();
Assert.isInstanceOf(String.class, exception, "Exception key must be a String (the exception classname).");
Assert.isInstanceOf(String.class, url, "URL must be a String");
Assert.isTrue(UrlUtils.isValidRedirectUrl((String) url), () -> "Not a valid redirect URL: " + url);
this.failureUrlMap.put((String) exception, (String) url);
}
}
}
| 2,994 | 36.4375 | 109 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/RequestMatcherDelegatingAuthenticationManagerResolver.java | /*
* Copyright 2002-2022 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.web.authentication;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationManagerResolver;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.web.access.intercept.RequestMatcherDelegatingAuthorizationManager;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcherEntry;
import org.springframework.util.Assert;
/**
* An {@link AuthenticationManagerResolver} that returns a {@link AuthenticationManager}
* instances based upon the type of {@link HttpServletRequest} passed into
* {@link #resolve(HttpServletRequest)}.
*
* @author Josh Cummings
* @since 5.7
*/
public final class RequestMatcherDelegatingAuthenticationManagerResolver
implements AuthenticationManagerResolver<HttpServletRequest> {
private final List<RequestMatcherEntry<AuthenticationManager>> authenticationManagers;
private AuthenticationManager defaultAuthenticationManager = (authentication) -> {
throw new AuthenticationServiceException("Cannot authenticate " + authentication);
};
/**
* Construct an {@link RequestMatcherDelegatingAuthenticationManagerResolver} based on
* the provided parameters
* @param authenticationManagers a {@link Map} of
* {@link RequestMatcher}/{@link AuthenticationManager} pairs
*/
RequestMatcherDelegatingAuthenticationManagerResolver(
RequestMatcherEntry<AuthenticationManager>... authenticationManagers) {
Assert.notEmpty(authenticationManagers, "authenticationManagers cannot be empty");
this.authenticationManagers = Arrays.asList(authenticationManagers);
}
/**
* Construct an {@link RequestMatcherDelegatingAuthenticationManagerResolver} based on
* the provided parameters
* @param authenticationManagers a {@link Map} of
* {@link RequestMatcher}/{@link AuthenticationManager} pairs
*/
RequestMatcherDelegatingAuthenticationManagerResolver(
List<RequestMatcherEntry<AuthenticationManager>> authenticationManagers) {
Assert.notEmpty(authenticationManagers, "authenticationManagers cannot be empty");
this.authenticationManagers = authenticationManagers;
}
/**
* {@inheritDoc}
*/
@Override
public AuthenticationManager resolve(HttpServletRequest context) {
for (RequestMatcherEntry<AuthenticationManager> entry : this.authenticationManagers) {
if (entry.getRequestMatcher().matches(context)) {
return entry.getEntry();
}
}
return this.defaultAuthenticationManager;
}
/**
* Set the default {@link AuthenticationManager} to use when a request does not match
* @param defaultAuthenticationManager the default {@link AuthenticationManager} to
* use
*/
public void setDefaultAuthenticationManager(AuthenticationManager defaultAuthenticationManager) {
Assert.notNull(defaultAuthenticationManager, "defaultAuthenticationManager cannot be null");
this.defaultAuthenticationManager = defaultAuthenticationManager;
}
/**
* Creates a builder for {@link RequestMatcherDelegatingAuthorizationManager}.
* @return the new {@link RequestMatcherDelegatingAuthorizationManager.Builder}
* instance
*/
public static Builder builder() {
return new Builder();
}
/**
* A builder for {@link RequestMatcherDelegatingAuthenticationManagerResolver}.
*/
public static final class Builder {
private final List<RequestMatcherEntry<AuthenticationManager>> entries = new ArrayList<>();
private Builder() {
}
/**
* Maps a {@link RequestMatcher} to an {@link AuthorizationManager}.
* @param matcher the {@link RequestMatcher} to use
* @param manager the {@link AuthenticationManager} to use
* @return the {@link Builder} for further
* customizationServerWebExchangeDelegatingReactiveAuthenticationManagerResolvers
*/
public Builder add(RequestMatcher matcher, AuthenticationManager manager) {
Assert.notNull(matcher, "matcher cannot be null");
Assert.notNull(manager, "manager cannot be null");
this.entries.add(new RequestMatcherEntry<>(matcher, manager));
return this;
}
/**
* Creates a {@link RequestMatcherDelegatingAuthenticationManagerResolver}
* instance.
* @return the {@link RequestMatcherDelegatingAuthenticationManagerResolver}
* instance
*/
public RequestMatcherDelegatingAuthenticationManagerResolver build() {
return new RequestMatcherDelegatingAuthenticationManagerResolver(this.entries);
}
}
}
| 5,389 | 35.666667 | 102 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/WebAuthenticationDetails.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.web.authentication;
import java.io.Serializable;
import java.util.Objects;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.core.SpringSecurityCoreVersion;
/**
* A holder of selected HTTP details related to a web authentication request.
*
* @author Ben Alex
* @author Luke Taylor
*/
public class WebAuthenticationDetails implements Serializable {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final String remoteAddress;
private final String sessionId;
/**
* Records the remote address and will also set the session Id if a session already
* exists (it won't create one).
* @param request that the authentication request was received from
*/
public WebAuthenticationDetails(HttpServletRequest request) {
this(request.getRemoteAddr(), extractSessionId(request));
}
/**
* Constructor to add Jackson2 serialize/deserialize support
* @param remoteAddress remote address of current request
* @param sessionId session id
* @since 5.7
*/
public WebAuthenticationDetails(String remoteAddress, String sessionId) {
this.remoteAddress = remoteAddress;
this.sessionId = sessionId;
}
private static String extractSessionId(HttpServletRequest request) {
HttpSession session = request.getSession(false);
return (session != null) ? session.getId() : null;
}
/**
* Indicates the TCP/IP address the authentication request was received from.
* @return the address
*/
public String getRemoteAddress() {
return this.remoteAddress;
}
/**
* Indicates the <code>HttpSession</code> id the authentication request was received
* from.
* @return the session ID
*/
public String getSessionId() {
return this.sessionId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WebAuthenticationDetails that = (WebAuthenticationDetails) o;
return Objects.equals(this.remoteAddress, that.remoteAddress) && Objects.equals(this.sessionId, that.sessionId);
}
@Override
public int hashCode() {
return Objects.hash(this.remoteAddress, this.sessionId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()).append(" [");
sb.append("RemoteIpAddress=").append(this.getRemoteAddress()).append(", ");
sb.append("SessionId=").append(this.getSessionId()).append("]");
return sb.toString();
}
}
| 3,213 | 28.218182 | 114 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/AuthenticationEntryPointFailureHandler.java | /*
* Copyright 2002-2022 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.web.authentication;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.util.Assert;
/**
* Adapts a {@link AuthenticationEntryPoint} into a {@link AuthenticationFailureHandler}
*
* @author Sergey Bespalov
* @since 5.2.0
*/
public class AuthenticationEntryPointFailureHandler implements AuthenticationFailureHandler {
private boolean rethrowAuthenticationServiceException = true;
private final AuthenticationEntryPoint authenticationEntryPoint;
public AuthenticationEntryPointFailureHandler(AuthenticationEntryPoint authenticationEntryPoint) {
Assert.notNull(authenticationEntryPoint, "authenticationEntryPoint cannot be null");
this.authenticationEntryPoint = authenticationEntryPoint;
}
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
if (!this.rethrowAuthenticationServiceException) {
this.authenticationEntryPoint.commence(request, response, exception);
return;
}
if (!AuthenticationServiceException.class.isAssignableFrom(exception.getClass())) {
this.authenticationEntryPoint.commence(request, response, exception);
return;
}
throw exception;
}
/**
* Set whether to rethrow {@link AuthenticationServiceException}s (defaults to true)
* @param rethrowAuthenticationServiceException whether to rethrow
* {@link AuthenticationServiceException}s
* @since 5.8
*/
public void setRethrowAuthenticationServiceException(boolean rethrowAuthenticationServiceException) {
this.rethrowAuthenticationServiceException = rethrowAuthenticationServiceException;
}
}
| 2,664 | 36.013889 | 102 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.web.authentication;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;
/**
* Processes an authentication form submission. Called
* {@code AuthenticationProcessingFilter} prior to Spring Security 3.0.
* <p>
* Login forms must present two parameters to this filter: a username and password. The
* default parameter names to use are contained in the static fields
* {@link #SPRING_SECURITY_FORM_USERNAME_KEY} and
* {@link #SPRING_SECURITY_FORM_PASSWORD_KEY}. The parameter names can also be changed by
* setting the {@code usernameParameter} and {@code passwordParameter} properties.
* <p>
* This filter by default responds to the URL {@code /login}.
*
* @author Ben Alex
* @author Colin Sampaleanu
* @author Luke Taylor
* @since 3.0
*/
public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/login",
"POST");
private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
private boolean postOnly = true;
public UsernamePasswordAuthenticationFilter() {
super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
}
public UsernamePasswordAuthenticationFilter(AuthenticationManager authenticationManager) {
super(DEFAULT_ANT_PATH_REQUEST_MATCHER, authenticationManager);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
if (this.postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
String username = obtainUsername(request);
username = (username != null) ? username.trim() : "";
String password = obtainPassword(request);
password = (password != null) ? password : "";
UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,
password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
/**
* Enables subclasses to override the composition of the password, such as by
* including additional values and a separator.
* <p>
* This might be used for example if a postcode/zipcode was required in addition to
* the password. A delimiter such as a pipe (|) should be used to separate the
* password and extended value(s). The <code>AuthenticationDao</code> will need to
* generate the expected password in a corresponding manner.
* </p>
* @param request so that request attributes can be retrieved
* @return the password that will be presented in the <code>Authentication</code>
* request token to the <code>AuthenticationManager</code>
*/
@Nullable
protected String obtainPassword(HttpServletRequest request) {
return request.getParameter(this.passwordParameter);
}
/**
* Enables subclasses to override the composition of the username, such as by
* including additional values and a separator.
* @param request so that request attributes can be retrieved
* @return the username that will be presented in the <code>Authentication</code>
* request token to the <code>AuthenticationManager</code>
*/
@Nullable
protected String obtainUsername(HttpServletRequest request) {
return request.getParameter(this.usernameParameter);
}
/**
* Provided so that subclasses may configure what is put into the authentication
* request's details property.
* @param request that an authentication request is being created for
* @param authRequest the authentication request object that should have its details
* set
*/
protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
}
/**
* Sets the parameter name which will be used to obtain the username from the login
* request.
* @param usernameParameter the parameter name. Defaults to "username".
*/
public void setUsernameParameter(String usernameParameter) {
Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
this.usernameParameter = usernameParameter;
}
/**
* Sets the parameter name which will be used to obtain the password from the login
* request..
* @param passwordParameter the parameter name. Defaults to "password".
*/
public void setPasswordParameter(String passwordParameter) {
Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
this.passwordParameter = passwordParameter;
}
/**
* Defines whether only HTTP POST requests will be allowed by this filter. If set to
* true, and an authentication request is received which is not a POST request, an
* exception will be raised immediately and authentication will not be attempted. The
* <tt>unsuccessfulAuthentication()</tt> method will be called as if handling a failed
* authentication.
* <p>
* Defaults to <tt>true</tt> but may be overridden by subclasses.
*/
public void setPostOnly(boolean postOnly) {
this.postOnly = postOnly;
}
public final String getUsernameParameter() {
return this.usernameParameter;
}
public final String getPasswordParameter() {
return this.passwordParameter;
}
}
| 6,831 | 38.953216 | 114 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/rememberme/package-info.java | /*
* Copyright 2002-2016 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.
*/
/**
* Support for remembering a user between different web sessions.
* <p>
* Comes with two default implementations. See the <a href=
* "https://docs.spring.io/spring-security/site/docs/3.0.x/reference/remember-me.html">Remember-Me
* Authentication</a> chapter of the reference manual.
*/
package org.springframework.security.web.authentication.rememberme;
| 986 | 38.48 | 98 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilter.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.web.authentication.rememberme;
import java.io.IOException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.core.log.LogMessage;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.util.Assert;
import org.springframework.web.filter.GenericFilterBean;
/**
* Detects if there is no {@code Authentication} object in the {@code SecurityContext},
* and populates the context with a remember-me authentication token if a
* {@link RememberMeServices} implementation so requests.
* <p>
* Concrete {@code RememberMeServices} implementations will have their
* {@link RememberMeServices#autoLogin(HttpServletRequest, HttpServletResponse)} method
* called by this filter. If this method returns a non-null {@code Authentication} object,
* it will be passed to the {@code AuthenticationManager}, so that any
* authentication-specific behaviour can be achieved. The resulting {@code Authentication}
* (if successful) will be placed into the {@code SecurityContext}.
* <p>
* If authentication is successful, an {@link InteractiveAuthenticationSuccessEvent} will
* be published to the application context. No events will be published if authentication
* was unsuccessful, because this would generally be recorded via an
* {@code AuthenticationManager}-specific application event.
* <p>
* Normally the request will be allowed to proceed regardless of whether authentication
* succeeds or fails. If some control over the destination for authenticated users is
* required, an {@link AuthenticationSuccessHandler} can be injected
*
* @author Ben Alex
* @author Luke Taylor
*/
public class RememberMeAuthenticationFilter extends GenericFilterBean implements ApplicationEventPublisherAware {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private ApplicationEventPublisher eventPublisher;
private AuthenticationSuccessHandler successHandler;
private AuthenticationManager authenticationManager;
private RememberMeServices rememberMeServices;
private SecurityContextRepository securityContextRepository = new HttpSessionSecurityContextRepository();
public RememberMeAuthenticationFilter(AuthenticationManager authenticationManager,
RememberMeServices rememberMeServices) {
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
Assert.notNull(rememberMeServices, "rememberMeServices cannot be null");
this.authenticationManager = authenticationManager;
this.rememberMeServices = rememberMeServices;
}
@Override
public void afterPropertiesSet() {
Assert.notNull(this.authenticationManager, "authenticationManager must be specified");
Assert.notNull(this.rememberMeServices, "rememberMeServices must be specified");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
}
private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (this.securityContextHolderStrategy.getContext().getAuthentication() != null) {
this.logger.debug(LogMessage
.of(() -> "SecurityContextHolder not populated with remember-me token, as it already contained: '"
+ this.securityContextHolderStrategy.getContext().getAuthentication() + "'"));
chain.doFilter(request, response);
return;
}
Authentication rememberMeAuth = this.rememberMeServices.autoLogin(request, response);
if (rememberMeAuth != null) {
// Attempt authentication via AuthenticationManager
try {
rememberMeAuth = this.authenticationManager.authenticate(rememberMeAuth);
// Store to SecurityContextHolder
SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
context.setAuthentication(rememberMeAuth);
this.securityContextHolderStrategy.setContext(context);
onSuccessfulAuthentication(request, response, rememberMeAuth);
this.logger.debug(LogMessage.of(() -> "SecurityContextHolder populated with remember-me token: '"
+ this.securityContextHolderStrategy.getContext().getAuthentication() + "'"));
this.securityContextRepository.saveContext(context, request, response);
if (this.eventPublisher != null) {
this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(
this.securityContextHolderStrategy.getContext().getAuthentication(), this.getClass()));
}
if (this.successHandler != null) {
this.successHandler.onAuthenticationSuccess(request, response, rememberMeAuth);
return;
}
}
catch (AuthenticationException ex) {
this.logger.debug(LogMessage
.format("SecurityContextHolder not populated with remember-me token, as AuthenticationManager "
+ "rejected Authentication returned by RememberMeServices: '%s'; "
+ "invalidating remember-me token", rememberMeAuth),
ex);
this.rememberMeServices.loginFail(request, response);
onUnsuccessfulAuthentication(request, response, ex);
}
}
chain.doFilter(request, response);
}
/**
* Called if a remember-me token is presented and successfully authenticated by the
* {@code RememberMeServices} {@code autoLogin} method and the
* {@code AuthenticationManager}.
*/
protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
Authentication authResult) {
}
/**
* Called if the {@code AuthenticationManager} rejects the authentication object
* returned from the {@code RememberMeServices} {@code autoLogin} method. This method
* will not be called when no remember-me token is present in the request and
* {@code autoLogin} reurns null.
*/
protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) {
}
public RememberMeServices getRememberMeServices() {
return this.rememberMeServices;
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
/**
* Allows control over the destination a remembered user is sent to when they are
* successfully authenticated. By default, the filter will just allow the current
* request to proceed, but if an {@code AuthenticationSuccessHandler} is set, it will
* be invoked and the {@code doFilter()} method will return immediately, thus allowing
* the application to redirect the user to a specific URL, regardless of whatthe
* original request was for.
* @param successHandler the strategy to invoke immediately before returning from
* {@code doFilter()}.
*/
public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler successHandler) {
Assert.notNull(successHandler, "successHandler cannot be null");
this.successHandler = successHandler;
}
/**
* Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on
* authentication success. The default action is not to save the
* {@link SecurityContext}.
* @param securityContextRepository the {@link SecurityContextRepository} to use.
* Cannot be null.
*/
public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) {
Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
this.securityContextRepository = securityContextRepository;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
}
| 9,803 | 44.6 | 113 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.web.authentication.rememberme;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.crypto.codec.Utf8;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Identifies previously remembered users by a Base-64 encoded cookie.
*
* <p>
* This implementation does not rely on an external database, so is attractive for simple
* applications. The cookie will be valid for a specific period from the date of the last
* {@link #loginSuccess(HttpServletRequest, HttpServletResponse, Authentication)}. As per
* the interface contract, this method will only be called when the principal completes a
* successful interactive authentication. As such the time period commences from the last
* authentication attempt where they furnished credentials - not the time period they last
* logged in via remember-me. The implementation will only send a remember-me token if the
* parameter defined by {@link #setParameter(String)} is present.
* <p>
* An {@link org.springframework.security.core.userdetails.UserDetailsService} is required
* by this implementation, so that it can construct a valid <code>Authentication</code>
* from the returned {@link org.springframework.security.core.userdetails.UserDetails}.
* This is also necessary so that the user's password is available and can be checked as
* part of the encoded cookie.
* <p>
* The cookie encoded by this implementation adopts the following form:
*
* <pre>
* username + ":" + expiryTime + ":" + algorithmName + ":"
* + algorithmHex(username + ":" + expiryTime + ":" + password + ":" + key)
* </pre>
*
* <p>
* This implementation uses the algorithm configured in {@link #encodingAlgorithm} to
* encode the signature. It will try to use the algorithm retrieved from the
* {@code algorithmName} to validate the signature. However, if the {@code algorithmName}
* is not present in the cookie value, the algorithm configured in
* {@link #matchingAlgorithm} will be used to validate the signature. This allows users to
* safely upgrade to a different encoding algorithm while still able to verify old ones if
* there is no {@code algorithmName} present.
* </p>
*
* <p>
* As such, if the user changes their password, any remember-me token will be invalidated.
* Equally, the system administrator may invalidate every remember-me token on issue by
* changing the key. This provides some reasonable approaches to recovering from a
* remember-me token being left on a public machine (e.g. kiosk system, Internet cafe
* etc). Most importantly, at no time is the user's password ever sent to the user agent,
* providing an important security safeguard. Unfortunately the username is necessary in
* this implementation (as we do not want to rely on a database for remember-me services).
* High security applications should be aware of this occasionally undesired disclosure of
* a valid username.
* <p>
* This is a basic remember-me implementation which is suitable for many applications.
* However, we recommend a database-based implementation if you require a more secure
* remember-me approach (see {@link PersistentTokenBasedRememberMeServices}).
* <p>
* By default the tokens will be valid for 14 days from the last successful authentication
* attempt. This can be changed using {@link #setTokenValiditySeconds(int)}. If this value
* is less than zero, the <tt>expiryTime</tt> will remain at 14 days, but the negative
* value will be used for the <tt>maxAge</tt> property of the cookie, meaning that it will
* not be stored when the browser is closed.
*
* @author Ben Alex
* @author Marcus Da Coregio
*/
public class TokenBasedRememberMeServices extends AbstractRememberMeServices {
private static final RememberMeTokenAlgorithm DEFAULT_MATCHING_ALGORITHM = RememberMeTokenAlgorithm.SHA256;
private static final RememberMeTokenAlgorithm DEFAULT_ENCODING_ALGORITHM = RememberMeTokenAlgorithm.SHA256;
private final RememberMeTokenAlgorithm encodingAlgorithm;
private RememberMeTokenAlgorithm matchingAlgorithm = DEFAULT_MATCHING_ALGORITHM;
public TokenBasedRememberMeServices(String key, UserDetailsService userDetailsService) {
this(key, userDetailsService, DEFAULT_ENCODING_ALGORITHM);
}
/**
* Construct the instance with the parameters provided
* @param key the signature key
* @param userDetailsService the {@link UserDetailsService}
* @param encodingAlgorithm the {@link RememberMeTokenAlgorithm} used to encode the
* signature
* @since 5.8
*/
public TokenBasedRememberMeServices(String key, UserDetailsService userDetailsService,
RememberMeTokenAlgorithm encodingAlgorithm) {
super(key, userDetailsService);
Assert.notNull(encodingAlgorithm, "encodingAlgorithm cannot be null");
this.encodingAlgorithm = encodingAlgorithm;
}
@Override
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request,
HttpServletResponse response) {
if (!isValidCookieTokensLength(cookieTokens)) {
throw new InvalidCookieException(
"Cookie token did not contain 3 or 4 tokens, but contained '" + Arrays.asList(cookieTokens) + "'");
}
long tokenExpiryTime = getTokenExpiryTime(cookieTokens);
if (isTokenExpired(tokenExpiryTime)) {
throw new InvalidCookieException("Cookie token[1] has expired (expired on '" + new Date(tokenExpiryTime)
+ "'; current time is '" + new Date() + "')");
}
// Check the user exists. Defer lookup until after expiry time checked, to
// possibly avoid expensive database call.
UserDetails userDetails = getUserDetailsService().loadUserByUsername(cookieTokens[0]);
Assert.notNull(userDetails, () -> "UserDetailsService " + getUserDetailsService()
+ " returned null for username " + cookieTokens[0] + ". " + "This is an interface contract violation");
// Check signature of token matches remaining details. Must do this after user
// lookup, as we need the DAO-derived password. If efficiency was a major issue,
// just add in a UserCache implementation, but recall that this method is usually
// only called once per HttpSession - if the token is valid, it will cause
// SecurityContextHolder population, whilst if invalid, will cause the cookie to
// be cancelled.
String actualTokenSignature = cookieTokens[2];
RememberMeTokenAlgorithm actualAlgorithm = this.matchingAlgorithm;
// If the cookie value contains the algorithm, we use that algorithm to check the
// signature
if (cookieTokens.length == 4) {
actualTokenSignature = cookieTokens[3];
actualAlgorithm = RememberMeTokenAlgorithm.valueOf(cookieTokens[2]);
}
String expectedTokenSignature = makeTokenSignature(tokenExpiryTime, userDetails.getUsername(),
userDetails.getPassword(), actualAlgorithm);
if (!equals(expectedTokenSignature, actualTokenSignature)) {
throw new InvalidCookieException("Cookie contained signature '" + actualTokenSignature + "' but expected '"
+ expectedTokenSignature + "'");
}
return userDetails;
}
private boolean isValidCookieTokensLength(String[] cookieTokens) {
return cookieTokens.length == 3 || cookieTokens.length == 4;
}
private long getTokenExpiryTime(String[] cookieTokens) {
try {
return Long.valueOf(cookieTokens[1]);
}
catch (NumberFormatException nfe) {
throw new InvalidCookieException(
"Cookie token[1] did not contain a valid number (contained '" + cookieTokens[1] + "')");
}
}
/**
* Calculates the digital signature to be put in the cookie. Default value is
* {@link #encodingAlgorithm} applied to ("username:tokenExpiryTime:password:key")
*/
protected String makeTokenSignature(long tokenExpiryTime, String username, String password) {
String data = username + ":" + tokenExpiryTime + ":" + password + ":" + getKey();
try {
MessageDigest digest = MessageDigest.getInstance(this.encodingAlgorithm.getDigestAlgorithm());
return new String(Hex.encode(digest.digest(data.getBytes())));
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("No " + this.encodingAlgorithm.name() + " algorithm available!");
}
}
/**
* Calculates the digital signature to be put in the cookie.
* @since 5.8
*/
protected String makeTokenSignature(long tokenExpiryTime, String username, String password,
RememberMeTokenAlgorithm algorithm) {
String data = username + ":" + tokenExpiryTime + ":" + password + ":" + getKey();
try {
MessageDigest digest = MessageDigest.getInstance(algorithm.getDigestAlgorithm());
return new String(Hex.encode(digest.digest(data.getBytes())));
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("No " + algorithm.name() + " algorithm available!");
}
}
protected boolean isTokenExpired(long tokenExpiryTime) {
return tokenExpiryTime < System.currentTimeMillis();
}
@Override
public void onLoginSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication successfulAuthentication) {
String username = retrieveUserName(successfulAuthentication);
String password = retrievePassword(successfulAuthentication);
// If unable to find a username and password, just abort as
// TokenBasedRememberMeServices is
// unable to construct a valid token in this case.
if (!StringUtils.hasLength(username)) {
this.logger.debug("Unable to retrieve username");
return;
}
if (!StringUtils.hasLength(password)) {
UserDetails user = getUserDetailsService().loadUserByUsername(username);
password = user.getPassword();
if (!StringUtils.hasLength(password)) {
this.logger.debug("Unable to obtain password for user: " + username);
return;
}
}
int tokenLifetime = calculateLoginLifetime(request, successfulAuthentication);
long expiryTime = System.currentTimeMillis();
// SEC-949
expiryTime += 1000L * ((tokenLifetime < 0) ? TWO_WEEKS_S : tokenLifetime);
String signatureValue = makeTokenSignature(expiryTime, username, password, this.encodingAlgorithm);
setCookie(new String[] { username, Long.toString(expiryTime), this.encodingAlgorithm.name(), signatureValue },
tokenLifetime, request, response);
if (this.logger.isDebugEnabled()) {
this.logger.debug(
"Added remember-me cookie for user '" + username + "', expiry: '" + new Date(expiryTime) + "'");
}
}
/**
* Sets the algorithm to be used to match the token signature
* @param matchingAlgorithm the matching algorithm
* @since 5.8
*/
public void setMatchingAlgorithm(RememberMeTokenAlgorithm matchingAlgorithm) {
Assert.notNull(matchingAlgorithm, "matchingAlgorithm cannot be null");
this.matchingAlgorithm = matchingAlgorithm;
}
/**
* Calculates the validity period in seconds for a newly generated remember-me login.
* After this period (from the current time) the remember-me login will be considered
* expired. This method allows customization based on request parameters supplied with
* the login or information in the <tt>Authentication</tt> object. The default value
* is just the token validity period property, <tt>tokenValiditySeconds</tt>.
* <p>
* The returned value will be used to work out the expiry time of the token and will
* also be used to set the <tt>maxAge</tt> property of the cookie.
* <p>
* See SEC-485.
* @param request the request passed to onLoginSuccess
* @param authentication the successful authentication object.
* @return the lifetime in seconds.
*/
protected int calculateLoginLifetime(HttpServletRequest request, Authentication authentication) {
return getTokenValiditySeconds();
}
protected String retrieveUserName(Authentication authentication) {
if (isInstanceOfUserDetails(authentication)) {
return ((UserDetails) authentication.getPrincipal()).getUsername();
}
return authentication.getPrincipal().toString();
}
protected String retrievePassword(Authentication authentication) {
if (isInstanceOfUserDetails(authentication)) {
return ((UserDetails) authentication.getPrincipal()).getPassword();
}
if (authentication.getCredentials() != null) {
return authentication.getCredentials().toString();
}
return null;
}
private boolean isInstanceOfUserDetails(Authentication authentication) {
return authentication.getPrincipal() instanceof UserDetails;
}
/**
* Constant time comparison to prevent against timing attacks.
*/
private static boolean equals(String expected, String actual) {
byte[] expectedBytes = bytesUtf8(expected);
byte[] actualBytes = bytesUtf8(actual);
return MessageDigest.isEqual(expectedBytes, actualBytes);
}
private static byte[] bytesUtf8(String s) {
return (s != null) ? Utf8.encode(s) : null;
}
public enum RememberMeTokenAlgorithm {
MD5("MD5"), SHA256("SHA-256");
private final String digestAlgorithm;
RememberMeTokenAlgorithm(String digestAlgorithm) {
this.digestAlgorithm = digestAlgorithm;
}
public String getDigestAlgorithm() {
return this.digestAlgorithm;
}
}
}
| 14,122 | 42.322086 | 112 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServices.java | /*
* Copyright 2002-2023 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.web.authentication.rememberme;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.core.log.LogMessage;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.core.authority.mapping.NullAuthoritiesMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Base class for RememberMeServices implementations.
*
* @author Luke Taylor
* @author Rob Winch
* @author Eddú Meléndez
* @author Onur Kagan Ozcan
* @since 2.0
*/
public abstract class AbstractRememberMeServices
implements RememberMeServices, InitializingBean, LogoutHandler, MessageSourceAware {
public static final String SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY = "remember-me";
public static final String DEFAULT_PARAMETER = "remember-me";
public static final int TWO_WEEKS_S = 1209600;
private static final String DELIMITER = ":";
protected final Log logger = LogFactory.getLog(getClass());
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private UserDetailsService userDetailsService;
private UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker();
private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
private String cookieName = SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY;
private String cookieDomain;
private String parameter = DEFAULT_PARAMETER;
private boolean alwaysRemember;
private String key;
private int tokenValiditySeconds = TWO_WEEKS_S;
private Boolean useSecureCookie = null;
private GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper();
protected AbstractRememberMeServices(String key, UserDetailsService userDetailsService) {
Assert.hasLength(key, "key cannot be empty or null");
Assert.notNull(userDetailsService, "UserDetailsService cannot be null");
this.key = key;
this.userDetailsService = userDetailsService;
}
@Override
public void afterPropertiesSet() {
Assert.hasLength(this.key, "key cannot be empty or null");
Assert.notNull(this.userDetailsService, "A UserDetailsService is required");
}
/**
* Template implementation which locates the Spring Security cookie, decodes it into a
* delimited array of tokens and submits it to subclasses for processing via the
* <tt>processAutoLoginCookie</tt> method.
* <p>
* The returned username is then used to load the UserDetails object for the user,
* which in turn is used to create a valid authentication token.
*/
@Override
public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) {
String rememberMeCookie = extractRememberMeCookie(request);
if (rememberMeCookie == null) {
return null;
}
this.logger.debug("Remember-me cookie detected");
if (rememberMeCookie.length() == 0) {
this.logger.debug("Cookie was empty");
cancelCookie(request, response);
return null;
}
try {
String[] cookieTokens = decodeCookie(rememberMeCookie);
UserDetails user = processAutoLoginCookie(cookieTokens, request, response);
this.userDetailsChecker.check(user);
this.logger.debug("Remember-me cookie accepted");
return createSuccessfulAuthentication(request, user);
}
catch (CookieTheftException ex) {
cancelCookie(request, response);
throw ex;
}
catch (UsernameNotFoundException ex) {
this.logger.debug("Remember-me login was valid but corresponding user not found.", ex);
}
catch (InvalidCookieException ex) {
this.logger.debug("Invalid remember-me cookie: " + ex.getMessage());
}
catch (AccountStatusException ex) {
this.logger.debug("Invalid UserDetails: " + ex.getMessage());
}
catch (RememberMeAuthenticationException ex) {
this.logger.debug(ex.getMessage());
}
cancelCookie(request, response);
return null;
}
/**
* Locates the Spring Security remember me cookie in the request and returns its
* value. The cookie is searched for by name and also by matching the context path to
* the cookie path.
* @param request the submitted request which is to be authenticated
* @return the cookie value (if present), null otherwise.
*/
protected String extractRememberMeCookie(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if ((cookies == null) || (cookies.length == 0)) {
return null;
}
for (Cookie cookie : cookies) {
if (this.cookieName.equals(cookie.getName())) {
return cookie.getValue();
}
}
return null;
}
/**
* Creates the final <tt>Authentication</tt> object returned from the
* <tt>autoLogin</tt> method.
* <p>
* By default it will create a <tt>RememberMeAuthenticationToken</tt> instance.
* @param request the original request. The configured
* <tt>AuthenticationDetailsSource</tt> will use this to build the details property of
* the returned object.
* @param user the <tt>UserDetails</tt> loaded from the <tt>UserDetailsService</tt>.
* This will be stored as the principal.
* @return the <tt>Authentication</tt> for the remember-me authenticated user
*/
protected Authentication createSuccessfulAuthentication(HttpServletRequest request, UserDetails user) {
RememberMeAuthenticationToken auth = new RememberMeAuthenticationToken(this.key, user,
this.authoritiesMapper.mapAuthorities(user.getAuthorities()));
auth.setDetails(this.authenticationDetailsSource.buildDetails(request));
return auth;
}
/**
* Decodes the cookie and splits it into a set of token strings using the ":"
* delimiter.
* @param cookieValue the value obtained from the submitted cookie
* @return the array of tokens.
* @throws InvalidCookieException if the cookie was not base64 encoded.
*/
protected String[] decodeCookie(String cookieValue) throws InvalidCookieException {
for (int j = 0; j < cookieValue.length() % 4; j++) {
cookieValue = cookieValue + "=";
}
String cookieAsPlainText;
try {
cookieAsPlainText = new String(Base64.getDecoder().decode(cookieValue.getBytes()));
}
catch (IllegalArgumentException ex) {
throw new InvalidCookieException("Cookie token was not Base64 encoded; value was '" + cookieValue + "'");
}
String[] tokens = StringUtils.delimitedListToStringArray(cookieAsPlainText, DELIMITER);
for (int i = 0; i < tokens.length; i++) {
try {
tokens[i] = URLDecoder.decode(tokens[i], StandardCharsets.UTF_8.toString());
}
catch (UnsupportedEncodingException ex) {
this.logger.error(ex.getMessage(), ex);
}
}
return tokens;
}
/**
* Inverse operation of decodeCookie.
* @param cookieTokens the tokens to be encoded.
* @return base64 encoding of the tokens concatenated with the ":" delimiter.
*/
protected String encodeCookie(String[] cookieTokens) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cookieTokens.length; i++) {
try {
sb.append(URLEncoder.encode(cookieTokens[i], StandardCharsets.UTF_8.toString()));
}
catch (UnsupportedEncodingException ex) {
this.logger.error(ex.getMessage(), ex);
}
if (i < cookieTokens.length - 1) {
sb.append(DELIMITER);
}
}
String value = sb.toString();
sb = new StringBuilder(new String(Base64.getEncoder().encode(value.getBytes())));
while (sb.charAt(sb.length() - 1) == '=') {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
@Override
public void loginFail(HttpServletRequest request, HttpServletResponse response) {
this.logger.debug("Interactive login attempt was unsuccessful.");
cancelCookie(request, response);
onLoginFail(request, response);
}
protected void onLoginFail(HttpServletRequest request, HttpServletResponse response) {
}
/**
* {@inheritDoc}
*
* <p>
* Examines the incoming request and checks for the presence of the configured
* "remember me" parameter. If it's present, or if <tt>alwaysRemember</tt> is set to
* true, calls <tt>onLoginSuccess</tt>.
* </p>
*/
@Override
public void loginSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication successfulAuthentication) {
if (!rememberMeRequested(request, this.parameter)) {
this.logger.debug("Remember-me login not requested.");
return;
}
onLoginSuccess(request, response, successfulAuthentication);
}
/**
* Called from loginSuccess when a remember-me login has been requested. Typically
* implemented by subclasses to set a remember-me cookie and potentially store a
* record of it if the implementation requires this.
*/
protected abstract void onLoginSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication successfulAuthentication);
/**
* Allows customization of whether a remember-me login has been requested. The default
* is to return true if <tt>alwaysRemember</tt> is set or the configured parameter
* name has been included in the request and is set to the value "true".
* @param request the request submitted from an interactive login, which may include
* additional information indicating that a persistent login is desired.
* @param parameter the configured remember-me parameter name.
* @return true if the request includes information indicating that a persistent login
* has been requested.
*/
protected boolean rememberMeRequested(HttpServletRequest request, String parameter) {
if (this.alwaysRemember) {
return true;
}
String paramValue = request.getParameter(parameter);
if (paramValue != null) {
if (paramValue.equalsIgnoreCase("true") || paramValue.equalsIgnoreCase("on")
|| paramValue.equalsIgnoreCase("yes") || paramValue.equals("1")) {
return true;
}
}
this.logger.debug(
LogMessage.format("Did not send remember-me cookie (principal did not set parameter '%s')", parameter));
return false;
}
/**
* Called from autoLogin to process the submitted persistent login cookie. Subclasses
* should validate the cookie and perform any additional management required.
* @param cookieTokens the decoded and tokenized cookie value
* @param request the request
* @param response the response, to allow the cookie to be modified if required.
* @return the UserDetails for the corresponding user account if the cookie was
* validated successfully.
* @throws RememberMeAuthenticationException if the cookie is invalid or the login is
* invalid for some other reason.
* @throws UsernameNotFoundException if the user account corresponding to the login
* cookie couldn't be found (for example if the user has been removed from the
* system).
*/
protected abstract UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request,
HttpServletResponse response) throws RememberMeAuthenticationException, UsernameNotFoundException;
/**
* Sets a "cancel cookie" (with maxAge = 0) on the response to disable persistent
* logins.
*/
protected void cancelCookie(HttpServletRequest request, HttpServletResponse response) {
this.logger.debug("Cancelling cookie");
Cookie cookie = new Cookie(this.cookieName, null);
cookie.setMaxAge(0);
cookie.setPath(getCookiePath(request));
if (this.cookieDomain != null) {
cookie.setDomain(this.cookieDomain);
}
cookie.setSecure((this.useSecureCookie != null) ? this.useSecureCookie : request.isSecure());
response.addCookie(cookie);
}
/**
* Sets the cookie on the response.
*
* By default a secure cookie will be used if the connection is secure. You can set
* the {@code useSecureCookie} property to {@code false} to override this. If you set
* it to {@code true}, the cookie will always be flagged as secure. By default the
* cookie will be marked as HttpOnly.
* @param tokens the tokens which will be encoded to make the cookie value.
* @param maxAge the value passed to {@link Cookie#setMaxAge(int)}
* @param request the request
* @param response the response to add the cookie to.
*/
protected void setCookie(String[] tokens, int maxAge, HttpServletRequest request, HttpServletResponse response) {
String cookieValue = encodeCookie(tokens);
Cookie cookie = new Cookie(this.cookieName, cookieValue);
cookie.setMaxAge(maxAge);
cookie.setPath(getCookiePath(request));
if (this.cookieDomain != null) {
cookie.setDomain(this.cookieDomain);
}
if (maxAge < 1) {
cookie.setVersion(1);
}
cookie.setSecure((this.useSecureCookie != null) ? this.useSecureCookie : request.isSecure());
cookie.setHttpOnly(true);
response.addCookie(cookie);
}
private String getCookiePath(HttpServletRequest request) {
String contextPath = request.getContextPath();
return (contextPath.length() > 0) ? contextPath : "/";
}
/**
* Implementation of {@code LogoutHandler}. Default behaviour is to call
* {@code cancelCookie()}.
*/
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
this.logger.debug(LogMessage
.of(() -> "Logout of user " + ((authentication != null) ? authentication.getName() : "Unknown")));
cancelCookie(request, response);
}
public void setCookieName(String cookieName) {
Assert.hasLength(cookieName, "Cookie name cannot be empty or null");
this.cookieName = cookieName;
}
public void setCookieDomain(String cookieDomain) {
Assert.hasLength(cookieDomain, "Cookie domain cannot be empty or null");
this.cookieDomain = cookieDomain;
}
protected String getCookieName() {
return this.cookieName;
}
public void setAlwaysRemember(boolean alwaysRemember) {
this.alwaysRemember = alwaysRemember;
}
/**
* Sets the name of the parameter which should be checked for to see if a remember-me
* has been requested during a login request. This should be the same name you assign
* to the checkbox in your login form.
* @param parameter the HTTP request parameter
*/
public void setParameter(String parameter) {
Assert.hasText(parameter, "Parameter name cannot be empty or null");
this.parameter = parameter;
}
public String getParameter() {
return this.parameter;
}
protected UserDetailsService getUserDetailsService() {
return this.userDetailsService;
}
public String getKey() {
return this.key;
}
public void setTokenValiditySeconds(int tokenValiditySeconds) {
this.tokenValiditySeconds = tokenValiditySeconds;
}
protected int getTokenValiditySeconds() {
return this.tokenValiditySeconds;
}
/**
* Whether the cookie should be flagged as secure or not. Secure cookies can only be
* sent over an HTTPS connection and thus cannot be accidentally submitted over HTTP
* where they could be intercepted.
* <p>
* By default the cookie will be secure if the request is secure. If you only want to
* use remember-me over HTTPS (recommended) you should set this property to
* {@code true}.
* @param useSecureCookie set to {@code true} to always user secure cookies,
* {@code false} to disable their use.
*/
public void setUseSecureCookie(boolean useSecureCookie) {
this.useSecureCookie = useSecureCookie;
}
protected AuthenticationDetailsSource<HttpServletRequest, ?> getAuthenticationDetailsSource() {
return this.authenticationDetailsSource;
}
public void setAuthenticationDetailsSource(
AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource cannot be null");
this.authenticationDetailsSource = authenticationDetailsSource;
}
/**
* Sets the strategy to be used to validate the {@code UserDetails} object obtained
* for the user when processing a remember-me cookie to automatically log in a user.
* @param userDetailsChecker the strategy which will be passed the user object to
* allow it to be rejected if account should not be allowed to authenticate (if it is
* locked, for example). Defaults to a {@code AccountStatusUserDetailsChecker}
* instance.
*
*/
public void setUserDetailsChecker(UserDetailsChecker userDetailsChecker) {
this.userDetailsChecker = userDetailsChecker;
}
public void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) {
this.authoritiesMapper = authoritiesMapper;
}
/**
* @since 5.5
*/
@Override
public void setMessageSource(MessageSource messageSource) {
Assert.notNull(messageSource, "messageSource cannot be null");
this.messages = new MessageSourceAccessor(messageSource);
}
}
| 18,633 | 36.568548 | 127 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImpl.java | /*
* Copyright 2002-2012 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.web.authentication.rememberme;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import org.springframework.core.log.LogMessage;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
/**
* JDBC based persistent login token repository implementation.
*
* @author Luke Taylor
* @since 2.0
*/
public class JdbcTokenRepositoryImpl extends JdbcDaoSupport implements PersistentTokenRepository {
/** Default SQL for creating the database table to store the tokens */
public static final String CREATE_TABLE_SQL = "create table persistent_logins (username varchar(64) not null, series varchar(64) primary key, "
+ "token varchar(64) not null, last_used timestamp not null)";
/** The default SQL used by the <tt>getTokenBySeries</tt> query */
public static final String DEF_TOKEN_BY_SERIES_SQL = "select username,series,token,last_used from persistent_logins where series = ?";
/** The default SQL used by <tt>createNewToken</tt> */
public static final String DEF_INSERT_TOKEN_SQL = "insert into persistent_logins (username, series, token, last_used) values(?,?,?,?)";
/** The default SQL used by <tt>updateToken</tt> */
public static final String DEF_UPDATE_TOKEN_SQL = "update persistent_logins set token = ?, last_used = ? where series = ?";
/** The default SQL used by <tt>removeUserTokens</tt> */
public static final String DEF_REMOVE_USER_TOKENS_SQL = "delete from persistent_logins where username = ?";
private String tokensBySeriesSql = DEF_TOKEN_BY_SERIES_SQL;
private String insertTokenSql = DEF_INSERT_TOKEN_SQL;
private String updateTokenSql = DEF_UPDATE_TOKEN_SQL;
private String removeUserTokensSql = DEF_REMOVE_USER_TOKENS_SQL;
private boolean createTableOnStartup;
@Override
protected void initDao() {
if (this.createTableOnStartup) {
getJdbcTemplate().execute(CREATE_TABLE_SQL);
}
}
@Override
public void createNewToken(PersistentRememberMeToken token) {
getJdbcTemplate().update(this.insertTokenSql, token.getUsername(), token.getSeries(), token.getTokenValue(),
token.getDate());
}
@Override
public void updateToken(String series, String tokenValue, Date lastUsed) {
getJdbcTemplate().update(this.updateTokenSql, tokenValue, lastUsed, series);
}
/**
* Loads the token data for the supplied series identifier.
*
* If an error occurs, it will be reported and null will be returned (since the result
* should just be a failed persistent login).
* @param seriesId
* @return the token matching the series, or null if no match found or an exception
* occurred.
*/
@Override
public PersistentRememberMeToken getTokenForSeries(String seriesId) {
try {
return getJdbcTemplate().queryForObject(this.tokensBySeriesSql, this::createRememberMeToken, seriesId);
}
catch (EmptyResultDataAccessException ex) {
this.logger.debug(LogMessage.format("Querying token for series '%s' returned no results.", seriesId), ex);
}
catch (IncorrectResultSizeDataAccessException ex) {
this.logger.error(LogMessage.format(
"Querying token for series '%s' returned more than one value. Series" + " should be unique",
seriesId));
}
catch (DataAccessException ex) {
this.logger.error("Failed to load token for series " + seriesId, ex);
}
return null;
}
private PersistentRememberMeToken createRememberMeToken(ResultSet rs, int rowNum) throws SQLException {
return new PersistentRememberMeToken(rs.getString(1), rs.getString(2), rs.getString(3), rs.getTimestamp(4));
}
@Override
public void removeUserTokens(String username) {
getJdbcTemplate().update(this.removeUserTokensSql, username);
}
/**
* Intended for convenience in debugging. Will create the persistent_tokens database
* table when the class is initialized during the initDao method.
* @param createTableOnStartup set to true to execute the
*/
public void setCreateTableOnStartup(boolean createTableOnStartup) {
this.createTableOnStartup = createTableOnStartup;
}
}
| 4,834 | 36.773438 | 144 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/rememberme/InvalidCookieException.java | /*
* Copyright 2002-2016 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.web.authentication.rememberme;
/**
* Exception thrown by a RememberMeServices implementation to indicate that a submitted
* cookie is of an invalid format or has expired.
*
* @author Luke Taylor
*/
public class InvalidCookieException extends RememberMeAuthenticationException {
public InvalidCookieException(String message) {
super(message);
}
}
| 1,018 | 30.84375 | 87 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/rememberme/PersistentTokenRepository.java | /*
* Copyright 2002-2016 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.web.authentication.rememberme;
import java.util.Date;
/**
* The abstraction used by {@link PersistentTokenBasedRememberMeServices} to store the
* persistent login tokens for a user.
*
* @author Luke Taylor
* @since 2.0
* @see JdbcTokenRepositoryImpl
* @see InMemoryTokenRepositoryImpl
*/
public interface PersistentTokenRepository {
void createNewToken(PersistentRememberMeToken token);
void updateToken(String series, String tokenValue, Date lastUsed);
PersistentRememberMeToken getTokenForSeries(String seriesId);
void removeUserTokens(String username);
}
| 1,237 | 29.195122 | 86 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationException.java | /*
* Copyright 2002-2016 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.web.authentication.rememberme;
import org.springframework.security.core.AuthenticationException;
/**
* This exception is thrown when an
* {@link org.springframework.security.core.Authentication} exception occurs while using
* the remember-me authentication.
*
* @author Luke Taylor
*/
public class RememberMeAuthenticationException extends AuthenticationException {
/**
* Constructs a {@code RememberMeAuthenticationException} with the specified message
* and root cause.
* @param msg the detail message
* @param cause the root cause
*/
public RememberMeAuthenticationException(String msg, Throwable cause) {
super(msg, cause);
}
/**
* Constructs an {@code RememberMeAuthenticationException} with the specified message
* and no root cause.
* @param msg the detail message
*/
public RememberMeAuthenticationException(String msg) {
super(msg);
}
}
| 1,545 | 29.92 | 88 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/rememberme/InMemoryTokenRepositoryImpl.java | /*
* Copyright 2002-2016 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.web.authentication.rememberme;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.springframework.dao.DataIntegrityViolationException;
/**
* Simple <tt>PersistentTokenRepository</tt> implementation backed by a Map. Intended for
* testing only.
*
* @author Luke Taylor
*/
public class InMemoryTokenRepositoryImpl implements PersistentTokenRepository {
private final Map<String, PersistentRememberMeToken> seriesTokens = new HashMap<>();
@Override
public synchronized void createNewToken(PersistentRememberMeToken token) {
PersistentRememberMeToken current = this.seriesTokens.get(token.getSeries());
if (current != null) {
throw new DataIntegrityViolationException("Series Id '" + token.getSeries() + "' already exists!");
}
this.seriesTokens.put(token.getSeries(), token);
}
@Override
public synchronized void updateToken(String series, String tokenValue, Date lastUsed) {
PersistentRememberMeToken token = getTokenForSeries(series);
PersistentRememberMeToken newToken = new PersistentRememberMeToken(token.getUsername(), series, tokenValue,
new Date());
// Store it, overwriting the existing one.
this.seriesTokens.put(series, newToken);
}
@Override
public synchronized PersistentRememberMeToken getTokenForSeries(String seriesId) {
return this.seriesTokens.get(seriesId);
}
@Override
public synchronized void removeUserTokens(String username) {
Iterator<String> series = this.seriesTokens.keySet().iterator();
while (series.hasNext()) {
String seriesId = series.next();
PersistentRememberMeToken token = this.seriesTokens.get(seriesId);
if (username.equals(token.getUsername())) {
series.remove();
}
}
}
}
| 2,400 | 32.347222 | 109 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/rememberme/PersistentRememberMeToken.java | /*
* Copyright 2002-2016 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.web.authentication.rememberme;
import java.util.Date;
/**
* @author Luke Taylor
*/
public class PersistentRememberMeToken {
private final String username;
private final String series;
private final String tokenValue;
private final Date date;
public PersistentRememberMeToken(String username, String series, String tokenValue, Date date) {
this.username = username;
this.series = series;
this.tokenValue = tokenValue;
this.date = date;
}
public String getUsername() {
return this.username;
}
public String getSeries() {
return this.series;
}
public String getTokenValue() {
return this.tokenValue;
}
public Date getDate() {
return this.date;
}
}
| 1,349 | 22.275862 | 97 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/rememberme/CookieTheftException.java | /*
* Copyright 2002-2016 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.web.authentication.rememberme;
/**
* @author Luke Taylor
*/
public class CookieTheftException extends RememberMeAuthenticationException {
public CookieTheftException(String message) {
super(message);
}
}
| 873 | 29.137931 | 77 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServices.java | /*
* Copyright 2002-2017 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.web.authentication.rememberme;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.log.LogMessage;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.util.Assert;
/**
* {@link RememberMeServices} implementation based on Barry Jaspan's
* <a href="http://jaspan.com/improved_persistent_login_cookie_best_practice">Improved
* Persistent Login Cookie Best Practice</a>.
*
* There is a slight modification to the described approach, in that the username is not
* stored as part of the cookie but obtained from the persistent store via an
* implementation of {@link PersistentTokenRepository}. The latter should place a unique
* constraint on the series identifier, so that it is impossible for the same identifier
* to be allocated to two different users.
*
* <p>
* User management such as changing passwords, removing users and setting user status
* should be combined with maintenance of the user's persistent tokens.
* </p>
*
* <p>
* Note that while this class will use the date a token was created to check whether a
* presented cookie is older than the configured <tt>tokenValiditySeconds</tt> property
* and deny authentication in this case, it will not delete these tokens from storage. A
* suitable batch process should be run periodically to remove expired tokens from the
* database.
* </p>
*
* @author Luke Taylor
* @since 2.0
*/
public class PersistentTokenBasedRememberMeServices extends AbstractRememberMeServices {
private PersistentTokenRepository tokenRepository = new InMemoryTokenRepositoryImpl();
private SecureRandom random;
public static final int DEFAULT_SERIES_LENGTH = 16;
public static final int DEFAULT_TOKEN_LENGTH = 16;
private int seriesLength = DEFAULT_SERIES_LENGTH;
private int tokenLength = DEFAULT_TOKEN_LENGTH;
public PersistentTokenBasedRememberMeServices(String key, UserDetailsService userDetailsService,
PersistentTokenRepository tokenRepository) {
super(key, userDetailsService);
this.random = new SecureRandom();
this.tokenRepository = tokenRepository;
}
/**
* Locates the presented cookie data in the token repository, using the series id. If
* the data compares successfully with that in the persistent store, a new token is
* generated and stored with the same series. The corresponding cookie value is set on
* the response.
* @param cookieTokens the series and token values
* @throws RememberMeAuthenticationException if there is no stored token corresponding
* to the submitted cookie, or if the token in the persistent store has expired.
* @throws InvalidCookieException if the cookie doesn't have two tokens as expected.
* @throws CookieTheftException if a presented series value is found, but the stored
* token is different from the one presented.
*/
@Override
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request,
HttpServletResponse response) {
if (cookieTokens.length != 2) {
throw new InvalidCookieException("Cookie token did not contain " + 2 + " tokens, but contained '"
+ Arrays.asList(cookieTokens) + "'");
}
String presentedSeries = cookieTokens[0];
String presentedToken = cookieTokens[1];
PersistentRememberMeToken token = this.tokenRepository.getTokenForSeries(presentedSeries);
if (token == null) {
// No series match, so we can't authenticate using this cookie
throw new RememberMeAuthenticationException("No persistent token found for series id: " + presentedSeries);
}
// We have a match for this user/series combination
if (!presentedToken.equals(token.getTokenValue())) {
// Token doesn't match series value. Delete all logins for this user and throw
// an exception to warn them.
this.tokenRepository.removeUserTokens(token.getUsername());
throw new CookieTheftException(this.messages.getMessage(
"PersistentTokenBasedRememberMeServices.cookieStolen",
"Invalid remember-me token (Series/token) mismatch. Implies previous cookie theft attack."));
}
if (token.getDate().getTime() + getTokenValiditySeconds() * 1000L < System.currentTimeMillis()) {
throw new RememberMeAuthenticationException("Remember-me login has expired");
}
// Token also matches, so login is valid. Update the token value, keeping the
// *same* series number.
this.logger.debug(LogMessage.format("Refreshing persistent login token for user '%s', series '%s'",
token.getUsername(), token.getSeries()));
PersistentRememberMeToken newToken = new PersistentRememberMeToken(token.getUsername(), token.getSeries(),
generateTokenData(), new Date());
try {
this.tokenRepository.updateToken(newToken.getSeries(), newToken.getTokenValue(), newToken.getDate());
addCookie(newToken, request, response);
}
catch (Exception ex) {
this.logger.error("Failed to update token: ", ex);
throw new RememberMeAuthenticationException("Autologin failed due to data access problem");
}
return getUserDetailsService().loadUserByUsername(token.getUsername());
}
/**
* Creates a new persistent login token with a new series number, stores the data in
* the persistent token repository and adds the corresponding cookie to the response.
*
*/
@Override
protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication successfulAuthentication) {
String username = successfulAuthentication.getName();
this.logger.debug(LogMessage.format("Creating new persistent login for user %s", username));
PersistentRememberMeToken persistentToken = new PersistentRememberMeToken(username, generateSeriesData(),
generateTokenData(), new Date());
try {
this.tokenRepository.createNewToken(persistentToken);
addCookie(persistentToken, request, response);
}
catch (Exception ex) {
this.logger.error("Failed to save persistent token ", ex);
}
}
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
super.logout(request, response, authentication);
if (authentication != null) {
this.tokenRepository.removeUserTokens(authentication.getName());
}
}
protected String generateSeriesData() {
byte[] newSeries = new byte[this.seriesLength];
this.random.nextBytes(newSeries);
return new String(Base64.getEncoder().encode(newSeries));
}
protected String generateTokenData() {
byte[] newToken = new byte[this.tokenLength];
this.random.nextBytes(newToken);
return new String(Base64.getEncoder().encode(newToken));
}
private void addCookie(PersistentRememberMeToken token, HttpServletRequest request, HttpServletResponse response) {
setCookie(new String[] { token.getSeries(), token.getTokenValue() }, getTokenValiditySeconds(), request,
response);
}
public void setSeriesLength(int seriesLength) {
this.seriesLength = seriesLength;
}
public void setTokenLength(int tokenLength) {
this.tokenLength = tokenLength;
}
@Override
public void setTokenValiditySeconds(int tokenValiditySeconds) {
Assert.isTrue(tokenValiditySeconds > 0, "tokenValiditySeconds must be positive for this implementation");
super.setTokenValiditySeconds(tokenValiditySeconds);
}
}
| 8,254 | 40.691919 | 116 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/www/package-info.java | /*
* Copyright 2002-2016 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.
*/
/**
* WWW-Authenticate based authentication mechanism implementations: Basic and Digest
* authentication.
*/
package org.springframework.security.web.authentication.www;
| 796 | 35.227273 | 84 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilter.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.web.authentication.www;
import java.io.IOException;
import java.nio.charset.Charset;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.log.LogMessage;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.NullRememberMeServices;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* Processes a HTTP request's BASIC authorization headers, putting the result into the
* <code>SecurityContextHolder</code>.
*
* <p>
* For a detailed background on what this filter is designed to process, refer to
* <a href="https://tools.ietf.org/html/rfc1945">RFC 1945, Section 11.1</a>. Any realm
* name presented in the HTTP request is ignored.
*
* <p>
* In summary, this filter is responsible for processing any request that has a HTTP
* request header of <code>Authorization</code> with an authentication scheme of
* <code>Basic</code> and a Base64-encoded <code>username:password</code> token. For
* example, to authenticate user "Aladdin" with password "open sesame" the following
* header would be presented:
*
* <pre>
*
* Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
* </pre>
*
* <p>
* This filter can be used to provide BASIC authentication services to both remoting
* protocol clients (such as Hessian and SOAP) as well as standard user agents (such as
* Internet Explorer and Netscape).
* <p>
* If authentication is successful, the resulting {@link Authentication} object will be
* placed into the <code>SecurityContextHolder</code>.
*
* <p>
* If authentication fails and <code>ignoreFailure</code> is <code>false</code> (the
* default), an {@link AuthenticationEntryPoint} implementation is called (unless the
* <tt>ignoreFailure</tt> property is set to <tt>true</tt>). Usually this should be
* {@link BasicAuthenticationEntryPoint}, which will prompt the user to authenticate again
* via BASIC authentication.
*
* <p>
* Basic authentication is an attractive protocol because it is simple and widely
* deployed. However, it still transmits a password in clear text and as such is
* undesirable in many situations.
* <p>
* Note that if a {@link RememberMeServices} is set, this filter will automatically send
* back remember-me details to the client. Therefore, subsequent requests will not need to
* present a BASIC authentication header as they will be authenticated using the
* remember-me mechanism.
*
* @author Ben Alex
*/
public class BasicAuthenticationFilter extends OncePerRequestFilter {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private AuthenticationEntryPoint authenticationEntryPoint;
private AuthenticationManager authenticationManager;
private RememberMeServices rememberMeServices = new NullRememberMeServices();
private boolean ignoreFailure = false;
private String credentialsCharset = "UTF-8";
private BasicAuthenticationConverter authenticationConverter = new BasicAuthenticationConverter();
private SecurityContextRepository securityContextRepository = new RequestAttributeSecurityContextRepository();
/**
* Creates an instance which will authenticate against the supplied
* {@code AuthenticationManager} and which will ignore failed authentication attempts,
* allowing the request to proceed down the filter chain.
* @param authenticationManager the bean to submit authentication requests to
*/
public BasicAuthenticationFilter(AuthenticationManager authenticationManager) {
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
this.authenticationManager = authenticationManager;
this.ignoreFailure = true;
}
/**
* Creates an instance which will authenticate against the supplied
* {@code AuthenticationManager} and use the supplied {@code AuthenticationEntryPoint}
* to handle authentication failures.
* @param authenticationManager the bean to submit authentication requests to
* @param authenticationEntryPoint will be invoked when authentication fails.
* Typically an instance of {@link BasicAuthenticationEntryPoint}.
*/
public BasicAuthenticationFilter(AuthenticationManager authenticationManager,
AuthenticationEntryPoint authenticationEntryPoint) {
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
Assert.notNull(authenticationEntryPoint, "authenticationEntryPoint cannot be null");
this.authenticationManager = authenticationManager;
this.authenticationEntryPoint = authenticationEntryPoint;
}
/**
* Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on
* authentication success. The default action is not to save the
* {@link SecurityContext}.
* @param securityContextRepository the {@link SecurityContextRepository} to use.
* Cannot be null.
*/
public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) {
Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
this.securityContextRepository = securityContextRepository;
}
@Override
public void afterPropertiesSet() {
Assert.notNull(this.authenticationManager, "An AuthenticationManager is required");
if (!isIgnoreFailure()) {
Assert.notNull(this.authenticationEntryPoint, "An AuthenticationEntryPoint is required");
}
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
try {
UsernamePasswordAuthenticationToken authRequest = this.authenticationConverter.convert(request);
if (authRequest == null) {
this.logger.trace("Did not process authentication request since failed to find "
+ "username and password in Basic Authorization header");
chain.doFilter(request, response);
return;
}
String username = authRequest.getName();
this.logger.trace(LogMessage.format("Found username '%s' in Basic Authorization header", username));
if (authenticationIsRequired(username)) {
Authentication authResult = this.authenticationManager.authenticate(authRequest);
SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
context.setAuthentication(authResult);
this.securityContextHolderStrategy.setContext(context);
if (this.logger.isDebugEnabled()) {
this.logger.debug(LogMessage.format("Set SecurityContextHolder to %s", authResult));
}
this.rememberMeServices.loginSuccess(request, response, authResult);
this.securityContextRepository.saveContext(context, request, response);
onSuccessfulAuthentication(request, response, authResult);
}
}
catch (AuthenticationException ex) {
this.securityContextHolderStrategy.clearContext();
this.logger.debug("Failed to process authentication request", ex);
this.rememberMeServices.loginFail(request, response);
onUnsuccessfulAuthentication(request, response, ex);
if (this.ignoreFailure) {
chain.doFilter(request, response);
}
else {
this.authenticationEntryPoint.commence(request, response, ex);
}
return;
}
chain.doFilter(request, response);
}
protected boolean authenticationIsRequired(String username) {
// Only reauthenticate if username doesn't match SecurityContextHolder and user
// isn't authenticated (see SEC-53)
Authentication existingAuth = this.securityContextHolderStrategy.getContext().getAuthentication();
if (existingAuth == null || !existingAuth.getName().equals(username) || !existingAuth.isAuthenticated()) {
return true;
}
// Handle unusual condition where an AnonymousAuthenticationToken is already
// present. This shouldn't happen very often, as BasicProcessingFitler is meant to
// be earlier in the filter chain than AnonymousAuthenticationFilter.
// Nevertheless, presence of both an AnonymousAuthenticationToken together with a
// BASIC authentication request header should indicate reauthentication using the
// BASIC protocol is desirable. This behaviour is also consistent with that
// provided by form and digest, both of which force re-authentication if the
// respective header is detected (and in doing so replace/ any existing
// AnonymousAuthenticationToken). See SEC-610.
return (existingAuth instanceof AnonymousAuthenticationToken);
}
protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
Authentication authResult) throws IOException {
}
protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) throws IOException {
}
protected AuthenticationEntryPoint getAuthenticationEntryPoint() {
return this.authenticationEntryPoint;
}
protected AuthenticationManager getAuthenticationManager() {
return this.authenticationManager;
}
protected boolean isIgnoreFailure() {
return this.ignoreFailure;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
public void setAuthenticationDetailsSource(
AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
this.authenticationConverter.setAuthenticationDetailsSource(authenticationDetailsSource);
}
public void setRememberMeServices(RememberMeServices rememberMeServices) {
Assert.notNull(rememberMeServices, "rememberMeServices cannot be null");
this.rememberMeServices = rememberMeServices;
}
public void setCredentialsCharset(String credentialsCharset) {
Assert.hasText(credentialsCharset, "credentialsCharset cannot be null or empty");
this.credentialsCharset = credentialsCharset;
this.authenticationConverter.setCredentialsCharset(Charset.forName(credentialsCharset));
}
protected String getCredentialsCharset(HttpServletRequest httpRequest) {
return this.credentialsCharset;
}
}
| 12,041 | 42.948905 | 111 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverter.java | /*
* Copyright 2002-2022 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.web.authentication.www;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Converts from a HttpServletRequest to {@link UsernamePasswordAuthenticationToken} that
* can be authenticated. Null authentication possible if there was no Authorization header
* with Basic authentication scheme.
*
* @author Sergey Bespalov
* @since 5.2.0
*/
public class BasicAuthenticationConverter implements AuthenticationConverter {
public static final String AUTHENTICATION_SCHEME_BASIC = "Basic";
private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource;
private Charset credentialsCharset = StandardCharsets.UTF_8;
public BasicAuthenticationConverter() {
this(new WebAuthenticationDetailsSource());
}
public BasicAuthenticationConverter(
AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
this.authenticationDetailsSource = authenticationDetailsSource;
}
public Charset getCredentialsCharset() {
return this.credentialsCharset;
}
public void setCredentialsCharset(Charset credentialsCharset) {
this.credentialsCharset = credentialsCharset;
}
public AuthenticationDetailsSource<HttpServletRequest, ?> getAuthenticationDetailsSource() {
return this.authenticationDetailsSource;
}
public void setAuthenticationDetailsSource(
AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required");
this.authenticationDetailsSource = authenticationDetailsSource;
}
@Override
public UsernamePasswordAuthenticationToken convert(HttpServletRequest request) {
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (header == null) {
return null;
}
header = header.trim();
if (!StringUtils.startsWithIgnoreCase(header, AUTHENTICATION_SCHEME_BASIC)) {
return null;
}
if (header.equalsIgnoreCase(AUTHENTICATION_SCHEME_BASIC)) {
throw new BadCredentialsException("Empty basic authentication token");
}
byte[] base64Token = header.substring(6).getBytes(StandardCharsets.UTF_8);
byte[] decoded = decode(base64Token);
String token = new String(decoded, getCredentialsCharset(request));
int delim = token.indexOf(":");
if (delim == -1) {
throw new BadCredentialsException("Invalid basic authentication token");
}
UsernamePasswordAuthenticationToken result = UsernamePasswordAuthenticationToken
.unauthenticated(token.substring(0, delim), token.substring(delim + 1));
result.setDetails(this.authenticationDetailsSource.buildDetails(request));
return result;
}
private byte[] decode(byte[] base64Token) {
try {
return Base64.getDecoder().decode(base64Token);
}
catch (IllegalArgumentException ex) {
throw new BadCredentialsException("Failed to decode basic authentication token");
}
}
protected Charset getCredentialsCharset(HttpServletRequest request) {
return getCredentialsCharset();
}
}
| 4,258 | 35.401709 | 93 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/www/DigestAuthUtils.java | /*
* Copyright 2002-2016 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.web.authentication.www;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
final class DigestAuthUtils {
private static final String[] EMPTY_STRING_ARRAY = new String[0];
private DigestAuthUtils() {
}
static String encodePasswordInA1Format(String username, String realm, String password) {
String a1 = username + ":" + realm + ":" + password;
return md5Hex(a1);
}
static String[] splitIgnoringQuotes(String str, char separatorChar) {
if (str == null) {
return null;
}
int len = str.length();
if (len == 0) {
return EMPTY_STRING_ARRAY;
}
List<String> list = new ArrayList<>();
int i = 0;
int start = 0;
boolean match = false;
while (i < len) {
if (str.charAt(i) == '"') {
i++;
while (i < len) {
if (str.charAt(i) == '"') {
i++;
break;
}
i++;
}
match = true;
continue;
}
if (str.charAt(i) == separatorChar) {
if (match) {
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
match = true;
i++;
}
if (match) {
list.add(str.substring(start, i));
}
return list.toArray(new String[0]);
}
/**
* Computes the <code>response</code> portion of a Digest authentication header. Both
* the server and user agent should compute the <code>response</code> independently.
* Provided as a static method to simplify the coding of user agents.
* @param passwordAlreadyEncoded true if the password argument is already encoded in
* the correct format. False if it is plain text.
* @param username the user's login name.
* @param realm the name of the realm.
* @param password the user's password in plaintext or ready-encoded.
* @param httpMethod the HTTP request method (GET, POST etc.)
* @param uri the request URI.
* @param qop the qop directive, or null if not set.
* @param nonce the nonce supplied by the server
* @param nc the "nonce-count" as defined in RFC 2617.
* @param cnonce opaque string supplied by the client when qop is set.
* @return the MD5 of the digest authentication response, encoded in hex
* @throws IllegalArgumentException if the supplied qop value is unsupported.
*/
static String generateDigest(boolean passwordAlreadyEncoded, String username, String realm, String password,
String httpMethod, String uri, String qop, String nonce, String nc, String cnonce)
throws IllegalArgumentException {
String a2 = httpMethod + ":" + uri;
String a1Md5 = (!passwordAlreadyEncoded) ? DigestAuthUtils.encodePasswordInA1Format(username, realm, password)
: password;
String a2Md5 = md5Hex(a2);
if (qop == null) {
// as per RFC 2069 compliant clients (also reaffirmed by RFC 2617)
return md5Hex(a1Md5 + ":" + nonce + ":" + a2Md5);
}
if ("auth".equals(qop)) {
// As per RFC 2617 compliant clients
return md5Hex(a1Md5 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + a2Md5);
}
throw new IllegalArgumentException("This method does not support a qop: '" + qop + "'");
}
/**
* Takes an array of <code>String</code>s, and for each element removes any instances
* of <code>removeCharacter</code>, and splits the element based on the
* <code>delimiter</code>. A <code>Map</code> is then generated, with the left of the
* delimiter providing the key, and the right of the delimiter providing the value.
* <p>
* Will trim both the key and value before adding to the <code>Map</code>.
* </p>
* @param array the array to process
* @param delimiter to split each element using (typically the equals symbol)
* @param removeCharacters one or more characters to remove from each element prior to
* attempting the split operation (typically the quotation mark symbol) or
* <code>null</code> if no removal should occur
* @return a <code>Map</code> representing the array contents, or <code>null</code> if
* the array to process was null or empty
*/
static Map<String, String> splitEachArrayElementAndCreateMap(String[] array, String delimiter,
String removeCharacters) {
if ((array == null) || (array.length == 0)) {
return null;
}
Map<String, String> map = new HashMap<>();
for (String s : array) {
String postRemove = (removeCharacters != null) ? StringUtils.replace(s, removeCharacters, "") : s;
String[] splitThisArrayElement = split(postRemove, delimiter);
if (splitThisArrayElement == null) {
continue;
}
map.put(splitThisArrayElement[0].trim(), splitThisArrayElement[1].trim());
}
return map;
}
/**
* Splits a <code>String</code> at the first instance of the delimiter.
* <p>
* Does not include the delimiter in the response.
* </p>
* @param toSplit the string to split
* @param delimiter to split the string up with
* @return a two element array with index 0 being before the delimiter, and index 1
* being after the delimiter (neither element includes the delimiter)
* @throws IllegalArgumentException if an argument was invalid
*/
static String[] split(String toSplit, String delimiter) {
Assert.hasLength(toSplit, "Cannot split a null or empty string");
Assert.hasLength(delimiter, "Cannot use a null or empty delimiter to split a string");
Assert.isTrue(delimiter.length() == 1, "Delimiter can only be one character in length");
int offset = toSplit.indexOf(delimiter);
if (offset < 0) {
return null;
}
String beforeDelimiter = toSplit.substring(0, offset);
String afterDelimiter = toSplit.substring(offset + 1);
return new String[] { beforeDelimiter, afterDelimiter };
}
static String md5Hex(String data) {
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
return new String(Hex.encode(digest.digest(data.getBytes())));
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("No MD5 algorithm available!");
}
}
}
| 6,752 | 34.730159 | 112 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/www/NonceExpiredException.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.web.authentication.www;
import org.springframework.security.core.AuthenticationException;
/**
* Thrown if an authentication request is rejected because the digest nonce has expired.
*
* @author Ben Alex
*/
public class NonceExpiredException extends AuthenticationException {
/**
* Constructs a <code>NonceExpiredException</code> with the specified message.
* @param msg the detail message
*/
public NonceExpiredException(String msg) {
super(msg);
}
/**
* Constructs a <code>NonceExpiredException</code> with the specified message and root
* cause.
* @param msg the detail message
* @param cause root cause
*/
public NonceExpiredException(String msg, Throwable cause) {
super(msg, cause);
}
}
| 1,391 | 28.617021 | 88 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/www/DigestAuthenticationEntryPoint.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.web.authentication.www;
import java.io.IOException;
import java.util.Base64;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.Ordered;
import org.springframework.core.log.LogMessage;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.util.Assert;
/**
* Used by the <code>SecurityEnforcementFilter</code> to commence authentication via the
* {@link DigestAuthenticationFilter}.
* <p>
* The nonce sent back to the user agent will be valid for the period indicated by
* {@link #setNonceValiditySeconds(int)}. By default this is 300 seconds. Shorter times
* should be used if replay attacks are a major concern. Larger values can be used if
* performance is a greater concern. This class correctly presents the
* <code>stale=true</code> header when the nonce has expired, so properly implemented user
* agents will automatically renegotiate with a new nonce value (i.e. without presenting a
* new password dialog box to the user).
*
* @author Ben Alex
*/
public class DigestAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean, Ordered {
private static final Log logger = LogFactory.getLog(DigestAuthenticationEntryPoint.class);
private String key;
private String realmName;
private int nonceValiditySeconds = 300;
private int order = Integer.MAX_VALUE; // ~ default
@Override
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
@Override
public void afterPropertiesSet() {
Assert.hasLength(this.realmName, "realmName must be specified");
Assert.hasLength(this.key, "key must be specified");
}
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
// compute a nonce (do not use remote IP address due to proxy farms) format of
// nonce is: base64(expirationTime + ":" + md5Hex(expirationTime + ":" + key))
long expiryTime = System.currentTimeMillis() + (this.nonceValiditySeconds * 1000);
String signatureValue = DigestAuthUtils.md5Hex(expiryTime + ":" + this.key);
String nonceValue = expiryTime + ":" + signatureValue;
String nonceValueBase64 = new String(Base64.getEncoder().encode(nonceValue.getBytes()));
// qop is quality of protection, as defined by RFC 2617. We do not use opaque due
// to IE violation of RFC 2617 in not representing opaque on subsequent requests
// in same session.
String authenticateHeader = "Digest realm=\"" + this.realmName + "\", " + "qop=\"auth\", nonce=\""
+ nonceValueBase64 + "\"";
if (authException instanceof NonceExpiredException) {
authenticateHeader = authenticateHeader + ", stale=\"true\"";
}
logger.debug(LogMessage.format("WWW-Authenticate header sent to user agent: %s", authenticateHeader));
response.addHeader("WWW-Authenticate", authenticateHeader);
response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
}
public String getKey() {
return this.key;
}
public int getNonceValiditySeconds() {
return this.nonceValiditySeconds;
}
public String getRealmName() {
return this.realmName;
}
public void setKey(String key) {
this.key = key;
}
public void setNonceValiditySeconds(int nonceValiditySeconds) {
this.nonceValiditySeconds = nonceValiditySeconds;
}
public void setRealmName(String realmName) {
this.realmName = realmName;
}
}
| 4,444 | 35.138211 | 108 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationEntryPoint.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.web.authentication.www;
import java.io.IOException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.util.Assert;
/**
* Used by the <code>ExceptionTranslationFilter</code> to commence authentication via the
* {@link BasicAuthenticationFilter}.
* <p>
* Once a user agent is authenticated using BASIC authentication, logout requires that the
* browser be closed or an unauthorized (401) header be sent. The simplest way of
* achieving the latter is to call the
* {@link #commence(HttpServletRequest, HttpServletResponse, AuthenticationException)}
* method below. This will indicate to the browser its credentials are no longer
* authorized, causing it to prompt the user to login again.
*
* @author Ben Alex
*/
public class BasicAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean {
private String realmName;
@Override
public void afterPropertiesSet() {
Assert.hasText(this.realmName, "realmName must be specified");
}
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.addHeader("WWW-Authenticate", "Basic realm=\"" + this.realmName + "\"");
response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
}
public String getRealmName() {
return this.realmName;
}
public void setRealmName(String realmName) {
this.realmName = realmName;
}
}
| 2,426 | 34.691176 | 98 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilter.java | /*
* Copyright 2004, 2005, 2006, 2009 Acegi Technology Pty Limited
*
* 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.web.authentication.www;
import java.io.IOException;
import java.util.Base64;
import java.util.Map;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.core.log.LogMessage;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.cache.NullUserCache;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
/**
* Processes a HTTP request's Digest authorization headers, putting the result into the
* <code>SecurityContextHolder</code>.
* <p>
* For a detailed background on what this filter is designed to process, refer to
* <a href="https://www.ietf.org/rfc/rfc2617.txt">RFC 2617</a> (which superseded RFC 2069,
* although this filter support clients that implement either RFC 2617 or RFC 2069).
* <p>
* This filter can be used to provide Digest authentication services to both remoting
* protocol clients (such as Hessian and SOAP) as well as standard user agents (such as
* Internet Explorer and FireFox).
* <p>
* This Digest implementation has been designed to avoid needing to store session state
* between invocations. All session management information is stored in the "nonce" that
* is sent to the client by the {@link DigestAuthenticationEntryPoint}.
* <p>
* If authentication is successful, the resulting
* {@link org.springframework.security.core.Authentication Authentication} object will be
* placed into the <code>SecurityContextHolder</code>.
* <p>
* If authentication fails, an
* {@link org.springframework.security.web.AuthenticationEntryPoint
* AuthenticationEntryPoint} implementation is called. This must always be
* {@link DigestAuthenticationEntryPoint}, which will prompt the user to authenticate
* again via Digest authentication.
* <p>
* Note there are limitations to Digest authentication, although it is a more
* comprehensive and secure solution than Basic authentication. Please see RFC 2617
* section 4 for a full discussion on the advantages of Digest authentication over Basic
* authentication, including commentary on the limitations that it still imposes.
*
* @author Ben Alex
* @author Luke Taylor
* @since 1.0.0
*/
public class DigestAuthenticationFilter extends GenericFilterBean implements MessageSourceAware {
private static final Log logger = LogFactory.getLog(DigestAuthenticationFilter.class);
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
private DigestAuthenticationEntryPoint authenticationEntryPoint;
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private UserCache userCache = new NullUserCache();
private UserDetailsService userDetailsService;
private boolean passwordAlreadyEncoded = false;
private boolean createAuthenticatedToken = false;
private SecurityContextRepository securityContextRepository = new RequestAttributeSecurityContextRepository();
@Override
public void afterPropertiesSet() {
Assert.notNull(this.userDetailsService, "A UserDetailsService is required");
Assert.notNull(this.authenticationEntryPoint, "A DigestAuthenticationEntryPoint is required");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
}
private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Digest ")) {
chain.doFilter(request, response);
return;
}
logger.debug(LogMessage.format("Digest Authorization header received from user agent: %s", header));
DigestData digestAuth = new DigestData(header);
try {
digestAuth.validateAndDecode(this.authenticationEntryPoint.getKey(),
this.authenticationEntryPoint.getRealmName());
}
catch (BadCredentialsException ex) {
fail(request, response, ex);
return;
}
// Lookup password for presented username. N.B. DAO-provided password MUST be
// clear text - not encoded/salted (unless this instance's passwordAlreadyEncoded
// property is 'false')
boolean cacheWasUsed = true;
UserDetails user = this.userCache.getUserFromCache(digestAuth.getUsername());
String serverDigestMd5;
try {
if (user == null) {
cacheWasUsed = false;
user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());
if (user == null) {
throw new AuthenticationServiceException(
"AuthenticationDao returned null, which is an interface contract violation");
}
this.userCache.putUserInCache(user);
}
serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
// If digest is incorrect, try refreshing from backend and recomputing
if (!serverDigestMd5.equals(digestAuth.getResponse()) && cacheWasUsed) {
logger.debug("Digest comparison failure; trying to refresh user from DAO in case password had changed");
user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());
this.userCache.putUserInCache(user);
serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
}
}
catch (UsernameNotFoundException ex) {
String message = this.messages.getMessage("DigestAuthenticationFilter.usernameNotFound",
new Object[] { digestAuth.getUsername() }, "Username {0} not found");
fail(request, response, new BadCredentialsException(message));
return;
}
// If digest is still incorrect, definitely reject authentication attempt
if (!serverDigestMd5.equals(digestAuth.getResponse())) {
logger.debug(LogMessage.format(
"Expected response: '%s' but received: '%s'; is AuthenticationDao returning clear text passwords?",
serverDigestMd5, digestAuth.getResponse()));
String message = this.messages.getMessage("DigestAuthenticationFilter.incorrectResponse",
"Incorrect response");
fail(request, response, new BadCredentialsException(message));
return;
}
// To get this far, the digest must have been valid
// Check the nonce has not expired
// We do this last so we can direct the user agent its nonce is stale
// but the request was otherwise appearing to be valid
if (digestAuth.isNonceExpired()) {
String message = this.messages.getMessage("DigestAuthenticationFilter.nonceExpired",
"Nonce has expired/timed out");
fail(request, response, new NonceExpiredException(message));
return;
}
logger.debug(LogMessage.format("Authentication success for user: '%s' with response: '%s'",
digestAuth.getUsername(), digestAuth.getResponse()));
Authentication authentication = createSuccessfulAuthentication(request, user);
SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
context.setAuthentication(authentication);
this.securityContextHolderStrategy.setContext(context);
this.securityContextRepository.saveContext(context, request, response);
chain.doFilter(request, response);
}
private Authentication createSuccessfulAuthentication(HttpServletRequest request, UserDetails user) {
UsernamePasswordAuthenticationToken authRequest = getAuthRequest(user);
authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
return authRequest;
}
private UsernamePasswordAuthenticationToken getAuthRequest(UserDetails user) {
if (this.createAuthenticatedToken) {
return UsernamePasswordAuthenticationToken.authenticated(user, user.getPassword(), user.getAuthorities());
}
return UsernamePasswordAuthenticationToken.unauthenticated(user, user.getPassword());
}
private void fail(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed)
throws IOException, ServletException {
SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
this.securityContextHolderStrategy.setContext(context);
logger.debug(failed);
this.authenticationEntryPoint.commence(request, response, failed);
}
protected final DigestAuthenticationEntryPoint getAuthenticationEntryPoint() {
return this.authenticationEntryPoint;
}
public UserCache getUserCache() {
return this.userCache;
}
public UserDetailsService getUserDetailsService() {
return this.userDetailsService;
}
public void setAuthenticationDetailsSource(
AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required");
this.authenticationDetailsSource = authenticationDetailsSource;
}
public void setAuthenticationEntryPoint(DigestAuthenticationEntryPoint authenticationEntryPoint) {
this.authenticationEntryPoint = authenticationEntryPoint;
}
@Override
public void setMessageSource(MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
public void setPasswordAlreadyEncoded(boolean passwordAlreadyEncoded) {
this.passwordAlreadyEncoded = passwordAlreadyEncoded;
}
public void setUserCache(UserCache userCache) {
this.userCache = userCache;
}
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
/**
* If you set this property, the Authentication object, which is created after the
* successful digest authentication will be marked as <b>authenticated</b> and filled
* with the authorities loaded by the UserDetailsService. It therefore will not be
* re-authenticated by your AuthenticationProvider. This means, that only the password
* of the user is checked, but not the flags like isEnabled() or
* isAccountNonExpired(). You will save some time by enabling this flag, as otherwise
* your UserDetailsService will be called twice. A more secure option would be to
* introduce a cache around your UserDetailsService, but if you don't use these flags,
* you can also safely enable this option.
* @param createAuthenticatedToken default is false
*/
public void setCreateAuthenticatedToken(boolean createAuthenticatedToken) {
this.createAuthenticatedToken = createAuthenticatedToken;
}
/**
* Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on
* authentication success. The default action is not to save the
* {@link SecurityContext}.
* @param securityContextRepository the {@link SecurityContextRepository} to use.
* Cannot be null.
*/
public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) {
Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
this.securityContextRepository = securityContextRepository;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
private class DigestData {
private final String username;
private final String realm;
private final String nonce;
private final String uri;
private final String response;
private final String qop;
private final String nc;
private final String cnonce;
private final String section212response;
private long nonceExpiryTime;
DigestData(String header) {
this.section212response = header.substring(7);
String[] headerEntries = DigestAuthUtils.splitIgnoringQuotes(this.section212response, ',');
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
this.username = headerMap.get("username");
this.realm = headerMap.get("realm");
this.nonce = headerMap.get("nonce");
this.uri = headerMap.get("uri");
this.response = headerMap.get("response");
this.qop = headerMap.get("qop"); // RFC 2617 extension
this.nc = headerMap.get("nc"); // RFC 2617 extension
this.cnonce = headerMap.get("cnonce"); // RFC 2617 extension
logger.debug(
LogMessage.format("Extracted username: '%s'; realm: '%s'; nonce: '%s'; uri: '%s'; response: '%s'",
this.username, this.realm, this.nonce, this.uri, this.response));
}
void validateAndDecode(String entryPointKey, String expectedRealm) throws BadCredentialsException {
// Check all required parameters were supplied (ie RFC 2069)
if ((this.username == null) || (this.realm == null) || (this.nonce == null) || (this.uri == null)
|| (this.response == null)) {
throw new BadCredentialsException(DigestAuthenticationFilter.this.messages.getMessage(
"DigestAuthenticationFilter.missingMandatory", new Object[] { this.section212response },
"Missing mandatory digest value; received header {0}"));
}
// Check all required parameters for an "auth" qop were supplied (ie RFC 2617)
if ("auth".equals(this.qop)) {
if ((this.nc == null) || (this.cnonce == null)) {
logger.debug(LogMessage.format("extracted nc: '%s'; cnonce: '%s'", this.nc, this.cnonce));
throw new BadCredentialsException(DigestAuthenticationFilter.this.messages.getMessage(
"DigestAuthenticationFilter.missingAuth", new Object[] { this.section212response },
"Missing mandatory digest value; received header {0}"));
}
}
// Check realm name equals what we expected
if (!expectedRealm.equals(this.realm)) {
throw new BadCredentialsException(DigestAuthenticationFilter.this.messages.getMessage(
"DigestAuthenticationFilter.incorrectRealm", new Object[] { this.realm, expectedRealm },
"Response realm name '{0}' does not match system realm name of '{1}'"));
}
// Check nonce was Base64 encoded (as sent by DigestAuthenticationEntryPoint)
final byte[] nonceBytes;
try {
nonceBytes = Base64.getDecoder().decode(this.nonce.getBytes());
}
catch (IllegalArgumentException ex) {
throw new BadCredentialsException(
DigestAuthenticationFilter.this.messages.getMessage("DigestAuthenticationFilter.nonceEncoding",
new Object[] { this.nonce }, "Nonce is not encoded in Base64; received nonce {0}"));
}
// Decode nonce from Base64 format of nonce is: base64(expirationTime + ":" +
// md5Hex(expirationTime + ":" + key))
String nonceAsPlainText = new String(nonceBytes);
String[] nonceTokens = StringUtils.delimitedListToStringArray(nonceAsPlainText, ":");
if (nonceTokens.length != 2) {
throw new BadCredentialsException(DigestAuthenticationFilter.this.messages.getMessage(
"DigestAuthenticationFilter.nonceNotTwoTokens", new Object[] { nonceAsPlainText },
"Nonce should have yielded two tokens but was {0}"));
}
// Extract expiry time from nonce
try {
this.nonceExpiryTime = Long.valueOf(nonceTokens[0]);
}
catch (NumberFormatException nfe) {
throw new BadCredentialsException(DigestAuthenticationFilter.this.messages.getMessage(
"DigestAuthenticationFilter.nonceNotNumeric", new Object[] { nonceAsPlainText },
"Nonce token should have yielded a numeric first token, but was {0}"));
}
// Check signature of nonce matches this expiry time
String expectedNonceSignature = DigestAuthUtils.md5Hex(this.nonceExpiryTime + ":" + entryPointKey);
if (!expectedNonceSignature.equals(nonceTokens[1])) {
throw new BadCredentialsException(DigestAuthenticationFilter.this.messages.getMessage(
"DigestAuthenticationFilter.nonceCompromised", new Object[] { nonceAsPlainText },
"Nonce token compromised {0}"));
}
}
String calculateServerDigest(String password, String httpMethod) {
// Compute the expected response-digest (will be in hex form). Don't catch
// IllegalArgumentException (already checked validity)
return DigestAuthUtils.generateDigest(DigestAuthenticationFilter.this.passwordAlreadyEncoded, this.username,
this.realm, password, httpMethod, this.uri, this.qop, this.nonce, this.nc, this.cnonce);
}
boolean isNonceExpired() {
long now = System.currentTimeMillis();
return this.nonceExpiryTime < now;
}
String getUsername() {
return this.username;
}
String getResponse() {
return this.response;
}
}
}
| 19,056 | 43.629977 | 127 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/session/SessionAuthenticationStrategy.java | /*
* Copyright 2002-2016 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.web.authentication.session;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
/**
* Allows pluggable support for HttpSession-related behaviour when an authentication
* occurs.
* <p>
* Typical use would be to make sure a session exists or to change the session Id to guard
* against session-fixation attacks.
*
* @author Luke Taylor
* @since
*/
public interface SessionAuthenticationStrategy {
/**
* Performs Http session-related functionality when a new authentication occurs.
* @throws SessionAuthenticationException if it is decided that the authentication is
* not allowed for the session. This will typically be because the user has too many
* sessions open at once.
*/
void onAuthentication(Authentication authentication, HttpServletRequest request, HttpServletResponse response)
throws SessionAuthenticationException;
}
| 1,619 | 34.217391 | 111 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/session/package-info.java | /*
* Copyright 2002-2016 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.
*/
/**
* Strategy interface and implementations for handling session-related behaviour for a
* newly authenticated user.
* <p>
* Comes with support for:
* <ul>
* <li>Protection against session-fixation attacks</li>
* <li>Controlling the number of sessions an authenticated user can have open</li>
* </ul>
*/
package org.springframework.security.web.authentication.session;
| 1,002 | 34.821429 | 86 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/session/NullAuthenticatedSessionStrategy.java | /*
* Copyright 2002-2016 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.web.authentication.session;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
/**
* @author Luke Taylor
* @since 3.0
*/
public final class NullAuthenticatedSessionStrategy implements SessionAuthenticationStrategy {
@Override
public void onAuthentication(Authentication authentication, HttpServletRequest request,
HttpServletResponse response) {
}
}
| 1,127 | 30.333333 | 94 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/session/ChangeSessionIdAuthenticationStrategy.java | /*
* Copyright 2002-2013 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.web.authentication.session;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
/**
* Uses {@code HttpServletRequest.changeSessionId()} to protect against session fixation
* attacks. This is the default implementation.
*
* @author Rob Winch
* @since 3.2
*/
public final class ChangeSessionIdAuthenticationStrategy extends AbstractSessionFixationProtectionStrategy {
@Override
HttpSession applySessionFixation(HttpServletRequest request) {
request.changeSessionId();
return request.getSession();
}
}
| 1,213 | 30.947368 | 108 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategy.java | /*
* Copyright 2002-2013 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.web.authentication.session;
import java.util.List;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogMessage;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
/**
* A {@link SessionAuthenticationStrategy} that accepts multiple
* {@link SessionAuthenticationStrategy} implementations to delegate to. Each
* {@link SessionAuthenticationStrategy} is invoked in turn. The invocations are short
* circuited if any exception, (i.e. SessionAuthenticationException) is thrown.
*
* <p>
* Typical usage would include having the following delegates (in this order)
* </p>
*
* <ul>
* <li>{@link ConcurrentSessionControlAuthenticationStrategy} - verifies that a user is
* allowed to authenticate (i.e. they have not already logged into the application.</li>
* <li>{@link SessionFixationProtectionStrategy} - If session fixation is desired,
* {@link SessionFixationProtectionStrategy} should be after
* {@link ConcurrentSessionControlAuthenticationStrategy} to prevent unnecessary
* {@link HttpSession} creation if the
* {@link ConcurrentSessionControlAuthenticationStrategy} rejects authentication.</li>
* <li>{@link RegisterSessionAuthenticationStrategy} - It is important this is after
* {@link SessionFixationProtectionStrategy} so that the correct session is registered.
* </li>
* </ul>
*
* @author Rob Winch
* @since 3.2
*/
public class CompositeSessionAuthenticationStrategy implements SessionAuthenticationStrategy {
private final Log logger = LogFactory.getLog(getClass());
private final List<SessionAuthenticationStrategy> delegateStrategies;
public CompositeSessionAuthenticationStrategy(List<SessionAuthenticationStrategy> delegateStrategies) {
Assert.notEmpty(delegateStrategies, "delegateStrategies cannot be null or empty");
for (SessionAuthenticationStrategy strategy : delegateStrategies) {
Assert.notNull(strategy, () -> "delegateStrategies cannot contain null entires. Got " + delegateStrategies);
}
this.delegateStrategies = delegateStrategies;
}
@Override
public void onAuthentication(Authentication authentication, HttpServletRequest request,
HttpServletResponse response) throws SessionAuthenticationException {
int currentPosition = 0;
int size = this.delegateStrategies.size();
for (SessionAuthenticationStrategy delegate : this.delegateStrategies) {
if (this.logger.isTraceEnabled()) {
this.logger.trace(LogMessage.format("Preparing session with %s (%d/%d)",
delegate.getClass().getSimpleName(), ++currentPosition, size));
}
delegate.onAuthentication(authentication, request, response);
}
}
@Override
public String toString() {
return getClass().getName() + " [delegateStrategies = " + this.delegateStrategies + "]";
}
}
| 3,641 | 39.021978 | 111 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/session/ConcurrentSessionControlAuthenticationStrategy.java | /*
* Copyright 2002-2020 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.web.authentication.session;
import java.util.Comparator;
import java.util.List;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.session.ConcurrentSessionFilter;
import org.springframework.security.web.session.SessionManagementFilter;
import org.springframework.util.Assert;
/**
* Strategy which handles concurrent session-control.
*
* <p>
* When invoked following an authentication, it will check whether the user in question
* should be allowed to proceed, by comparing the number of sessions they already have
* active with the configured <tt>maximumSessions</tt> value. The {@link SessionRegistry}
* is used as the source of data on authenticated users and session data.
* </p>
* <p>
* If a user has reached the maximum number of permitted sessions, the behaviour depends
* on the <tt>exceptionIfMaxExceeded</tt> property. The default behaviour is to expire any
* sessions that exceed the maximum number of permitted sessions, starting with the least
* recently used sessions. The expired sessions will be invalidated by the
* {@link ConcurrentSessionFilter} if accessed again. If <tt>exceptionIfMaxExceeded</tt>
* is set to <tt>true</tt>, however, the user will be prevented from starting a new
* authenticated session.
* </p>
* <p>
* This strategy can be injected into both the {@link SessionManagementFilter} and
* instances of {@link AbstractAuthenticationProcessingFilter} (typically
* {@link UsernamePasswordAuthenticationFilter}), but is typically combined with
* {@link RegisterSessionAuthenticationStrategy} using
* {@link CompositeSessionAuthenticationStrategy}.
* </p>
*
* @author Luke Taylor
* @author Rob Winch
* @since 3.2
* @see CompositeSessionAuthenticationStrategy
*/
public class ConcurrentSessionControlAuthenticationStrategy
implements MessageSourceAware, SessionAuthenticationStrategy {
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private final SessionRegistry sessionRegistry;
private boolean exceptionIfMaximumExceeded = false;
private int maximumSessions = 1;
/**
* @param sessionRegistry the session registry which should be updated when the
* authenticated session is changed.
*/
public ConcurrentSessionControlAuthenticationStrategy(SessionRegistry sessionRegistry) {
Assert.notNull(sessionRegistry, "The sessionRegistry cannot be null");
this.sessionRegistry = sessionRegistry;
}
/**
* In addition to the steps from the superclass, the sessionRegistry will be updated
* with the new session information.
*/
@Override
public void onAuthentication(Authentication authentication, HttpServletRequest request,
HttpServletResponse response) {
int allowedSessions = getMaximumSessionsForThisUser(authentication);
if (allowedSessions == -1) {
// We permit unlimited logins
return;
}
List<SessionInformation> sessions = this.sessionRegistry.getAllSessions(authentication.getPrincipal(), false);
int sessionCount = sessions.size();
if (sessionCount < allowedSessions) {
// They haven't got too many login sessions running at present
return;
}
if (sessionCount == allowedSessions) {
HttpSession session = request.getSession(false);
if (session != null) {
// Only permit it though if this request is associated with one of the
// already registered sessions
for (SessionInformation si : sessions) {
if (si.getSessionId().equals(session.getId())) {
return;
}
}
}
// If the session is null, a new one will be created by the parent class,
// exceeding the allowed number
}
allowableSessionsExceeded(sessions, allowedSessions, this.sessionRegistry);
}
/**
* Method intended for use by subclasses to override the maximum number of sessions
* that are permitted for a particular authentication. The default implementation
* simply returns the <code>maximumSessions</code> value for the bean.
* @param authentication to determine the maximum sessions for
* @return either -1 meaning unlimited, or a positive integer to limit (never zero)
*/
protected int getMaximumSessionsForThisUser(Authentication authentication) {
return this.maximumSessions;
}
/**
* Allows subclasses to customise behaviour when too many sessions are detected.
* @param sessions either <code>null</code> or all unexpired sessions associated with
* the principal
* @param allowableSessions the number of concurrent sessions the user is allowed to
* have
* @param registry an instance of the <code>SessionRegistry</code> for subclass use
*
*/
protected void allowableSessionsExceeded(List<SessionInformation> sessions, int allowableSessions,
SessionRegistry registry) throws SessionAuthenticationException {
if (this.exceptionIfMaximumExceeded || (sessions == null)) {
throw new SessionAuthenticationException(
this.messages.getMessage("ConcurrentSessionControlAuthenticationStrategy.exceededAllowed",
new Object[] { allowableSessions }, "Maximum sessions of {0} for this principal exceeded"));
}
// Determine least recently used sessions, and mark them for invalidation
sessions.sort(Comparator.comparing(SessionInformation::getLastRequest));
int maximumSessionsExceededBy = sessions.size() - allowableSessions + 1;
List<SessionInformation> sessionsToBeExpired = sessions.subList(0, maximumSessionsExceededBy);
for (SessionInformation session : sessionsToBeExpired) {
session.expireNow();
}
}
/**
* Sets the <tt>exceptionIfMaximumExceeded</tt> property, which determines whether the
* user should be prevented from opening more sessions than allowed. If set to
* <tt>true</tt>, a <tt>SessionAuthenticationException</tt> will be raised which means
* the user authenticating will be prevented from authenticating. if set to
* <tt>false</tt>, the user that has already authenticated will be forcibly logged
* out.
* @param exceptionIfMaximumExceeded defaults to <tt>false</tt>.
*/
public void setExceptionIfMaximumExceeded(boolean exceptionIfMaximumExceeded) {
this.exceptionIfMaximumExceeded = exceptionIfMaximumExceeded;
}
/**
* Sets the <tt>maxSessions</tt> property. The default value is 1. Use -1 for
* unlimited sessions.
* @param maximumSessions the maximimum number of permitted sessions a user can have
* open simultaneously.
*/
public void setMaximumSessions(int maximumSessions) {
Assert.isTrue(maximumSessions != 0,
"MaximumLogins must be either -1 to allow unlimited logins, or a positive integer to specify a maximum");
this.maximumSessions = maximumSessions;
}
/**
* Sets the {@link MessageSource} used for reporting errors back to the user when the
* user has exceeded the maximum number of authentications.
*/
@Override
public void setMessageSource(MessageSource messageSource) {
Assert.notNull(messageSource, "messageSource cannot be null");
this.messages = new MessageSourceAccessor(messageSource);
}
}
| 8,342 | 41.350254 | 112 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/session/SessionFixationProtectionEvent.java | /*
* Copyright 2002-2013 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.web.authentication.session;
import org.springframework.security.authentication.event.AbstractAuthenticationEvent;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
/**
* Indicates a session ID was changed for the purposes of session fixation protection.
*
* @author Nicholas Williams
* @since 3.2
* @see SessionFixationProtectionStrategy
*/
public class SessionFixationProtectionEvent extends AbstractAuthenticationEvent {
private final String oldSessionId;
private final String newSessionId;
/**
* Constructs a new session fixation protection event.
* @param authentication The authentication object
* @param oldSessionId The old session ID before it was changed
* @param newSessionId The new session ID after it was changed
*/
public SessionFixationProtectionEvent(Authentication authentication, String oldSessionId, String newSessionId) {
super(authentication);
Assert.hasLength(oldSessionId, "oldSessionId must have length");
Assert.hasLength(newSessionId, "newSessionId must have length");
this.oldSessionId = oldSessionId;
this.newSessionId = newSessionId;
}
/**
* Getter for the session ID before it was changed.
* @return the old session ID.
*/
public String getOldSessionId() {
return this.oldSessionId;
}
/**
* Getter for the session ID after it was changed.
* @return the new session ID.
*/
public String getNewSessionId() {
return this.newSessionId;
}
}
| 2,134 | 30.865672 | 113 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/session/AbstractSessionFixationProtectionStrategy.java | /*
* Copyright 2002-2013 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.web.authentication.session;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.core.log.LogMessage;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
import org.springframework.web.util.WebUtils;
/**
* A base class for performing session fixation protection.
*
* @author Rob Winch
* @since 3.2
*/
public abstract class AbstractSessionFixationProtectionStrategy
implements SessionAuthenticationStrategy, ApplicationEventPublisherAware {
protected final Log logger = LogFactory.getLog(this.getClass());
/**
* Used for publishing events related to session fixation protection, such as
* {@link SessionFixationProtectionEvent}.
*/
private ApplicationEventPublisher applicationEventPublisher = new NullEventPublisher();
/**
* If set to {@code true}, a session will always be created, even if one didn't exist
* at the start of the request. Defaults to {@code false}.
*/
private boolean alwaysCreateSession;
AbstractSessionFixationProtectionStrategy() {
}
/**
* Called when a user is newly authenticated.
* <p>
* If a session already exists, and matches the session Id from the client, a new
* session will be created, and the session attributes copied to it (if
* {@code migrateSessionAttributes} is set). If the client's requested session Id is
* invalid, nothing will be done, since there is no need to change the session Id if
* it doesn't match the current session.
* <p>
* If there is no session, no action is taken unless the {@code alwaysCreateSession}
* property is set, in which case a session will be created if one doesn't already
* exist.
*/
@Override
public void onAuthentication(Authentication authentication, HttpServletRequest request,
HttpServletResponse response) {
boolean hadSessionAlready = request.getSession(false) != null;
if (!hadSessionAlready && !this.alwaysCreateSession) {
// Session fixation isn't a problem if there's no session
return;
}
// Create new session if necessary
HttpSession session = request.getSession();
if (hadSessionAlready && request.isRequestedSessionIdValid()) {
String originalSessionId;
String newSessionId;
Object mutex = WebUtils.getSessionMutex(session);
synchronized (mutex) {
// We need to migrate to a new session
originalSessionId = session.getId();
session = applySessionFixation(request);
newSessionId = session.getId();
}
if (originalSessionId.equals(newSessionId)) {
this.logger.warn("Your servlet container did not change the session ID when a new session "
+ "was created. You will not be adequately protected against session-fixation attacks");
}
else {
if (this.logger.isDebugEnabled()) {
this.logger.debug(LogMessage.format("Changed session id from %s", originalSessionId));
}
}
onSessionChange(originalSessionId, session, authentication);
}
}
/**
* Applies session fixation
* @param request the {@link HttpServletRequest} to apply session fixation protection
* for
* @return the new {@link HttpSession} to use. Cannot be null.
*/
abstract HttpSession applySessionFixation(HttpServletRequest request);
/**
* Called when the session has been changed and the old attributes have been migrated
* to the new session. Only called if a session existed to start with. Allows
* subclasses to plug in additional behaviour. *
* <p>
* The default implementation of this method publishes a
* {@link SessionFixationProtectionEvent} to notify the application that the session
* ID has changed. If you override this method and still wish these events to be
* published, you should call {@code super.onSessionChange()} within your overriding
* method.
* @param originalSessionId the original session identifier
* @param newSession the newly created session
* @param auth the token for the newly authenticated principal
*/
protected void onSessionChange(String originalSessionId, HttpSession newSession, Authentication auth) {
this.applicationEventPublisher
.publishEvent(new SessionFixationProtectionEvent(auth, originalSessionId, newSession.getId()));
}
/**
* Sets the {@link ApplicationEventPublisher} to use for submitting
* {@link SessionFixationProtectionEvent}. The default is to not submit the
* {@link SessionFixationProtectionEvent}.
* @param applicationEventPublisher the {@link ApplicationEventPublisher}. Cannot be
* null.
*/
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
Assert.notNull(applicationEventPublisher, "applicationEventPublisher cannot be null");
this.applicationEventPublisher = applicationEventPublisher;
}
public void setAlwaysCreateSession(boolean alwaysCreateSession) {
this.alwaysCreateSession = alwaysCreateSession;
}
protected static final class NullEventPublisher implements ApplicationEventPublisher {
@Override
public void publishEvent(ApplicationEvent event) {
}
@Override
public void publishEvent(Object event) {
}
}
}
| 6,099 | 36.654321 | 104 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/session/RegisterSessionAuthenticationStrategy.java | /*
* Copyright 2002-2016 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.web.authentication.session;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.util.Assert;
/**
* Strategy used to register a user with the {@link SessionRegistry} after successful
* {@link Authentication}.
*
* <p>
* {@link RegisterSessionAuthenticationStrategy} is typically used in combination with
* {@link CompositeSessionAuthenticationStrategy} and
* {@link ConcurrentSessionControlAuthenticationStrategy}, but can be used on its own if
* tracking of sessions is desired but no need to control concurrency.
*
* <p>
* NOTE: When using a {@link SessionRegistry} it is important that all sessions (including
* timed out sessions) are removed. This is typically done by adding
* {@link HttpSessionEventPublisher}.
*
* @author Luke Taylor
* @author Rob Winch
* @since 3.2
* @see CompositeSessionAuthenticationStrategy
*/
public class RegisterSessionAuthenticationStrategy implements SessionAuthenticationStrategy {
private final SessionRegistry sessionRegistry;
/**
* @param sessionRegistry the session registry which should be updated when the
* authenticated session is changed.
*/
public RegisterSessionAuthenticationStrategy(SessionRegistry sessionRegistry) {
Assert.notNull(sessionRegistry, "The sessionRegistry cannot be null");
this.sessionRegistry = sessionRegistry;
}
/**
* In addition to the steps from the superclass, the sessionRegistry will be updated
* with the new session information.
*/
@Override
public void onAuthentication(Authentication authentication, HttpServletRequest request,
HttpServletResponse response) {
this.sessionRegistry.registerNewSession(request.getSession().getId(), authentication.getPrincipal());
}
}
| 2,626 | 36 | 103 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/session/SessionFixationProtectionStrategy.java | /*
* Copyright 2002-2020 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.web.authentication.session;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.core.log.LogMessage;
/**
* Uses {@code HttpServletRequest.invalidate()} to protect against session fixation
* attacks.
* <p>
* Creates a new session for the newly authenticated user if they already have a session
* (as a defence against session-fixation protection attacks), and copies their session
* attributes across to the new session. The copying of the attributes can be disabled by
* setting {@code migrateSessionAttributes} to {@code false} (note that even in this case,
* internal Spring Security attributes will still be migrated to the new session).
* <p>
* This approach will only be effective if your servlet container always assigns a new
* session Id when a session is invalidated and a new session created by calling
* {@link HttpServletRequest#getSession()}.
* <p>
* <h3>Issues with {@code HttpSessionBindingListener}</h3>
* <p>
* The migration of existing attributes to the newly-created session may cause problems if
* any of the objects implement the {@code HttpSessionBindingListener} interface in a way
* which makes assumptions about the life-cycle of the object. An example is the use of
* Spring session-scoped beans, where the initial removal of the bean from the session
* will cause the {@code DisposableBean} interface to be invoked, in the assumption that
* the bean is no longer required.
* <p>
* We'd recommend that you take account of this when designing your application and do not
* store attributes which may not function correctly when they are removed and then placed
* back in the session. Alternatively, you should customize the
* {@code SessionAuthenticationStrategy} to deal with the issue in an application-specific
* way.
*
* @author Luke Taylor
* @since 3.0
*/
public class SessionFixationProtectionStrategy extends AbstractSessionFixationProtectionStrategy {
/**
* Indicates that the session attributes of an existing session should be migrated to
* the new session. Defaults to <code>true</code>.
*/
boolean migrateSessionAttributes = true;
/**
* Called to extract the existing attributes from the session, prior to invalidating
* it. If {@code migrateAttributes} is set to {@code false}, only Spring Security
* attributes will be retained. All application attributes will be discarded.
* <p>
* You can override this method to control exactly what is transferred to the new
* session.
* @param session the session from which the attributes should be extracted
* @return the map of session attributes which should be transferred to the new
* session
*/
protected Map<String, Object> extractAttributes(HttpSession session) {
return createMigratedAttributeMap(session);
}
@Override
final HttpSession applySessionFixation(HttpServletRequest request) {
HttpSession session = request.getSession();
String originalSessionId = session.getId();
this.logger.debug(LogMessage.of(() -> "Invalidating session with Id '" + originalSessionId + "' "
+ (this.migrateSessionAttributes ? "and" : "without") + " migrating attributes."));
Map<String, Object> attributesToMigrate = extractAttributes(session);
int maxInactiveIntervalToMigrate = session.getMaxInactiveInterval();
session.invalidate();
session = request.getSession(true); // we now have a new session
this.logger.debug(LogMessage.format("Started new session: %s", session.getId()));
transferAttributes(attributesToMigrate, session);
if (this.migrateSessionAttributes) {
session.setMaxInactiveInterval(maxInactiveIntervalToMigrate);
}
return session;
}
/**
* @param attributes the attributes which were extracted from the original session by
* {@code extractAttributes}
* @param newSession the newly created session
*/
void transferAttributes(Map<String, Object> attributes, HttpSession newSession) {
if (attributes != null) {
attributes.forEach(newSession::setAttribute);
}
}
@SuppressWarnings("unchecked")
private HashMap<String, Object> createMigratedAttributeMap(HttpSession session) {
HashMap<String, Object> attributesToMigrate = new HashMap<>();
Enumeration<String> enumeration = session.getAttributeNames();
while (enumeration.hasMoreElements()) {
String key = enumeration.nextElement();
if (!this.migrateSessionAttributes && !key.startsWith("SPRING_SECURITY_")) {
// Only retain Spring Security attributes
continue;
}
attributesToMigrate.put(key, session.getAttribute(key));
}
return attributesToMigrate;
}
/**
* Defines whether attributes should be migrated to a new session or not. Has no
* effect if you override the {@code extractAttributes} method.
* <p>
* Attributes used by Spring Security (to store cached requests, for example) will
* still be retained by default, even if you set this value to {@code false}.
* @param migrateSessionAttributes whether the attributes from the session should be
* transferred to the new, authenticated session.
*/
public void setMigrateSessionAttributes(boolean migrateSessionAttributes) {
this.migrateSessionAttributes = migrateSessionAttributes;
}
}
| 5,954 | 41.234043 | 99 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/session/SessionAuthenticationException.java | /*
* Copyright 2002-2016 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.web.authentication.session;
import org.springframework.security.core.AuthenticationException;
/**
* Thrown by an <tt>SessionAuthenticationStrategy</tt> to indicate that an authentication
* object is not valid for the current session, typically because the same user has
* exceeded the number of sessions they are allowed to have concurrently.
*
* @author Luke Taylor
* @since 3.0
*/
public class SessionAuthenticationException extends AuthenticationException {
public SessionAuthenticationException(String msg) {
super(msg);
}
}
| 1,204 | 32.472222 | 89 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/package-info.java | /*
* Copyright 2002-2016 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.
*/
/**
* Support for "pre-authenticated" scenarios, where Spring Security assumes the incoming
* request has already been authenticated by some externally configured system.
*/
package org.springframework.security.web.authentication.preauth;
| 865 | 38.363636 | 88 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedCredentialsNotFoundException.java | /*
* Copyright 2002-2016 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.web.authentication.preauth;
import org.springframework.security.core.AuthenticationException;
public class PreAuthenticatedCredentialsNotFoundException extends AuthenticationException {
public PreAuthenticatedCredentialsNotFoundException(String msg) {
super(msg);
}
/**
* @param message The message for the Exception
* @param cause The Exception that caused this Exception.
*/
public PreAuthenticatedCredentialsNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,171 | 31.555556 | 91 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/RequestHeaderAuthenticationFilter.java | /*
* Copyright 2002-2016 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.web.authentication.preauth;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.Assert;
/**
* A simple pre-authenticated filter which obtains the username from a request header, for
* use with systems such as CA Siteminder.
* <p>
* As with most pre-authenticated scenarios, it is essential that the external
* authentication system is set up correctly as this filter does no authentication
* whatsoever. All the protection is assumed to be provided externally and if this filter
* is included inappropriately in a configuration, it would be possible to assume the
* identity of a user merely by setting the correct header name. This also means it should
* not generally be used in combination with other Spring Security authentication
* mechanisms such as form login, as this would imply there was a means of bypassing the
* external system which would be risky.
* <p>
* The property {@code principalRequestHeader} is the name of the request header that
* contains the username. It defaults to "SM_USER" for compatibility with Siteminder.
* <p>
* If the header is missing from the request, {@code getPreAuthenticatedPrincipal} will
* throw an exception. You can override this behaviour by setting the
* {@code exceptionIfHeaderMissing} property.
*
* @author Luke Taylor
* @since 2.0
*/
public class RequestHeaderAuthenticationFilter extends AbstractPreAuthenticatedProcessingFilter {
private String principalRequestHeader = "SM_USER";
private String credentialsRequestHeader;
private boolean exceptionIfHeaderMissing = true;
/**
* Read and returns the header named by {@code principalRequestHeader} from the
* request.
* @throws PreAuthenticatedCredentialsNotFoundException if the header is missing and
* {@code exceptionIfHeaderMissing} is set to {@code true}.
*/
@Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
String principal = request.getHeader(this.principalRequestHeader);
if (principal == null && this.exceptionIfHeaderMissing) {
throw new PreAuthenticatedCredentialsNotFoundException(
this.principalRequestHeader + " header not found in request.");
}
return principal;
}
/**
* Credentials aren't usually applicable, but if a {@code credentialsRequestHeader} is
* set, this will be read and used as the credentials value. Otherwise a dummy value
* will be used.
*/
@Override
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
if (this.credentialsRequestHeader != null) {
return request.getHeader(this.credentialsRequestHeader);
}
return "N/A";
}
public void setPrincipalRequestHeader(String principalRequestHeader) {
Assert.hasText(principalRequestHeader, "principalRequestHeader must not be empty or null");
this.principalRequestHeader = principalRequestHeader;
}
public void setCredentialsRequestHeader(String credentialsRequestHeader) {
Assert.hasText(credentialsRequestHeader, "credentialsRequestHeader must not be empty or null");
this.credentialsRequestHeader = credentialsRequestHeader;
}
/**
* Defines whether an exception should be raised if the principal header is missing.
* Defaults to {@code true}.
* @param exceptionIfHeaderMissing set to {@code false} to override the default
* behaviour and allow the request to proceed if no header is found.
*/
public void setExceptionIfHeaderMissing(boolean exceptionIfHeaderMissing) {
this.exceptionIfHeaderMissing = exceptionIfHeaderMissing;
}
}
| 4,176 | 39.163462 | 97 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsService.java | /*
* Copyright 2002-2016 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.web.authentication.preauth;
import java.util.Collection;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthoritiesContainer;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;
/**
* <p>
* This AuthenticationUserDetailsService implementation creates a UserDetails object based
* solely on the information contained in the given PreAuthenticatedAuthenticationToken.
* The user name is set to the name as returned by
* PreAuthenticatedAuthenticationToken.getName(), the password is set to a fixed dummy
* value (it will not be used by the PreAuthenticatedAuthenticationProvider anyway), and
* the Granted Authorities are retrieved from the details object as returned by
* PreAuthenticatedAuthenticationToken.getDetails().
*
* <p>
* The details object as returned by PreAuthenticatedAuthenticationToken.getDetails() must
* implement the {@link GrantedAuthoritiesContainer} interface for this implementation to
* work.
*
* @author Ruud Senden
* @since 2.0
*/
public class PreAuthenticatedGrantedAuthoritiesUserDetailsService
implements AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> {
/**
* Get a UserDetails object based on the user name contained in the given token, and
* the GrantedAuthorities as returned by the GrantedAuthoritiesContainer
* implementation as returned by the token.getDetails() method.
*/
@Override
public final UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token) throws AuthenticationException {
Assert.notNull(token.getDetails(), "token.getDetails() cannot be null");
Assert.isInstanceOf(GrantedAuthoritiesContainer.class, token.getDetails());
Collection<? extends GrantedAuthority> authorities = ((GrantedAuthoritiesContainer) token.getDetails())
.getGrantedAuthorities();
return createUserDetails(token, authorities);
}
/**
* Creates the final <tt>UserDetails</tt> object. Can be overridden to customize the
* contents.
* @param token the authentication request token
* @param authorities the pre-authenticated authorities.
*/
protected UserDetails createUserDetails(Authentication token, Collection<? extends GrantedAuthority> authorities) {
return new User(token.getName(), "N/A", true, true, true, true, authorities);
}
}
| 3,307 | 42.526316 | 117 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationProvider.java | /*
* Copyright 2002-2016 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.web.authentication.preauth;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.Ordered;
import org.springframework.core.log.LogMessage;
import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;
import org.springframework.util.Assert;
/**
* <p>
* Processes a pre-authenticated authentication request. The request will typically
* originate from a
* {@link org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter}
* subclass.
*
* <p>
* This authentication provider will not perform any checks on authentication requests, as
* they should already be pre-authenticated. However, the AuthenticationUserDetailsService
* implementation may still throw a UsernameNotFoundException, for example.
*
* @author Ruud Senden
* @since 2.0
*/
public class PreAuthenticatedAuthenticationProvider implements AuthenticationProvider, InitializingBean, Ordered {
private static final Log logger = LogFactory.getLog(PreAuthenticatedAuthenticationProvider.class);
private AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> preAuthenticatedUserDetailsService;
private UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker();
private boolean throwExceptionWhenTokenRejected;
private int order = -1; // default: same as non-ordered
/**
* Check whether all required properties have been set.
*/
@Override
public void afterPropertiesSet() {
Assert.notNull(this.preAuthenticatedUserDetailsService, "An AuthenticationUserDetailsService must be set");
}
/**
* Authenticate the given PreAuthenticatedAuthenticationToken.
* <p>
* If the principal contained in the authentication object is null, the request will
* be ignored to allow other providers to authenticate it.
*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (!supports(authentication.getClass())) {
return null;
}
logger.debug(LogMessage.format("PreAuthenticated authentication request: %s", authentication));
if (authentication.getPrincipal() == null) {
logger.debug("No pre-authenticated principal found in request.");
if (this.throwExceptionWhenTokenRejected) {
throw new BadCredentialsException("No pre-authenticated principal found in request.");
}
return null;
}
if (authentication.getCredentials() == null) {
logger.debug("No pre-authenticated credentials found in request.");
if (this.throwExceptionWhenTokenRejected) {
throw new BadCredentialsException("No pre-authenticated credentials found in request.");
}
return null;
}
UserDetails userDetails = this.preAuthenticatedUserDetailsService
.loadUserDetails((PreAuthenticatedAuthenticationToken) authentication);
this.userDetailsChecker.check(userDetails);
PreAuthenticatedAuthenticationToken result = new PreAuthenticatedAuthenticationToken(userDetails,
authentication.getCredentials(), userDetails.getAuthorities());
result.setDetails(authentication.getDetails());
return result;
}
/**
* Indicate that this provider only supports PreAuthenticatedAuthenticationToken
* (sub)classes.
*/
@Override
public final boolean supports(Class<?> authentication) {
return PreAuthenticatedAuthenticationToken.class.isAssignableFrom(authentication);
}
/**
* Set the AuthenticatedUserDetailsService to be used to load the {@code UserDetails}
* for the authenticated user.
* @param uds
*/
public void setPreAuthenticatedUserDetailsService(
AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> uds) {
this.preAuthenticatedUserDetailsService = uds;
}
/**
* If true, causes the provider to throw a BadCredentialsException if the presented
* authentication request is invalid (contains a null principal or credentials).
* Otherwise it will just return null. Defaults to false.
*/
public void setThrowExceptionWhenTokenRejected(boolean throwExceptionWhenTokenRejected) {
this.throwExceptionWhenTokenRejected = throwExceptionWhenTokenRejected;
}
/**
* Sets the strategy which will be used to validate the loaded <tt>UserDetails</tt>
* object for the user. Defaults to an {@link AccountStatusUserDetailsChecker}.
* @param userDetailsChecker
*/
public void setUserDetailsChecker(UserDetailsChecker userDetailsChecker) {
Assert.notNull(userDetailsChecker, "userDetailsChecker cannot be null");
this.userDetailsChecker = userDetailsChecker;
}
@Override
public int getOrder() {
return this.order;
}
public void setOrder(int i) {
this.order = i;
}
}
| 5,878 | 37.424837 | 114 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/RequestAttributeAuthenticationFilter.java | /*
* Copyright 2002-2016 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.web.authentication.preauth;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.Assert;
/**
* A simple pre-authenticated filter which obtains the username from request attributes,
* for use with SSO systems such as
* <a href="https://webauth.stanford.edu/manual/mod/mod_webauth.html#java">Stanford
* WebAuth</a> or <a href=
* "https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPJavaInstall">Shibboleth</a>.
* <p>
* As with most pre-authenticated scenarios, it is essential that the external
* authentication system is set up correctly as this filter does no authentication
* whatsoever.
* <p>
* The property {@code principalEnvironmentVariable} is the name of the request attribute
* that contains the username. It defaults to "REMOTE_USER" for compatibility with WebAuth
* and Shibboleth.
* <p>
* If the environment variable is missing from the request,
* {@code getPreAuthenticatedPrincipal} will throw an exception. You can override this
* behaviour by setting the {@code exceptionIfVariableMissing} property.
*
* @author Milan Sevcik
* @since 4.2
*/
public class RequestAttributeAuthenticationFilter extends AbstractPreAuthenticatedProcessingFilter {
private String principalEnvironmentVariable = "REMOTE_USER";
private String credentialsEnvironmentVariable;
private boolean exceptionIfVariableMissing = true;
/**
* Read and returns the variable named by {@code principalEnvironmentVariable} from
* the request.
* @throws PreAuthenticatedCredentialsNotFoundException if the environment variable is
* missing and {@code exceptionIfVariableMissing} is set to {@code true}.
*/
@Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
String principal = (String) request.getAttribute(this.principalEnvironmentVariable);
if (principal == null && this.exceptionIfVariableMissing) {
throw new PreAuthenticatedCredentialsNotFoundException(
this.principalEnvironmentVariable + " variable not found in request.");
}
return principal;
}
/**
* Credentials aren't usually applicable, but if a
* {@code credentialsEnvironmentVariable} is set, this will be read and used as the
* credentials value. Otherwise a dummy value will be used.
*/
@Override
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
if (this.credentialsEnvironmentVariable != null) {
return request.getAttribute(this.credentialsEnvironmentVariable);
}
return "N/A";
}
public void setPrincipalEnvironmentVariable(String principalEnvironmentVariable) {
Assert.hasText(principalEnvironmentVariable, "principalEnvironmentVariable must not be empty or null");
this.principalEnvironmentVariable = principalEnvironmentVariable;
}
public void setCredentialsEnvironmentVariable(String credentialsEnvironmentVariable) {
Assert.hasText(credentialsEnvironmentVariable, "credentialsEnvironmentVariable must not be empty or null");
this.credentialsEnvironmentVariable = credentialsEnvironmentVariable;
}
/**
* Defines whether an exception should be raised if the principal variable is missing.
* Defaults to {@code true}.
* @param exceptionIfVariableMissing set to {@code false} to override the default
* behaviour and allow the request to proceed if no variable is found.
*/
public void setExceptionIfVariableMissing(boolean exceptionIfVariableMissing) {
this.exceptionIfVariableMissing = exceptionIfVariableMissing;
}
}
| 4,133 | 39.135922 | 109 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationToken.java | /*
* Copyright 2002-2016 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.web.authentication.preauth;
import java.util.Collection;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
/**
* {@link org.springframework.security.core.Authentication} implementation for
* pre-authenticated authentication.
*
* @author Ruud Senden
* @since 2.0
*/
public class PreAuthenticatedAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final Object principal;
private final Object credentials;
/**
* Constructor used for an authentication request. The
* {@link org.springframework.security.core.Authentication#isAuthenticated()} will
* return <code>false</code>.
* @param aPrincipal The pre-authenticated principal
* @param aCredentials The pre-authenticated credentials
*/
public PreAuthenticatedAuthenticationToken(Object aPrincipal, Object aCredentials) {
super(null);
this.principal = aPrincipal;
this.credentials = aCredentials;
}
/**
* Constructor used for an authentication response. The
* {@link org.springframework.security.core.Authentication#isAuthenticated()} will
* return <code>true</code>.
* @param aPrincipal The authenticated principal
* @param anAuthorities The granted authorities
*/
public PreAuthenticatedAuthenticationToken(Object aPrincipal, Object aCredentials,
Collection<? extends GrantedAuthority> anAuthorities) {
super(anAuthorities);
this.principal = aPrincipal;
this.credentials = aCredentials;
setAuthenticated(true);
}
/**
* Get the credentials
*/
@Override
public Object getCredentials() {
return this.credentials;
}
/**
* Get the principal
*/
@Override
public Object getPrincipal() {
return this.principal;
}
}
| 2,565 | 29.188235 | 91 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.java | /*
* Copyright 2002-2016 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.web.authentication.preauth;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.authority.GrantedAuthoritiesContainer;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
/**
* This WebAuthenticationDetails implementation allows for storing a list of
* pre-authenticated Granted Authorities.
*
* @author Ruud Senden
* @author Luke Taylor
* @since 2.0
*/
public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails extends WebAuthenticationDetails
implements GrantedAuthoritiesContainer {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final List<GrantedAuthority> authorities;
public PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(HttpServletRequest request,
Collection<? extends GrantedAuthority> authorities) {
super(request);
List<GrantedAuthority> temp = new ArrayList<>(authorities.size());
temp.addAll(authorities);
this.authorities = Collections.unmodifiableList(temp);
}
@Override
public List<GrantedAuthority> getGrantedAuthorities() {
return this.authorities;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString()).append("; ");
sb.append(this.authorities);
return sb.toString();
}
}
| 2,235 | 31.882353 | 104 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilter.java | /*
* Copyright 2002-2022 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.web.authentication.preauth;
import java.io.IOException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.core.log.LogMessage;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
import org.springframework.web.filter.GenericFilterBean;
/**
* Base class for processing filters that handle pre-authenticated authentication
* requests, where it is assumed that the principal has already been authenticated by an
* external system.
* <p>
* The purpose is then only to extract the necessary information on the principal from the
* incoming request, rather than to authenticate them. External authentication systems may
* provide this information via request data such as headers or cookies which the
* pre-authentication system can extract. It is assumed that the external system is
* responsible for the accuracy of the data and preventing the submission of forged
* values.
*
* Subclasses must implement the {@code getPreAuthenticatedPrincipal()} and
* {@code getPreAuthenticatedCredentials()} methods. Subclasses of this filter are
* typically used in combination with a {@code PreAuthenticatedAuthenticationProvider},
* which is used to load additional data for the user. This provider will reject null
* credentials, so the {@link #getPreAuthenticatedCredentials} method should not return
* null for a valid principal.
* <p>
* If the security context already contains an {@code Authentication} object (either from
* a invocation of the filter or because of some other authentication mechanism), the
* filter will do nothing by default. You can force it to check for a change in the
* principal by setting the {@link #setCheckForPrincipalChanges(boolean)
* checkForPrincipalChanges} property.
* <p>
* By default, the filter chain will proceed when an authentication attempt fails in order
* to allow other authentication mechanisms to process the request. To reject the
* credentials immediately, set the
* <tt>continueFilterChainOnUnsuccessfulAuthentication</tt> flag to false. The exception
* raised by the <tt>AuthenticationManager</tt> will the be re-thrown. Note that this will
* not affect cases where the principal returned by {@link #getPreAuthenticatedPrincipal}
* is null, when the chain will still proceed as normal.
*
* @author Luke Taylor
* @author Ruud Senden
* @author Rob Winch
* @author Tadaya Tsuyukubo
* @since 2.0
*/
public abstract class AbstractPreAuthenticatedProcessingFilter extends GenericFilterBean
implements ApplicationEventPublisherAware {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private ApplicationEventPublisher eventPublisher = null;
private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
private AuthenticationManager authenticationManager = null;
private boolean continueFilterChainOnUnsuccessfulAuthentication = true;
private boolean checkForPrincipalChanges;
private boolean invalidateSessionOnPrincipalChange = true;
private AuthenticationSuccessHandler authenticationSuccessHandler = null;
private AuthenticationFailureHandler authenticationFailureHandler = null;
private RequestMatcher requiresAuthenticationRequestMatcher = new PreAuthenticatedProcessingRequestMatcher();
private SecurityContextRepository securityContextRepository = new HttpSessionSecurityContextRepository();
/**
* Check whether all required properties have been set.
*/
@Override
public void afterPropertiesSet() {
try {
super.afterPropertiesSet();
}
catch (ServletException ex) {
// convert to RuntimeException for passivity on afterPropertiesSet signature
throw new RuntimeException(ex);
}
Assert.notNull(this.authenticationManager, "An AuthenticationManager must be set");
}
/**
* Try to authenticate a pre-authenticated user with Spring Security if the user has
* not yet been authenticated.
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (this.requiresAuthenticationRequestMatcher.matches((HttpServletRequest) request)) {
if (logger.isDebugEnabled()) {
logger.debug(LogMessage.of(
() -> "Authenticating " + this.securityContextHolderStrategy.getContext().getAuthentication()));
}
doAuthenticate((HttpServletRequest) request, (HttpServletResponse) response);
}
else {
if (logger.isTraceEnabled()) {
logger.trace(LogMessage.format("Did not authenticate since request did not match [%s]",
this.requiresAuthenticationRequestMatcher));
}
}
chain.doFilter(request, response);
}
/**
* Determines if the current principal has changed. The default implementation tries
*
* <ul>
* <li>If the {@link #getPreAuthenticatedPrincipal(HttpServletRequest)} is a String,
* the {@link Authentication#getName()} is compared against the pre authenticated
* principal</li>
* <li>Otherwise, the {@link #getPreAuthenticatedPrincipal(HttpServletRequest)} is
* compared against the {@link Authentication#getPrincipal()}
* </ul>
*
* <p>
* Subclasses can override this method to determine when a principal has changed.
* </p>
* @param request
* @param currentAuthentication
* @return true if the principal has changed, else false
*/
protected boolean principalChanged(HttpServletRequest request, Authentication currentAuthentication) {
Object principal = getPreAuthenticatedPrincipal(request);
if ((principal instanceof String) && currentAuthentication.getName().equals(principal)) {
return false;
}
if (principal != null && principal.equals(currentAuthentication.getPrincipal())) {
return false;
}
this.logger.debug(LogMessage.format("Pre-authenticated principal has changed to %s and will be reauthenticated",
principal));
return true;
}
/**
* Do the actual authentication for a pre-authenticated user.
*/
private void doAuthenticate(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
Object principal = getPreAuthenticatedPrincipal(request);
if (principal == null) {
this.logger.debug("No pre-authenticated principal found in request");
return;
}
this.logger.debug(LogMessage.format("preAuthenticatedPrincipal = %s, trying to authenticate", principal));
Object credentials = getPreAuthenticatedCredentials(request);
try {
PreAuthenticatedAuthenticationToken authenticationRequest = new PreAuthenticatedAuthenticationToken(
principal, credentials);
authenticationRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
Authentication authenticationResult = this.authenticationManager.authenticate(authenticationRequest);
successfulAuthentication(request, response, authenticationResult);
}
catch (AuthenticationException ex) {
unsuccessfulAuthentication(request, response, ex);
if (!this.continueFilterChainOnUnsuccessfulAuthentication) {
throw ex;
}
}
}
/**
* Puts the <code>Authentication</code> instance returned by the authentication
* manager into the secure context.
*/
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
Authentication authResult) throws IOException, ServletException {
this.logger.debug(LogMessage.format("Authentication success: %s", authResult));
SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
context.setAuthentication(authResult);
this.securityContextHolderStrategy.setContext(context);
this.securityContextRepository.saveContext(context, request, response);
if (this.eventPublisher != null) {
this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));
}
if (this.authenticationSuccessHandler != null) {
this.authenticationSuccessHandler.onAuthenticationSuccess(request, response, authResult);
}
}
/**
* Ensures the authentication object in the secure context is set to null when
* authentication fails.
* <p>
* Caches the failure exception as a request attribute
*/
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) throws IOException, ServletException {
this.securityContextHolderStrategy.clearContext();
this.logger.debug("Cleared security context due to exception", failed);
request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, failed);
if (this.authenticationFailureHandler != null) {
this.authenticationFailureHandler.onAuthenticationFailure(request, response, failed);
}
}
/**
* @param anApplicationEventPublisher The ApplicationEventPublisher to use
*/
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher anApplicationEventPublisher) {
this.eventPublisher = anApplicationEventPublisher;
}
/**
* Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on
* authentication success. The default action is not to save the
* {@link SecurityContext}.
* @param securityContextRepository the {@link SecurityContextRepository} to use.
* Cannot be null.
*/
public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) {
Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
this.securityContextRepository = securityContextRepository;
}
/**
* @param authenticationDetailsSource The AuthenticationDetailsSource to use
*/
public void setAuthenticationDetailsSource(
AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required");
this.authenticationDetailsSource = authenticationDetailsSource;
}
protected AuthenticationDetailsSource<HttpServletRequest, ?> getAuthenticationDetailsSource() {
return this.authenticationDetailsSource;
}
/**
* @param authenticationManager The AuthenticationManager to use
*/
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
/**
* If set to {@code true} (the default), any {@code AuthenticationException} raised by
* the {@code AuthenticationManager} will be swallowed, and the request will be
* allowed to proceed, potentially using alternative authentication mechanisms. If
* {@code false}, authentication failure will result in an immediate exception.
* @param shouldContinue set to {@code true} to allow the request to proceed after a
* failed authentication.
*/
public void setContinueFilterChainOnUnsuccessfulAuthentication(boolean shouldContinue) {
this.continueFilterChainOnUnsuccessfulAuthentication = shouldContinue;
}
/**
* If set, the pre-authenticated principal will be checked on each request and
* compared against the name of the current <tt>Authentication</tt> object. A check to
* determine if {@link Authentication#getPrincipal()} is equal to the principal will
* also be performed. If a change is detected, the user will be reauthenticated.
* @param checkForPrincipalChanges
*/
public void setCheckForPrincipalChanges(boolean checkForPrincipalChanges) {
this.checkForPrincipalChanges = checkForPrincipalChanges;
}
/**
* If <tt>checkForPrincipalChanges</tt> is set, and a change of principal is detected,
* determines whether any existing session should be invalidated before proceeding to
* authenticate the new principal.
* @param invalidateSessionOnPrincipalChange <tt>false</tt> to retain the existing
* session. Defaults to <tt>true</tt>.
*/
public void setInvalidateSessionOnPrincipalChange(boolean invalidateSessionOnPrincipalChange) {
this.invalidateSessionOnPrincipalChange = invalidateSessionOnPrincipalChange;
}
/**
* Sets the strategy used to handle a successful authentication.
*/
public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler authenticationSuccessHandler) {
this.authenticationSuccessHandler = authenticationSuccessHandler;
}
/**
* Sets the strategy used to handle a failed authentication.
*/
public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
this.authenticationFailureHandler = authenticationFailureHandler;
}
/**
* Sets the request matcher to check whether to proceed the request further.
*/
public void setRequiresAuthenticationRequestMatcher(RequestMatcher requiresAuthenticationRequestMatcher) {
Assert.notNull(requiresAuthenticationRequestMatcher, "requestMatcher cannot be null");
this.requiresAuthenticationRequestMatcher = requiresAuthenticationRequestMatcher;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
/**
* Override to extract the principal information from the current request
*/
protected abstract Object getPreAuthenticatedPrincipal(HttpServletRequest request);
/**
* Override to extract the credentials (if applicable) from the current request.
* Should not return null for a valid principal, though some implementations may
* return a dummy value.
*/
protected abstract Object getPreAuthenticatedCredentials(HttpServletRequest request);
/**
* Request matcher for default auth check logic
*/
private class PreAuthenticatedProcessingRequestMatcher implements RequestMatcher {
@Override
public boolean matches(HttpServletRequest request) {
Authentication currentUser = AbstractPreAuthenticatedProcessingFilter.this.securityContextHolderStrategy
.getContext().getAuthentication();
if (currentUser == null) {
return true;
}
if (!AbstractPreAuthenticatedProcessingFilter.this.checkForPrincipalChanges) {
return false;
}
if (!principalChanged(request, currentUser)) {
return false;
}
AbstractPreAuthenticatedProcessingFilter.this.logger
.debug("Pre-authenticated principal has changed and will be reauthenticated");
if (AbstractPreAuthenticatedProcessingFilter.this.invalidateSessionOnPrincipalChange) {
AbstractPreAuthenticatedProcessingFilter.this.securityContextHolderStrategy.clearContext();
HttpSession session = request.getSession(false);
if (session != null) {
AbstractPreAuthenticatedProcessingFilter.this.logger.debug("Invalidating existing session");
session.invalidate();
request.getSession();
}
}
return true;
}
}
}
| 17,082 | 41.7075 | 127 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/package-info.java | /*
* Copyright 2002-2016 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.
*/
/**
* Websphere-specific pre-authentication classes.
*/
package org.springframework.security.web.authentication.preauth.websphere;
| 756 | 35.047619 | 75 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/DefaultWASUsernameAndGroupsExtractor.java | /*
* Copyright 2002-2016 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.web.authentication.preauth.websphere;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.security.auth.Subject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogMessage;
/**
* WebSphere Security helper class to allow retrieval of the current username and groups.
* <p>
* See Spring Security Jira SEC-477.
*
* @author Ruud Senden
* @author Stephane Manciot
* @since 2.0
*/
final class DefaultWASUsernameAndGroupsExtractor implements WASUsernameAndGroupsExtractor {
private static final Log logger = LogFactory.getLog(DefaultWASUsernameAndGroupsExtractor.class);
private static final String PORTABLE_REMOTE_OBJECT_CLASSNAME = "javax.rmi.PortableRemoteObject";
private static final String USER_REGISTRY = "UserRegistry";
private static Method getRunAsSubject = null;
private static Method getGroupsForUser = null;
private static Method getSecurityName = null;
private static Method narrow = null;
// SEC-803
private static Class<?> wsCredentialClass = null;
@Override
public List<String> getGroupsForCurrentUser() {
return getWebSphereGroups(getRunAsSubject());
}
@Override
public String getCurrentUserName() {
return getSecurityName(getRunAsSubject());
}
/**
* Get the security name for the given subject.
* @param subject The subject for which to retrieve the security name
* @return String the security name for the given subject
*/
private static String getSecurityName(final Subject subject) {
logger.debug(LogMessage.format("Determining Websphere security name for subject %s", subject));
String userSecurityName = null;
if (subject != null) {
// SEC-803
Object credential = subject.getPublicCredentials(getWSCredentialClass()).iterator().next();
if (credential != null) {
userSecurityName = (String) invokeMethod(getSecurityNameMethod(), credential);
}
}
logger.debug(LogMessage.format("Websphere security name is %s for subject %s", subject, userSecurityName));
return userSecurityName;
}
/**
* Get the current RunAs subject.
* @return Subject the current RunAs subject
*/
private static Subject getRunAsSubject() {
logger.debug("Retrieving WebSphere RunAs subject");
// get Subject: WSSubject.getCallerSubject ();
return (Subject) invokeMethod(getRunAsSubjectMethod(), null, new Object[] {});
}
/**
* Get the WebSphere group names for the given subject.
* @param subject The subject for which to retrieve the WebSphere group names
* @return the WebSphere group names for the given subject
*/
private static List<String> getWebSphereGroups(final Subject subject) {
return getWebSphereGroups(getSecurityName(subject));
}
/**
* Get the WebSphere group names for the given security name.
* @param securityName The security name for which to retrieve the WebSphere group
* names
* @return the WebSphere group names for the given security name
*/
@SuppressWarnings("unchecked")
private static List<String> getWebSphereGroups(final String securityName) {
Context context = null;
try {
// TODO: Cache UserRegistry object
context = new InitialContext();
Object objRef = context.lookup(USER_REGISTRY);
Object userReg = invokeMethod(getNarrowMethod(), null, objRef,
Class.forName("com.ibm.websphere.security.UserRegistry"));
logger.debug(LogMessage.format("Determining WebSphere groups for user %s using WebSphere UserRegistry %s",
securityName, userReg));
final Collection<String> groups = (Collection<String>) invokeMethod(getGroupsForUserMethod(), userReg,
new Object[] { securityName });
logger.debug(LogMessage.format("Groups for user %s: %s", securityName, groups));
return new ArrayList<String>(groups);
}
catch (Exception ex) {
logger.error("Exception occured while looking up groups for user", ex);
throw new RuntimeException("Exception occured while looking up groups for user", ex);
}
finally {
closeContext(context);
}
}
private static void closeContext(Context context) {
try {
if (context != null) {
context.close();
}
}
catch (NamingException ex) {
logger.debug("Exception occured while closing context", ex);
}
}
private static Object invokeMethod(Method method, Object instance, Object... args) {
try {
return method.invoke(instance, args);
}
catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException ex) {
String message = "Error while invoking method " + method.getClass().getName() + "." + method.getName() + "("
+ Arrays.asList(args) + ")";
logger.error(message, ex);
throw new RuntimeException(message, ex);
}
}
private static Method getMethod(String className, String methodName, String[] parameterTypeNames) {
try {
Class<?> c = Class.forName(className);
int len = parameterTypeNames.length;
Class<?>[] parameterTypes = new Class[len];
for (int i = 0; i < len; i++) {
parameterTypes[i] = Class.forName(parameterTypeNames[i]);
}
return c.getDeclaredMethod(methodName, parameterTypes);
}
catch (ClassNotFoundException ex) {
logger.error("Required class" + className + " not found");
throw new RuntimeException("Required class" + className + " not found", ex);
}
catch (NoSuchMethodException ex) {
logger.error("Required method " + methodName + " with parameter types (" + Arrays.asList(parameterTypeNames)
+ ") not found on class " + className);
throw new RuntimeException("Required class" + className + " not found", ex);
}
}
private static Method getRunAsSubjectMethod() {
if (getRunAsSubject == null) {
getRunAsSubject = getMethod("com.ibm.websphere.security.auth.WSSubject", "getRunAsSubject",
new String[] {});
}
return getRunAsSubject;
}
private static Method getGroupsForUserMethod() {
if (getGroupsForUser == null) {
getGroupsForUser = getMethod("com.ibm.websphere.security.UserRegistry", "getGroupsForUser",
new String[] { "java.lang.String" });
}
return getGroupsForUser;
}
private static Method getSecurityNameMethod() {
if (getSecurityName == null) {
getSecurityName = getMethod("com.ibm.websphere.security.cred.WSCredential", "getSecurityName",
new String[] {});
}
return getSecurityName;
}
private static Method getNarrowMethod() {
if (narrow == null) {
narrow = getMethod(PORTABLE_REMOTE_OBJECT_CLASSNAME, "narrow",
new String[] { Object.class.getName(), Class.class.getName() });
}
return narrow;
}
// SEC-803
private static Class<?> getWSCredentialClass() {
if (wsCredentialClass == null) {
wsCredentialClass = getClass("com.ibm.websphere.security.cred.WSCredential");
}
return wsCredentialClass;
}
private static Class<?> getClass(String className) {
try {
return Class.forName(className);
}
catch (ClassNotFoundException ex) {
logger.error("Required class " + className + " not found");
throw new RuntimeException("Required class " + className + " not found", ex);
}
}
}
| 7,920 | 32.281513 | 111 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilter.java | /*
* Copyright 2002-2016 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.web.authentication.preauth.websphere;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.log.LogMessage;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
/**
* This AbstractPreAuthenticatedProcessingFilter implementation is based on WebSphere
* authentication. It will use the WebSphere RunAs user principal name as the
* pre-authenticated principal.
*
* @author Ruud Senden
* @since 2.0
*/
public class WebSpherePreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter {
private final WASUsernameAndGroupsExtractor wasHelper;
/**
* Public constructor which overrides the default AuthenticationDetails class to be
* used.
*/
public WebSpherePreAuthenticatedProcessingFilter() {
this(new DefaultWASUsernameAndGroupsExtractor());
}
WebSpherePreAuthenticatedProcessingFilter(WASUsernameAndGroupsExtractor wasHelper) {
this.wasHelper = wasHelper;
setAuthenticationDetailsSource(new WebSpherePreAuthenticatedWebAuthenticationDetailsSource());
}
/**
* Return the WebSphere user name.
*/
@Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest httpRequest) {
Object principal = this.wasHelper.getCurrentUserName();
this.logger.debug(LogMessage.format("PreAuthenticated WebSphere principal: %s", principal));
return principal;
}
/**
* For J2EE container-based authentication there is no generic way to retrieve the
* credentials, as such this method returns a fixed dummy value.
*/
@Override
protected Object getPreAuthenticatedCredentials(HttpServletRequest httpRequest) {
return "N/A";
}
}
| 2,333 | 32.826087 | 105 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedWebAuthenticationDetailsSource.java | /*
* Copyright 2002-2016 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.web.authentication.preauth.websphere;
import java.util.Collection;
import java.util.List;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogMessage;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.mapping.Attributes2GrantedAuthoritiesMapper;
import org.springframework.security.core.authority.mapping.SimpleAttributes2GrantedAuthoritiesMapper;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails;
/**
* This AuthenticationDetailsSource implementation will set the pre-authenticated granted
* authorities based on the WebSphere groups for the current WebSphere user, mapped using
* the configured Attributes2GrantedAuthoritiesMapper.
*
* @author Ruud Senden
*/
public class WebSpherePreAuthenticatedWebAuthenticationDetailsSource implements
AuthenticationDetailsSource<HttpServletRequest, PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails> {
private final Log logger = LogFactory.getLog(getClass());
private Attributes2GrantedAuthoritiesMapper webSphereGroups2GrantedAuthoritiesMapper = new SimpleAttributes2GrantedAuthoritiesMapper();
private final WASUsernameAndGroupsExtractor wasHelper;
public WebSpherePreAuthenticatedWebAuthenticationDetailsSource() {
this(new DefaultWASUsernameAndGroupsExtractor());
}
public WebSpherePreAuthenticatedWebAuthenticationDetailsSource(WASUsernameAndGroupsExtractor wasHelper) {
this.wasHelper = wasHelper;
}
@Override
public PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails buildDetails(HttpServletRequest context) {
return new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(context,
getWebSphereGroupsBasedGrantedAuthorities());
}
/**
* Get a list of Granted Authorities based on the current user's WebSphere groups.
* @return authorities mapped from the user's WebSphere groups.
*/
private Collection<? extends GrantedAuthority> getWebSphereGroupsBasedGrantedAuthorities() {
List<String> webSphereGroups = this.wasHelper.getGroupsForCurrentUser();
Collection<? extends GrantedAuthority> userGas = this.webSphereGroups2GrantedAuthoritiesMapper
.getGrantedAuthorities(webSphereGroups);
this.logger.debug(
LogMessage.format("WebSphere groups: %s mapped to Granted Authorities: %s", webSphereGroups, userGas));
return userGas;
}
/**
* @param mapper The Attributes2GrantedAuthoritiesMapper to use for converting the WAS
* groups to authorities
*/
public void setWebSphereGroups2GrantedAuthoritiesMapper(Attributes2GrantedAuthoritiesMapper mapper) {
this.webSphereGroups2GrantedAuthoritiesMapper = mapper;
}
}
| 3,545 | 40.717647 | 136 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/WASUsernameAndGroupsExtractor.java | /*
* Copyright 2002-2016 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.web.authentication.preauth.websphere;
import java.util.List;
/**
* Provides indirection between classes using websphere and the actual container
* interaction, allowing for easier unit testing.
* <p>
* Only for internal use.
*
* @author Luke Taylor
* @since 3.0.0
*/
interface WASUsernameAndGroupsExtractor {
List<String> getGroupsForCurrentUser();
String getCurrentUserName();
}
| 1,055 | 27.540541 | 80 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.java | /*
* Copyright 2002-2016 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.web.authentication.preauth.j2ee;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.log.LogMessage;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.mapping.Attributes2GrantedAuthoritiesMapper;
import org.springframework.security.core.authority.mapping.MappableAttributesRetriever;
import org.springframework.security.core.authority.mapping.SimpleAttributes2GrantedAuthoritiesMapper;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails;
import org.springframework.util.Assert;
/**
* Implementation of AuthenticationDetailsSource which converts the user's J2EE roles (as
* obtained by calling {@link HttpServletRequest#isUserInRole(String)}) into
* {@code GrantedAuthority}s and stores these in the authentication details object.
*
* @author Ruud Senden
* @since 2.0
*/
public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource implements
AuthenticationDetailsSource<HttpServletRequest, PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails>,
InitializingBean {
protected final Log logger = LogFactory.getLog(getClass());
/**
* The role attributes returned by the configured {@code MappableAttributesRetriever}
*/
protected Set<String> j2eeMappableRoles;
protected Attributes2GrantedAuthoritiesMapper j2eeUserRoles2GrantedAuthoritiesMapper = new SimpleAttributes2GrantedAuthoritiesMapper();
/**
* Check that all required properties have been set.
*/
@Override
public void afterPropertiesSet() {
Assert.notNull(this.j2eeMappableRoles, "No mappable roles available");
Assert.notNull(this.j2eeUserRoles2GrantedAuthoritiesMapper, "Roles to granted authorities mapper not set");
}
/**
* Obtains the list of user roles based on the current user's JEE roles. The
* {@link jakarta.servlet.http.HttpServletRequest#isUserInRole(String)} method is
* called for each of the values in the {@code j2eeMappableRoles} set to determine if
* that role should be assigned to the user.
* @param request the request which should be used to extract the user's roles.
* @return The subset of {@code j2eeMappableRoles} which applies to the current user
* making the request.
*/
protected Collection<String> getUserRoles(HttpServletRequest request) {
ArrayList<String> j2eeUserRolesList = new ArrayList<>();
for (String role : this.j2eeMappableRoles) {
if (request.isUserInRole(role)) {
j2eeUserRolesList.add(role);
}
}
return j2eeUserRolesList;
}
/**
* Builds the authentication details object.
*
* @see org.springframework.security.authentication.AuthenticationDetailsSource#buildDetails(Object)
*/
@Override
public PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails buildDetails(HttpServletRequest context) {
Collection<String> j2eeUserRoles = getUserRoles(context);
Collection<? extends GrantedAuthority> userGrantedAuthorities = this.j2eeUserRoles2GrantedAuthoritiesMapper
.getGrantedAuthorities(j2eeUserRoles);
if (this.logger.isDebugEnabled()) {
this.logger.debug(LogMessage.format("J2EE roles [%s] mapped to Granted Authorities: [%s]", j2eeUserRoles,
userGrantedAuthorities));
}
return new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(context, userGrantedAuthorities);
}
/**
* @param aJ2eeMappableRolesRetriever The MappableAttributesRetriever to use
*/
public void setMappableRolesRetriever(MappableAttributesRetriever aJ2eeMappableRolesRetriever) {
this.j2eeMappableRoles = Collections.unmodifiableSet(aJ2eeMappableRolesRetriever.getMappableAttributes());
}
/**
* @param mapper The Attributes2GrantedAuthoritiesMapper to use
*/
public void setUserRoles2GrantedAuthoritiesMapper(Attributes2GrantedAuthoritiesMapper mapper) {
this.j2eeUserRoles2GrantedAuthoritiesMapper = mapper;
}
}
| 4,890 | 40.10084 | 136 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/j2ee/package-info.java | /*
* Copyright 2002-2016 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.
*/
/**
* Pre-authentication support for container-authenticated requests.
* <p>
* It is assumed that standard JEE security has been configured and Spring Security hooks
* into the security methods exposed by {@code HttpServletRequest} to build
* {@code Authentication} object for the user.
*/
package org.springframework.security.web.authentication.preauth.j2ee;
| 989 | 38.6 | 89 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/j2ee/WebXmlMappableAttributesRetriever.java | /*
* Copyright 2002-2016 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.web.authentication.preauth.j2ee;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.security.core.authority.mapping.MappableAttributesRetriever;
import org.springframework.util.Assert;
/**
* This <tt>MappableAttributesRetriever</tt> implementation reads the list of defined J2EE
* roles from a <tt>web.xml</tt> file and returns these from {
* {@link #getMappableAttributes()}.
*
* @author Ruud Senden
* @author Luke Taylor
* @since 2.0
*/
public class WebXmlMappableAttributesRetriever
implements ResourceLoaderAware, MappableAttributesRetriever, InitializingBean {
protected final Log logger = LogFactory.getLog(getClass());
private ResourceLoader resourceLoader;
private Set<String> mappableAttributes;
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Override
public Set<String> getMappableAttributes() {
return this.mappableAttributes;
}
/**
* Loads the web.xml file using the configured <tt>ResourceLoader</tt> and parses the
* role-name elements from it, using these as the set of <tt>mappableAttributes</tt>.
*/
@Override
public void afterPropertiesSet() throws Exception {
Resource webXml = this.resourceLoader.getResource("/WEB-INF/web.xml");
Document doc = getDocument(webXml.getInputStream());
NodeList webApp = doc.getElementsByTagName("web-app");
Assert.isTrue(webApp.getLength() == 1, () -> "Failed to find 'web-app' element in resource" + webXml);
NodeList securityRoles = ((Element) webApp.item(0)).getElementsByTagName("security-role");
List<String> roleNames = getRoleNames(webXml, securityRoles);
this.mappableAttributes = Collections.unmodifiableSet(new HashSet<>(roleNames));
}
private List<String> getRoleNames(Resource webXml, NodeList securityRoles) {
ArrayList<String> roleNames = new ArrayList<>();
for (int i = 0; i < securityRoles.getLength(); i++) {
Element securityRoleElement = (Element) securityRoles.item(i);
NodeList roles = securityRoleElement.getElementsByTagName("role-name");
if (roles.getLength() > 0) {
String roleName = roles.item(0).getTextContent().trim();
roleNames.add(roleName);
this.logger.info("Retrieved role-name '" + roleName + "' from web.xml");
}
else {
this.logger.info("No security-role elements found in " + webXml);
}
}
return roleNames;
}
/**
* @return Document for the specified InputStream
*/
private Document getDocument(InputStream aStream) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(new MyEntityResolver());
return builder.parse(aStream);
}
catch (FactoryConfigurationError | IOException | SAXException | ParserConfigurationException ex) {
throw new RuntimeException("Unable to parse document object", ex);
}
finally {
try {
aStream.close();
}
catch (IOException ex) {
this.logger.warn("Failed to close input stream for web.xml", ex);
}
}
}
/**
* We do not need to resolve external entities, so just return an empty String.
*/
private static final class MyEntityResolver implements EntityResolver {
@Override
public InputSource resolveEntity(String publicId, String systemId) {
return new InputSource(new StringReader(""));
}
}
}
| 4,918 | 32.462585 | 104 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilter.java | /*
* Copyright 2002-2016 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.web.authentication.preauth.j2ee;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.log.LogMessage;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
/**
* This AbstractPreAuthenticatedProcessingFilter implementation is based on the J2EE
* container-based authentication mechanism. It will use the J2EE user principal name as
* the pre-authenticated principal.
*
* @author Ruud Senden
* @since 2.0
*/
public class J2eePreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter {
/**
* Return the J2EE user name.
*/
@Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest httpRequest) {
Object principal = (httpRequest.getUserPrincipal() != null) ? httpRequest.getUserPrincipal().getName() : null;
this.logger.debug(LogMessage.format("PreAuthenticated J2EE principal: %s", principal));
return principal;
}
/**
* For J2EE container-based authentication there is no generic way to retrieve the
* credentials, as such this method returns a fixed dummy value.
*/
@Override
protected Object getPreAuthenticatedCredentials(HttpServletRequest httpRequest) {
return "N/A";
}
}
| 1,893 | 34.074074 | 112 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/x509/package-info.java | /*
* Copyright 2002-2016 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.
*/
/**
* X.509 client certificate authentication support. Hooks into the certificate exposed by
* the servlet container through the {@code jakarta.servlet.request.X509Certificate}
* property.
*/
package org.springframework.security.web.authentication.preauth.x509;
| 889 | 37.695652 | 89 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/x509/X509PrincipalExtractor.java | /*
* Copyright 2002-2016 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.web.authentication.preauth.x509;
import java.security.cert.X509Certificate;
/**
* Obtains the principal from an X509Certificate for use within the framework.
*
* @author Luke Taylor
*/
public interface X509PrincipalExtractor {
/**
* Returns the principal (usually a String) for the given certificate.
*/
Object extractPrincipal(X509Certificate cert);
}
| 1,027 | 29.235294 | 78 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/x509/SubjectDnX509PrincipalExtractor.java | /*
* Copyright 2002-2020 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.web.authentication.preauth.x509;
import java.security.cert.X509Certificate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.core.log.LogMessage;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.util.Assert;
/**
* Obtains the principal from a certificate using a regular expression match against the
* Subject (as returned by a call to {@link X509Certificate#getSubjectDN()}).
* <p>
* The regular expression should contain a single group; for example the default
* expression "CN=(.*?)(?:,|$)" matches the common name field. So "CN=Jimi Hendrix,
* OU=..." will give a user name of "Jimi Hendrix".
* <p>
* The matches are case insensitive. So "emailAddress=(.*?)," will match
* "EMAILADDRESS=jimi@hendrix.org, CN=..." giving a user name "jimi@hendrix.org"
*
* @author Luke Taylor
*/
public class SubjectDnX509PrincipalExtractor implements X509PrincipalExtractor, MessageSourceAware {
protected final Log logger = LogFactory.getLog(getClass());
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private Pattern subjectDnPattern;
public SubjectDnX509PrincipalExtractor() {
setSubjectDnRegex("CN=(.*?)(?:,|$)");
}
@Override
public Object extractPrincipal(X509Certificate clientCert) {
// String subjectDN = clientCert.getSubjectX500Principal().getName();
String subjectDN = clientCert.getSubjectDN().getName();
this.logger.debug(LogMessage.format("Subject DN is '%s'", subjectDN));
Matcher matcher = this.subjectDnPattern.matcher(subjectDN);
if (!matcher.find()) {
throw new BadCredentialsException(this.messages.getMessage("SubjectDnX509PrincipalExtractor.noMatching",
new Object[] { subjectDN }, "No matching pattern was found in subject DN: {0}"));
}
Assert.isTrue(matcher.groupCount() == 1, "Regular expression must contain a single group ");
String username = matcher.group(1);
this.logger.debug(LogMessage.format("Extracted Principal name is '%s'", username));
return username;
}
/**
* Sets the regular expression which will by used to extract the user name from the
* certificate's Subject DN.
* <p>
* It should contain a single group; for example the default expression
* "CN=(.*?)(?:,|$)" matches the common name field. So "CN=Jimi Hendrix, OU=..." will
* give a user name of "Jimi Hendrix".
* <p>
* The matches are case insensitive. So "emailAddress=(.?)," will match
* "EMAILADDRESS=jimi@hendrix.org, CN=..." giving a user name "jimi@hendrix.org"
* @param subjectDnRegex the regular expression to find in the subject
*/
public void setSubjectDnRegex(String subjectDnRegex) {
Assert.hasText(subjectDnRegex, "Regular expression may not be null or empty");
this.subjectDnPattern = Pattern.compile(subjectDnRegex, Pattern.CASE_INSENSITIVE);
}
/**
* @since 5.5
*/
@Override
public void setMessageSource(MessageSource messageSource) {
Assert.notNull(messageSource, "messageSource cannot be null");
this.messages = new MessageSourceAccessor(messageSource);
}
}
| 4,082 | 39.029412 | 107 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/preauth/x509/X509AuthenticationFilter.java | /*
* Copyright 2002-2016 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.web.authentication.preauth.x509;
import java.security.cert.X509Certificate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.log.LogMessage;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
/**
* @author Luke Taylor
*/
public class X509AuthenticationFilter extends AbstractPreAuthenticatedProcessingFilter {
private X509PrincipalExtractor principalExtractor = new SubjectDnX509PrincipalExtractor();
@Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
X509Certificate cert = extractClientCertificate(request);
return (cert != null) ? this.principalExtractor.extractPrincipal(cert) : null;
}
@Override
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
return extractClientCertificate(request);
}
private X509Certificate extractClientCertificate(HttpServletRequest request) {
X509Certificate[] certs = (X509Certificate[]) request.getAttribute("jakarta.servlet.request.X509Certificate");
if (certs != null && certs.length > 0) {
this.logger.debug(LogMessage.format("X.509 client authentication certificate:%s", certs[0]));
return certs[0];
}
this.logger.debug("No client certificate found in request.");
return null;
}
public void setPrincipalExtractor(X509PrincipalExtractor principalExtractor) {
this.principalExtractor = principalExtractor;
}
}
| 2,100 | 34.610169 | 112 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/ui/package-info.java | /*
* Copyright 2002-2016 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.
*/
/**
* Authentication user-interface rendering code. Used to conveniently create an
* appropriate login page when using namespace configuration without defining a login page
* URL.
*/
package org.springframework.security.web.authentication.ui;
| 870 | 36.869565 | 90 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.java | /*
* Copyright 2002-2023 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.web.authentication.ui;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;
import org.springframework.util.Assert;
import org.springframework.web.filter.GenericFilterBean;
import org.springframework.web.util.HtmlUtils;
/**
* For internal use with namespace configuration in the case where a user doesn't
* configure a login page. The configuration code will insert this filter in the chain
* instead.
*
* Will only work if a redirect is used to the login page.
*
* @author Luke Taylor
* @since 2.0
*/
public class DefaultLoginPageGeneratingFilter extends GenericFilterBean {
public static final String DEFAULT_LOGIN_PAGE_URL = "/login";
public static final String ERROR_PARAMETER_NAME = "error";
private String loginPageUrl;
private String logoutSuccessUrl;
private String failureUrl;
private boolean formLoginEnabled;
private boolean oauth2LoginEnabled;
private boolean saml2LoginEnabled;
private String authenticationUrl;
private String usernameParameter;
private String passwordParameter;
private String rememberMeParameter;
private Map<String, String> oauth2AuthenticationUrlToClientName;
private Map<String, String> saml2AuthenticationUrlToProviderName;
private Function<HttpServletRequest, Map<String, String>> resolveHiddenInputs = (request) -> Collections.emptyMap();
public DefaultLoginPageGeneratingFilter() {
}
public DefaultLoginPageGeneratingFilter(UsernamePasswordAuthenticationFilter authFilter) {
this.loginPageUrl = DEFAULT_LOGIN_PAGE_URL;
this.logoutSuccessUrl = DEFAULT_LOGIN_PAGE_URL + "?logout";
this.failureUrl = DEFAULT_LOGIN_PAGE_URL + "?" + ERROR_PARAMETER_NAME;
if (authFilter != null) {
initAuthFilter(authFilter);
}
}
private void initAuthFilter(UsernamePasswordAuthenticationFilter authFilter) {
this.formLoginEnabled = true;
this.usernameParameter = authFilter.getUsernameParameter();
this.passwordParameter = authFilter.getPasswordParameter();
if (authFilter.getRememberMeServices() instanceof AbstractRememberMeServices rememberMeServices) {
this.rememberMeParameter = rememberMeServices.getParameter();
}
}
/**
* Sets a Function used to resolve a Map of the hidden inputs where the key is the
* name of the input and the value is the value of the input. Typically this is used
* to resolve the CSRF token.
* @param resolveHiddenInputs the function to resolve the inputs
*/
public void setResolveHiddenInputs(Function<HttpServletRequest, Map<String, String>> resolveHiddenInputs) {
Assert.notNull(resolveHiddenInputs, "resolveHiddenInputs cannot be null");
this.resolveHiddenInputs = resolveHiddenInputs;
}
public boolean isEnabled() {
return this.formLoginEnabled || this.oauth2LoginEnabled || this.saml2LoginEnabled;
}
public void setLogoutSuccessUrl(String logoutSuccessUrl) {
this.logoutSuccessUrl = logoutSuccessUrl;
}
public String getLoginPageUrl() {
return this.loginPageUrl;
}
public void setLoginPageUrl(String loginPageUrl) {
this.loginPageUrl = loginPageUrl;
}
public void setFailureUrl(String failureUrl) {
this.failureUrl = failureUrl;
}
public void setFormLoginEnabled(boolean formLoginEnabled) {
this.formLoginEnabled = formLoginEnabled;
}
public void setOauth2LoginEnabled(boolean oauth2LoginEnabled) {
this.oauth2LoginEnabled = oauth2LoginEnabled;
}
public void setSaml2LoginEnabled(boolean saml2LoginEnabled) {
this.saml2LoginEnabled = saml2LoginEnabled;
}
public void setAuthenticationUrl(String authenticationUrl) {
this.authenticationUrl = authenticationUrl;
}
public void setUsernameParameter(String usernameParameter) {
this.usernameParameter = usernameParameter;
}
public void setPasswordParameter(String passwordParameter) {
this.passwordParameter = passwordParameter;
}
public void setRememberMeParameter(String rememberMeParameter) {
this.rememberMeParameter = rememberMeParameter;
}
public void setOauth2AuthenticationUrlToClientName(Map<String, String> oauth2AuthenticationUrlToClientName) {
this.oauth2AuthenticationUrlToClientName = oauth2AuthenticationUrlToClientName;
}
public void setSaml2AuthenticationUrlToProviderName(Map<String, String> saml2AuthenticationUrlToProviderName) {
this.saml2AuthenticationUrlToProviderName = saml2AuthenticationUrlToProviderName;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
}
private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
boolean loginError = isErrorPage(request);
boolean logoutSuccess = isLogoutSuccess(request);
if (isLoginUrlRequest(request) || loginError || logoutSuccess) {
String loginPageHtml = generateLoginPageHtml(request, loginError, logoutSuccess);
response.setContentType("text/html;charset=UTF-8");
response.setContentLength(loginPageHtml.getBytes(StandardCharsets.UTF_8).length);
response.getWriter().write(loginPageHtml);
return;
}
chain.doFilter(request, response);
}
private String generateLoginPageHtml(HttpServletRequest request, boolean loginError, boolean logoutSuccess) {
String errorMsg = loginError ? getLoginErrorMessage(request) : "Invalid credentials";
String contextPath = request.getContextPath();
StringBuilder sb = new StringBuilder();
sb.append("<!DOCTYPE html>\n");
sb.append("<html lang=\"en\">\n");
sb.append(" <head>\n");
sb.append(" <meta charset=\"utf-8\">\n");
sb.append(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n");
sb.append(" <meta name=\"description\" content=\"\">\n");
sb.append(" <meta name=\"author\" content=\"\">\n");
sb.append(" <title>Please sign in</title>\n");
sb.append(" <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css\" "
+ "rel=\"stylesheet\" integrity=\"sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M\" crossorigin=\"anonymous\">\n");
sb.append(" <link href=\"https://getbootstrap.com/docs/4.0/examples/signin/signin.css\" "
+ "rel=\"stylesheet\" crossorigin=\"anonymous\"/>\n");
sb.append(" </head>\n");
sb.append(" <body>\n");
sb.append(" <div class=\"container\">\n");
if (this.formLoginEnabled) {
sb.append(" <form class=\"form-signin\" method=\"post\" action=\"" + contextPath
+ this.authenticationUrl + "\">\n");
sb.append(" <h2 class=\"form-signin-heading\">Please sign in</h2>\n");
sb.append(createError(loginError, errorMsg) + createLogoutSuccess(logoutSuccess) + " <p>\n");
sb.append(" <label for=\"username\" class=\"sr-only\">Username</label>\n");
sb.append(" <input type=\"text\" id=\"username\" name=\"" + this.usernameParameter
+ "\" class=\"form-control\" placeholder=\"Username\" required autofocus>\n");
sb.append(" </p>\n");
sb.append(" <p>\n");
sb.append(" <label for=\"password\" class=\"sr-only\">Password</label>\n");
sb.append(" <input type=\"password\" id=\"password\" name=\"" + this.passwordParameter
+ "\" class=\"form-control\" placeholder=\"Password\" required>\n");
sb.append(" </p>\n");
sb.append(createRememberMe(this.rememberMeParameter) + renderHiddenInputs(request));
sb.append(" <button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\">Sign in</button>\n");
sb.append(" </form>\n");
}
if (this.oauth2LoginEnabled) {
sb.append("<h2 class=\"form-signin-heading\">Login with OAuth 2.0</h2>");
sb.append(createError(loginError, errorMsg));
sb.append(createLogoutSuccess(logoutSuccess));
sb.append("<table class=\"table table-striped\">\n");
for (Map.Entry<String, String> clientAuthenticationUrlToClientName : this.oauth2AuthenticationUrlToClientName
.entrySet()) {
sb.append(" <tr><td>");
String url = clientAuthenticationUrlToClientName.getKey();
sb.append("<a href=\"").append(contextPath).append(url).append("\">");
String clientName = HtmlUtils.htmlEscape(clientAuthenticationUrlToClientName.getValue());
sb.append(clientName);
sb.append("</a>");
sb.append("</td></tr>\n");
}
sb.append("</table>\n");
}
if (this.saml2LoginEnabled) {
sb.append("<h2 class=\"form-signin-heading\">Login with SAML 2.0</h2>");
sb.append(createError(loginError, errorMsg));
sb.append(createLogoutSuccess(logoutSuccess));
sb.append("<table class=\"table table-striped\">\n");
for (Map.Entry<String, String> relyingPartyUrlToName : this.saml2AuthenticationUrlToProviderName
.entrySet()) {
sb.append(" <tr><td>");
String url = relyingPartyUrlToName.getKey();
sb.append("<a href=\"").append(contextPath).append(url).append("\">");
String partyName = HtmlUtils.htmlEscape(relyingPartyUrlToName.getValue());
sb.append(partyName);
sb.append("</a>");
sb.append("</td></tr>\n");
}
sb.append("</table>\n");
}
sb.append("</div>\n");
sb.append("</body></html>");
return sb.toString();
}
private String getLoginErrorMessage(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session != null &&
session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION) instanceof AuthenticationException exception) {
return exception.getMessage();
}
return "Invalid credentials";
}
private String renderHiddenInputs(HttpServletRequest request) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> input : this.resolveHiddenInputs.apply(request).entrySet()) {
sb.append("<input name=\"");
sb.append(input.getKey());
sb.append("\" type=\"hidden\" value=\"");
sb.append(input.getValue());
sb.append("\" />\n");
}
return sb.toString();
}
private String createRememberMe(String paramName) {
if (paramName == null) {
return "";
}
return "<p><input type='checkbox' name='" + paramName + "'/> Remember me on this computer.</p>\n";
}
private boolean isLogoutSuccess(HttpServletRequest request) {
return this.logoutSuccessUrl != null && matches(request, this.logoutSuccessUrl);
}
private boolean isLoginUrlRequest(HttpServletRequest request) {
return matches(request, this.loginPageUrl);
}
private boolean isErrorPage(HttpServletRequest request) {
return matches(request, this.failureUrl);
}
private String createError(boolean isError, String message) {
if (!isError) {
return "";
}
return "<div class=\"alert alert-danger\" role=\"alert\">" + HtmlUtils.htmlEscape(message) + "</div>";
}
private String createLogoutSuccess(boolean isLogoutSuccess) {
if (!isLogoutSuccess) {
return "";
}
return "<div class=\"alert alert-success\" role=\"alert\">You have been signed out</div>";
}
private boolean matches(HttpServletRequest request, String url) {
if (!"GET".equals(request.getMethod()) || url == null) {
return false;
}
String uri = request.getRequestURI();
int pathParamIndex = uri.indexOf(';');
if (pathParamIndex > 0) {
// strip everything after the first semi-colon
uri = uri.substring(0, pathParamIndex);
}
if (request.getQueryString() != null) {
uri += "?" + request.getQueryString();
}
if ("".equals(request.getContextPath())) {
return uri.equals(url);
}
return uri.equals(request.getContextPath() + url);
}
}
| 12,851 | 36.68915 | 143 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLogoutPageGeneratingFilter.java | /*
* Copyright 2002-2018 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.web.authentication.ui;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.log.LogMessage;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* Generates a default log out page.
*
* @author Rob Winch
* @since 5.1
*/
public class DefaultLogoutPageGeneratingFilter extends OncePerRequestFilter {
private RequestMatcher matcher = new AntPathRequestMatcher("/logout", "GET");
private Function<HttpServletRequest, Map<String, String>> resolveHiddenInputs = (request) -> Collections.emptyMap();
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (this.matcher.matches(request)) {
renderLogout(request, response);
}
else {
if (logger.isTraceEnabled()) {
logger.trace(LogMessage.format("Did not render default logout page since request did not match [%s]",
this.matcher));
}
filterChain.doFilter(request, response);
}
}
private void renderLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("<!DOCTYPE html>\n");
sb.append("<html lang=\"en\">\n");
sb.append(" <head>\n");
sb.append(" <meta charset=\"utf-8\">\n");
sb.append(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n");
sb.append(" <meta name=\"description\" content=\"\">\n");
sb.append(" <meta name=\"author\" content=\"\">\n");
sb.append(" <title>Confirm Log Out?</title>\n");
sb.append(" <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css\" "
+ "rel=\"stylesheet\" integrity=\"sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M\" "
+ "crossorigin=\"anonymous\">\n");
sb.append(" <link href=\"https://getbootstrap.com/docs/4.0/examples/signin/signin.css\" "
+ "rel=\"stylesheet\" crossorigin=\"anonymous\"/>\n");
sb.append(" </head>\n");
sb.append(" <body>\n");
sb.append(" <div class=\"container\">\n");
sb.append(" <form class=\"form-signin\" method=\"post\" action=\"" + request.getContextPath()
+ "/logout\">\n");
sb.append(" <h2 class=\"form-signin-heading\">Are you sure you want to log out?</h2>\n");
sb.append(renderHiddenInputs(request)
+ " <button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\">Log Out</button>\n");
sb.append(" </form>\n");
sb.append(" </div>\n");
sb.append(" </body>\n");
sb.append("</html>");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(sb.toString());
}
/**
* Sets a Function used to resolve a Map of the hidden inputs where the key is the
* name of the input and the value is the value of the input. Typically this is used
* to resolve the CSRF token.
* @param resolveHiddenInputs the function to resolve the inputs
*/
public void setResolveHiddenInputs(Function<HttpServletRequest, Map<String, String>> resolveHiddenInputs) {
Assert.notNull(resolveHiddenInputs, "resolveHiddenInputs cannot be null");
this.resolveHiddenInputs = resolveHiddenInputs;
}
private String renderHiddenInputs(HttpServletRequest request) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> input : this.resolveHiddenInputs.apply(request).entrySet()) {
sb.append("<input name=\"");
sb.append(input.getKey());
sb.append("\" type=\"hidden\" value=\"");
sb.append(input.getValue());
sb.append("\" />\n");
}
return sb.toString();
}
}
| 4,708 | 39.247863 | 117 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/switchuser/package-info.java | /*
* Copyright 2002-2016 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.
*/
/**
* Provides HTTP-based "switch user" (su) capabilities.
*/
package org.springframework.security.web.authentication.switchuser;
| 755 | 35 | 75 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/switchuser/AuthenticationSwitchUserEvent.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.web.authentication.switchuser;
import org.springframework.security.authentication.event.AbstractAuthenticationEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
/**
* Application event which indicates that a user context switch.
*
* @author Mark St.Godard
*/
public class AuthenticationSwitchUserEvent extends AbstractAuthenticationEvent {
private final UserDetails targetUser;
/**
* Switch user context event constructor
* @param authentication The current <code>Authentication</code> object
* @param targetUser The target user
*/
public AuthenticationSwitchUserEvent(Authentication authentication, UserDetails targetUser) {
super(authentication);
this.targetUser = targetUser;
}
public UserDetails getTargetUser() {
return this.targetUser;
}
}
| 1,519 | 31.340426 | 94 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/switchuser/SwitchUserGrantedAuthority.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.web.authentication.switchuser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.util.Assert;
/**
* Custom {@code GrantedAuthority} used by
* {@link org.springframework.security.web.authentication.switchuser.SwitchUserFilter}
* <p>
* Stores the {@code Authentication} object of the original user to be used later when
* 'exiting' from a user switch.
*
* @author Mark St.Godard
* @see org.springframework.security.web.authentication.switchuser.SwitchUserFilter
*/
public final class SwitchUserGrantedAuthority implements GrantedAuthority {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final String role;
private final Authentication source;
public SwitchUserGrantedAuthority(String role, Authentication source) {
Assert.notNull(role, "role cannot be null");
Assert.notNull(source, "source cannot be null");
this.role = role;
this.source = source;
}
/**
* Returns the original user associated with a successful user switch.
* @return The original <code>Authentication</code> object of the switched user.
*/
public Authentication getSource() {
return this.source;
}
@Override
public String getAuthority() {
return this.role;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof SwitchUserGrantedAuthority) {
SwitchUserGrantedAuthority swa = (SwitchUserGrantedAuthority) obj;
return this.role.equals(swa.role) && this.source.equals(swa.source);
}
return false;
}
@Override
public int hashCode() {
int result = this.role.hashCode();
result = 31 * result + this.source.hashCode();
return result;
}
@Override
public String toString() {
return "Switch User Authority [" + this.role + "," + this.source + "]";
}
}
| 2,618 | 29.103448 | 91 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.web.authentication.switchuser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.core.log.LogMessage;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
import org.springframework.web.filter.GenericFilterBean;
import org.springframework.web.util.UrlPathHelper;
/**
* Switch User processing filter responsible for user context switching.
* <p>
* This filter is similar to Unix 'su' however for Spring Security-managed web
* applications. A common use-case for this feature is the ability to allow
* higher-authority users (e.g. ROLE_ADMIN) to switch to a regular user (e.g. ROLE_USER).
* <p>
* This filter assumes that the user performing the switch will be required to be logged
* in as normal (i.e. as a ROLE_ADMIN user). The user will then access a page/controller
* that enables the administrator to specify who they wish to become (see
* <code>switchUserUrl</code>).
* <p>
* <b>Note: This URL will be required to have appropriate security constraints configured
* so that only users of that role can access it (e.g. ROLE_ADMIN).</b>
* <p>
* On a successful switch, the user's <code>SecurityContext</code> will be updated to
* reflect the specified user and will also contain an additional
* {@link org.springframework.security.web.authentication.switchuser.SwitchUserGrantedAuthority}
* which contains the original user. Before switching, a check will be made on whether the
* user is already currently switched, and any current switch will be exited to prevent
* "nested" switches.
* <p>
* To 'exit' from a user context, the user needs to access a URL (see
* <code>exitUserUrl</code>) that will switch back to the original user as identified by
* the <code>ROLE_PREVIOUS_ADMINISTRATOR</code>.
* <p>
* To configure the Switch User Processing Filter, create a bean definition for the Switch
* User processing filter and add to the filterChainProxy. Note that the filter must come
* <b>after</b> the <tt>FilterSecurityInteceptor</tt> in the chain, in order to apply the
* correct constraints to the <tt>switchUserUrl</tt>. Example:
*
* <pre>
* <bean id="switchUserProcessingFilter" class="org.springframework.security.web.authentication.switchuser.SwitchUserFilter">
* <property name="userDetailsService" ref="userDetailsService" />
* <property name="switchUserUrl" value="/login/impersonate" />
* <property name="exitUserUrl" value="/logout/impersonate" />
* <property name="targetUrl" value="/index.jsp" />
* </bean>
* </pre>
*
* @author Mark St.Godard
* @see SwitchUserGrantedAuthority
*/
public class SwitchUserFilter extends GenericFilterBean implements ApplicationEventPublisherAware, MessageSourceAware {
public static final String SPRING_SECURITY_SWITCH_USERNAME_KEY = "username";
public static final String ROLE_PREVIOUS_ADMINISTRATOR = "ROLE_PREVIOUS_ADMINISTRATOR";
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private ApplicationEventPublisher eventPublisher;
private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private RequestMatcher exitUserMatcher = createMatcher("/logout/impersonate");
private RequestMatcher switchUserMatcher = createMatcher("/login/impersonate");
private String targetUrl;
private String switchFailureUrl;
private String usernameParameter = SPRING_SECURITY_SWITCH_USERNAME_KEY;
private String switchAuthorityRole = ROLE_PREVIOUS_ADMINISTRATOR;
private SwitchUserAuthorityChanger switchUserAuthorityChanger;
private UserDetailsService userDetailsService;
private UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker();
private AuthenticationSuccessHandler successHandler;
private AuthenticationFailureHandler failureHandler;
private SecurityContextRepository securityContextRepository = new HttpSessionSecurityContextRepository();
@Override
public void afterPropertiesSet() {
Assert.notNull(this.userDetailsService, "userDetailsService must be specified");
Assert.isTrue(this.successHandler != null || this.targetUrl != null,
"You must set either a successHandler or the targetUrl");
if (this.targetUrl != null) {
Assert.isNull(this.successHandler, "You cannot set both successHandler and targetUrl");
this.successHandler = new SimpleUrlAuthenticationSuccessHandler(this.targetUrl);
}
if (this.failureHandler == null) {
this.failureHandler = (this.switchFailureUrl != null)
? new SimpleUrlAuthenticationFailureHandler(this.switchFailureUrl)
: new SimpleUrlAuthenticationFailureHandler();
}
else {
Assert.isNull(this.switchFailureUrl, "You cannot set both a switchFailureUrl and a failureHandler");
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
}
private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
// check for switch or exit request
if (requiresSwitchUser(request)) {
// if set, attempt switch and store original
try {
Authentication targetUser = attemptSwitchUser(request);
// update the current context to the new target user
SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
context.setAuthentication(targetUser);
this.securityContextHolderStrategy.setContext(context);
this.logger.debug(LogMessage.format("Set SecurityContextHolder to %s", targetUser));
this.securityContextRepository.saveContext(context, request, response);
// redirect to target url
this.successHandler.onAuthenticationSuccess(request, response, targetUser);
}
catch (AuthenticationException ex) {
this.logger.debug("Failed to switch user", ex);
this.failureHandler.onAuthenticationFailure(request, response, ex);
}
return;
}
if (requiresExitUser(request)) {
// get the original authentication object (if exists)
Authentication originalUser = attemptExitUser(request);
// update the current context back to the original user
SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
context.setAuthentication(originalUser);
this.securityContextHolderStrategy.setContext(context);
this.logger.debug(LogMessage.format("Set SecurityContextHolder to %s", originalUser));
this.securityContextRepository.saveContext(context, request, response);
// redirect to target url
this.successHandler.onAuthenticationSuccess(request, response, originalUser);
return;
}
this.logger.trace(LogMessage.format("Did not attempt to switch user since request did not match [%s] or [%s]",
this.switchUserMatcher, this.exitUserMatcher));
chain.doFilter(request, response);
}
/**
* Attempt to switch to another user. If the user does not exist or is not active,
* return null.
* @return The new <code>Authentication</code> request if successfully switched to
* another user, <code>null</code> otherwise.
* @throws UsernameNotFoundException If the target user is not found.
* @throws LockedException if the account is locked.
* @throws DisabledException If the target user is disabled.
* @throws AccountExpiredException If the target user account is expired.
* @throws CredentialsExpiredException If the target user credentials are expired.
*/
protected Authentication attemptSwitchUser(HttpServletRequest request) throws AuthenticationException {
UsernamePasswordAuthenticationToken targetUserRequest;
String username = request.getParameter(this.usernameParameter);
username = (username != null) ? username : "";
this.logger.debug(LogMessage.format("Attempting to switch to user [%s]", username));
UserDetails targetUser = this.userDetailsService.loadUserByUsername(username);
this.userDetailsChecker.check(targetUser);
// OK, create the switch user token
targetUserRequest = createSwitchUserToken(request, targetUser);
// publish event
if (this.eventPublisher != null) {
this.eventPublisher.publishEvent(new AuthenticationSwitchUserEvent(
this.securityContextHolderStrategy.getContext().getAuthentication(), targetUser));
}
return targetUserRequest;
}
/**
* Attempt to exit from an already switched user.
* @param request The http servlet request
* @return The original <code>Authentication</code> object or <code>null</code>
* otherwise.
* @throws AuthenticationCredentialsNotFoundException If no
* <code>Authentication</code> associated with this request.
*/
protected Authentication attemptExitUser(HttpServletRequest request)
throws AuthenticationCredentialsNotFoundException {
// need to check to see if the current user has a SwitchUserGrantedAuthority
Authentication current = this.securityContextHolderStrategy.getContext().getAuthentication();
if (current == null) {
throw new AuthenticationCredentialsNotFoundException(this.messages
.getMessage("SwitchUserFilter.noCurrentUser", "No current user associated with this request"));
}
// check to see if the current user did actual switch to another user
// if so, get the original source user so we can switch back
Authentication original = getSourceAuthentication(current);
if (original == null) {
this.logger.debug("Failed to find original user");
throw new AuthenticationCredentialsNotFoundException(this.messages
.getMessage("SwitchUserFilter.noOriginalAuthentication", "Failed to find original user"));
}
// get the source user details
UserDetails originalUser = null;
Object obj = original.getPrincipal();
if ((obj != null) && obj instanceof UserDetails) {
originalUser = (UserDetails) obj;
}
// publish event
if (this.eventPublisher != null) {
this.eventPublisher.publishEvent(new AuthenticationSwitchUserEvent(current, originalUser));
}
return original;
}
/**
* Create a switch user token that contains an additional <tt>GrantedAuthority</tt>
* that contains the original <code>Authentication</code> object.
* @param request The http servlet request.
* @param targetUser The target user
* @return The authentication token
*
* @see SwitchUserGrantedAuthority
*/
private UsernamePasswordAuthenticationToken createSwitchUserToken(HttpServletRequest request,
UserDetails targetUser) {
UsernamePasswordAuthenticationToken targetUserRequest;
// grant an additional authority that contains the original Authentication object
// which will be used to 'exit' from the current switched user.
Authentication currentAuthentication = getCurrentAuthentication(request);
GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(this.switchAuthorityRole,
currentAuthentication);
// get the original authorities
Collection<? extends GrantedAuthority> orig = targetUser.getAuthorities();
// Allow subclasses to change the authorities to be granted
if (this.switchUserAuthorityChanger != null) {
orig = this.switchUserAuthorityChanger.modifyGrantedAuthorities(targetUser, currentAuthentication, orig);
}
// add the new switch user authority
List<GrantedAuthority> newAuths = new ArrayList<>(orig);
newAuths.add(switchAuthority);
// create the new authentication token
targetUserRequest = UsernamePasswordAuthenticationToken.authenticated(targetUser, targetUser.getPassword(),
newAuths);
// set details
targetUserRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
return targetUserRequest;
}
private Authentication getCurrentAuthentication(HttpServletRequest request) {
try {
// SEC-1763. Check first if we are already switched.
return attemptExitUser(request);
}
catch (AuthenticationCredentialsNotFoundException ex) {
return this.securityContextHolderStrategy.getContext().getAuthentication();
}
}
/**
* Find the original <code>Authentication</code> object from the current user's
* granted authorities. A successfully switched user should have a
* <code>SwitchUserGrantedAuthority</code> that contains the original source user
* <code>Authentication</code> object.
* @param current The current <code>Authentication</code> object
* @return The source user <code>Authentication</code> object or <code>null</code>
* otherwise.
*/
private Authentication getSourceAuthentication(Authentication current) {
Authentication original = null;
// iterate over granted authorities and find the 'switch user' authority
Collection<? extends GrantedAuthority> authorities = current.getAuthorities();
for (GrantedAuthority auth : authorities) {
// check for switch user type of authority
if (auth instanceof SwitchUserGrantedAuthority) {
original = ((SwitchUserGrantedAuthority) auth).getSource();
this.logger.debug(LogMessage.format("Found original switch user granted authority [%s]", original));
}
}
return original;
}
/**
* Checks the request URI for the presence of <tt>exitUserUrl</tt>.
* @param request The http servlet request
* @return <code>true</code> if the request requires a exit user, <code>false</code>
* otherwise.
*
* @see SwitchUserFilter#setExitUserUrl(String)
*/
protected boolean requiresExitUser(HttpServletRequest request) {
return this.exitUserMatcher.matches(request);
}
/**
* Checks the request URI for the presence of <tt>switchUserUrl</tt>.
* @param request The http servlet request
* @return <code>true</code> if the request requires a switch, <code>false</code>
* otherwise.
*
* @see SwitchUserFilter#setSwitchUserUrl(String)
*/
protected boolean requiresSwitchUser(HttpServletRequest request) {
return this.switchUserMatcher.matches(request);
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher) throws BeansException {
this.eventPublisher = eventPublisher;
}
public void setAuthenticationDetailsSource(
AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required");
this.authenticationDetailsSource = authenticationDetailsSource;
}
@Override
public void setMessageSource(MessageSource messageSource) {
Assert.notNull(messageSource, "messageSource cannot be null");
this.messages = new MessageSourceAccessor(messageSource);
}
/**
* Sets the authentication data access object.
* @param userDetailsService The <tt>UserDetailsService</tt> which will be used to
* load information for the user that is being switched to.
*/
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
/**
* Set the URL to respond to exit user processing. This is a shortcut for
* {@link #setExitUserMatcher(RequestMatcher)}.
* @param exitUserUrl The exit user URL.
*/
public void setExitUserUrl(String exitUserUrl) {
Assert.isTrue(UrlUtils.isValidRedirectUrl(exitUserUrl),
"exitUserUrl cannot be empty and must be a valid redirect URL");
this.exitUserMatcher = createMatcher(exitUserUrl);
}
/**
* Set the matcher to respond to exit user processing.
* @param exitUserMatcher The exit matcher to use.
*/
public void setExitUserMatcher(RequestMatcher exitUserMatcher) {
Assert.notNull(exitUserMatcher, "exitUserMatcher cannot be null");
this.exitUserMatcher = exitUserMatcher;
}
/**
* Set the URL to respond to switch user processing. This is a shortcut for
* {@link #setSwitchUserMatcher(RequestMatcher)}
* @param switchUserUrl The switch user URL.
*/
public void setSwitchUserUrl(String switchUserUrl) {
Assert.isTrue(UrlUtils.isValidRedirectUrl(switchUserUrl),
"switchUserUrl cannot be empty and must be a valid redirect URL");
this.switchUserMatcher = createMatcher(switchUserUrl);
}
/**
* Set the matcher to respond to switch user processing.
* @param switchUserMatcher The switch user matcher.
*/
public void setSwitchUserMatcher(RequestMatcher switchUserMatcher) {
Assert.notNull(switchUserMatcher, "switchUserMatcher cannot be null");
this.switchUserMatcher = switchUserMatcher;
}
/**
* Sets the URL to go to after a successful switch / exit user request. Use
* {@link #setSuccessHandler(AuthenticationSuccessHandler) setSuccessHandler} instead
* if you need more customized behaviour.
* @param targetUrl The target url.
*/
public void setTargetUrl(String targetUrl) {
this.targetUrl = targetUrl;
}
/**
* Used to define custom behaviour on a successful switch or exit user.
* <p>
* Can be used instead of setting <tt>targetUrl</tt>.
*/
public void setSuccessHandler(AuthenticationSuccessHandler successHandler) {
Assert.notNull(successHandler, "successHandler cannot be null");
this.successHandler = successHandler;
}
/**
* Sets the URL to which a user should be redirected if the switch fails. For example,
* this might happen because the account they are attempting to switch to is invalid
* (the user doesn't exist, account is locked etc).
* <p>
* If not set, an error message will be written to the response.
* <p>
* Use {@link #setFailureHandler(AuthenticationFailureHandler) failureHandler} instead
* if you need more customized behaviour.
* @param switchFailureUrl the url to redirect to.
*/
public void setSwitchFailureUrl(String switchFailureUrl) {
Assert.isTrue(UrlUtils.isValidRedirectUrl(switchFailureUrl), "switchFailureUrl must be a valid redirect URL");
this.switchFailureUrl = switchFailureUrl;
}
/**
* Used to define custom behaviour when a switch fails.
* <p>
* Can be used instead of setting <tt>switchFailureUrl</tt>.
*/
public void setFailureHandler(AuthenticationFailureHandler failureHandler) {
Assert.notNull(failureHandler, "failureHandler cannot be null");
this.failureHandler = failureHandler;
}
/**
* @param switchUserAuthorityChanger to use to fine-tune the authorities granted to
* subclasses (may be null if SwitchUserFilter should not fine-tune the authorities)
*/
public void setSwitchUserAuthorityChanger(SwitchUserAuthorityChanger switchUserAuthorityChanger) {
this.switchUserAuthorityChanger = switchUserAuthorityChanger;
}
/**
* Sets the {@link UserDetailsChecker} that is called on the target user whenever the
* user is switched.
* @param userDetailsChecker the {@link UserDetailsChecker} that checks the status of
* the user that is being switched to. Defaults to
* {@link AccountStatusUserDetailsChecker}.
*/
public void setUserDetailsChecker(UserDetailsChecker userDetailsChecker) {
this.userDetailsChecker = userDetailsChecker;
}
/**
* Allows the parameter containing the username to be customized.
* @param usernameParameter the parameter name. Defaults to {@code username}
*/
public void setUsernameParameter(String usernameParameter) {
this.usernameParameter = usernameParameter;
}
/**
* Allows the role of the switchAuthority to be customized.
* @param switchAuthorityRole the role name. Defaults to
* {@link #ROLE_PREVIOUS_ADMINISTRATOR}
*/
public void setSwitchAuthorityRole(String switchAuthorityRole) {
Assert.notNull(switchAuthorityRole, "switchAuthorityRole cannot be null");
this.switchAuthorityRole = switchAuthorityRole;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
/**
* Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on
* switch user success. The default is
* {@link RequestAttributeSecurityContextRepository}.
* @param securityContextRepository the {@link SecurityContextRepository} to use.
* Cannot be null.
* @since 5.7.7
*/
public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) {
Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
this.securityContextRepository = securityContextRepository;
}
private static RequestMatcher createMatcher(String pattern) {
return new AntPathRequestMatcher(pattern, "POST", true, new UrlPathHelper());
}
}
| 24,335 | 43.007233 | 131 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/switchuser/SwitchUserAuthorityChanger.java | /*
* Copyright 2002-2016 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.web.authentication.switchuser;
import java.util.Collection;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
/**
* Allows subclasses to modify the {@link GrantedAuthority} list that will be assigned to
* the principal when they assume the identity of a different principal.
*
* <p>
* Configured against the {@link SwitchUserFilter}.
*
* @author Ben Alex
*
*/
public interface SwitchUserAuthorityChanger {
/**
* Allow subclasses to add or remove authorities that will be granted when in switch
* user mode.
* @param targetUser the UserDetails representing the identity being switched to
* @param currentAuthentication the current Authentication of the principal performing
* the switching
* @param authoritiesToBeGranted all
* {@link org.springframework.security.core.GrantedAuthority} instances to be granted
* to the user, excluding the special "switch user" authority that is used internally
* (guaranteed never null)
* @return the modified list of granted authorities.
*/
Collection<? extends GrantedAuthority> modifyGrantedAuthorities(UserDetails targetUser,
Authentication currentAuthentication, Collection<? extends GrantedAuthority> authoritiesToBeGranted);
}
| 2,001 | 36.773585 | 104 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/logout/package-info.java | /*
* Copyright 2002-2016 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.
*/
/**
* Logout functionality based around a filter which handles a specific logout URL.
*/
package org.springframework.security.web.authentication.logout;
| 778 | 36.095238 | 82 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandler.java | /*
* Copyright 2002-2016 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.web.authentication.logout;
import java.util.Arrays;
import java.util.List;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
/**
* Performs a logout through all the {@link LogoutHandler} implementations. If any
* exception is thrown by
* {@link #logout(HttpServletRequest, HttpServletResponse, Authentication)}, no additional
* LogoutHandler are invoked.
*
* @author Eddú Meléndez
* @since 4.2.0
*/
public final class CompositeLogoutHandler implements LogoutHandler {
private final List<LogoutHandler> logoutHandlers;
public CompositeLogoutHandler(LogoutHandler... logoutHandlers) {
Assert.notEmpty(logoutHandlers, "LogoutHandlers are required");
this.logoutHandlers = Arrays.asList(logoutHandlers);
}
public CompositeLogoutHandler(List<LogoutHandler> logoutHandlers) {
Assert.notEmpty(logoutHandlers, "LogoutHandlers are required");
this.logoutHandlers = logoutHandlers;
}
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
for (LogoutHandler handler : this.logoutHandlers) {
handler.logout(request, response, authentication);
}
}
}
| 1,947 | 32.016949 | 110 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/logout/DelegatingLogoutSuccessHandler.java | /*
* Copyright 2002-2016 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.web.authentication.logout;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
/**
* Delegates to logout handlers based on matched request matchers
*
* @author Shazin Sadakath
* @author Rob Winch
* @since 4.1
*/
public class DelegatingLogoutSuccessHandler implements LogoutSuccessHandler {
private final LinkedHashMap<RequestMatcher, LogoutSuccessHandler> matcherToHandler;
private LogoutSuccessHandler defaultLogoutSuccessHandler;
public DelegatingLogoutSuccessHandler(LinkedHashMap<RequestMatcher, LogoutSuccessHandler> matcherToHandler) {
Assert.notEmpty(matcherToHandler, "matcherToHandler cannot be null");
this.matcherToHandler = matcherToHandler;
}
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
for (Map.Entry<RequestMatcher, LogoutSuccessHandler> entry : this.matcherToHandler.entrySet()) {
RequestMatcher matcher = entry.getKey();
if (matcher.matches(request)) {
LogoutSuccessHandler handler = entry.getValue();
handler.onLogoutSuccess(request, response, authentication);
return;
}
}
if (this.defaultLogoutSuccessHandler != null) {
this.defaultLogoutSuccessHandler.onLogoutSuccess(request, response, authentication);
}
}
/**
* Sets the default {@link LogoutSuccessHandler} if no other handlers available
* @param defaultLogoutSuccessHandler the defaultLogoutSuccessHandler to set
*/
public void setDefaultLogoutSuccessHandler(LogoutSuccessHandler defaultLogoutSuccessHandler) {
this.defaultLogoutSuccessHandler = defaultLogoutSuccessHandler;
}
}
| 2,642 | 34.716216 | 117 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutSuccessHandler.java | /*
* Copyright 2002-2016 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.web.authentication.logout;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
/**
* Strategy that is called after a successful logout by the {@link LogoutFilter}, to
* handle redirection or forwarding to the appropriate destination.
* <p>
* Note that the interface is almost the same as {@link LogoutHandler} but may raise an
* exception. <tt>LogoutHandler</tt> implementations expect to be invoked to perform
* necessary cleanup, so should not throw exceptions.
*
* @author Luke Taylor
* @since 3.0
*/
public interface LogoutSuccessHandler {
void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException;
}
| 1,545 | 34.136364 | 110 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/logout/SecurityContextLogoutHandler.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.web.authentication.logout;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogMessage;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.util.Assert;
/**
* Performs a logout by modifying the
* {@link org.springframework.security.core.context.SecurityContextHolder}.
* <p>
* Will also invalidate the {@link HttpSession} if {@link #isInvalidateHttpSession()} is
* {@code true} and the session is not {@code null}.
* <p>
* Will also remove the {@link Authentication} from the current {@link SecurityContext} if
* {@link #clearAuthentication} is set to true (default).
*
* @author Ben Alex
* @author Rob Winch
*/
public class SecurityContextLogoutHandler implements LogoutHandler {
protected final Log logger = LogFactory.getLog(this.getClass());
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private boolean invalidateHttpSession = true;
private boolean clearAuthentication = true;
private SecurityContextRepository securityContextRepository = new HttpSessionSecurityContextRepository();
/**
* Requires the request to be passed in.
* @param request from which to obtain a HTTP session (cannot be null)
* @param response not used (can be <code>null</code>)
* @param authentication not used (can be <code>null</code>)
*/
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
Assert.notNull(request, "HttpServletRequest required");
if (this.invalidateHttpSession) {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
if (this.logger.isDebugEnabled()) {
this.logger.debug(LogMessage.format("Invalidated session %s", session.getId()));
}
}
}
SecurityContext context = this.securityContextHolderStrategy.getContext();
this.securityContextHolderStrategy.clearContext();
if (this.clearAuthentication) {
context.setAuthentication(null);
}
SecurityContext emptyContext = this.securityContextHolderStrategy.createEmptyContext();
this.securityContextRepository.saveContext(emptyContext, request, response);
}
public boolean isInvalidateHttpSession() {
return this.invalidateHttpSession;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
/**
* Causes the {@link HttpSession} to be invalidated when this {@link LogoutHandler} is
* invoked. Defaults to true.
* @param invalidateHttpSession true if you wish the session to be invalidated
* (default) or false if it should not be.
*/
public void setInvalidateHttpSession(boolean invalidateHttpSession) {
this.invalidateHttpSession = invalidateHttpSession;
}
/**
* If true, removes the {@link Authentication} from the {@link SecurityContext} to
* prevent issues with concurrent requests.
* @param clearAuthentication true if you wish to clear the {@link Authentication}
* from the {@link SecurityContext} (default) or false if the {@link Authentication}
* should not be removed.
*/
public void setClearAuthentication(boolean clearAuthentication) {
this.clearAuthentication = clearAuthentication;
}
/**
* Sets the {@link SecurityContextRepository} to use. Default is
* {@link HttpSessionSecurityContextRepository}.
* @param securityContextRepository the {@link SecurityContextRepository} to use.
*/
public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) {
Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
this.securityContextRepository = securityContextRepository;
}
}
| 5,328 | 38.768657 | 110 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/logout/HttpStatusReturningLogoutSuccessHandler.java | /*
* Copyright 2002-2016 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.web.authentication.logout;
import java.io.IOException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
/**
* Implementation of the {@link LogoutSuccessHandler}. By default returns an HTTP status
* code of {@code 200}. This is useful in REST-type scenarios where a redirect upon a
* successful logout is not desired.
*
* @author Gunnar Hillert
* @since 4.0.2
*/
public class HttpStatusReturningLogoutSuccessHandler implements LogoutSuccessHandler {
private final HttpStatus httpStatusToReturn;
/**
* Initialize the {@code HttpStatusLogoutSuccessHandler} with a user-defined
* {@link HttpStatus}.
* @param httpStatusToReturn Must not be {@code null}.
*/
public HttpStatusReturningLogoutSuccessHandler(HttpStatus httpStatusToReturn) {
Assert.notNull(httpStatusToReturn, "The provided HttpStatus must not be null.");
this.httpStatusToReturn = httpStatusToReturn;
}
/**
* Initialize the {@code HttpStatusLogoutSuccessHandler} with the default
* {@link HttpStatus#OK}.
*/
public HttpStatusReturningLogoutSuccessHandler() {
this.httpStatusToReturn = HttpStatus.OK;
}
/**
* Implementation of
* {@link LogoutSuccessHandler#onLogoutSuccess(HttpServletRequest, HttpServletResponse, Authentication)}
* . Sets the status on the {@link HttpServletResponse}.
*/
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException {
response.setStatus(this.httpStatusToReturn.value());
response.getWriter().flush();
}
}
| 2,394 | 32.732394 | 117 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/logout/ForwardLogoutSuccessHandler.java | /*
* Copyright 2002-2018 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.web.authentication.logout;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;
/**
* {@link LogoutSuccessHandler} implementation that will perform a request dispatcher
* "forward" to the specified target URL.
*
* @author Vedran Pavic
* @since 5.0
*/
public class ForwardLogoutSuccessHandler implements LogoutSuccessHandler {
private final String targetUrl;
/**
* Construct a new {@link ForwardLogoutSuccessHandler} with the given target URL.
* @param targetUrl the target URL
*/
public ForwardLogoutSuccessHandler(String targetUrl) {
Assert.isTrue(UrlUtils.isValidRedirectUrl(targetUrl), () -> "'" + targetUrl + "' is not a valid target URL");
this.targetUrl = targetUrl;
}
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
request.getRequestDispatcher(this.targetUrl).forward(request, response);
}
}
| 1,879 | 32.571429 | 117 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/logout/CookieClearingLogoutHandler.java | /*
* Copyright 2002-2021 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.web.authentication.logout;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* A logout handler which clears either - A defined list of cookie names, using the
* context path as the cookie path OR - A given list of Cookies
*
* @author Luke Taylor
* @author Onur Kagan Ozcan
* @since 3.1
*/
public final class CookieClearingLogoutHandler implements LogoutHandler {
private final List<Function<HttpServletRequest, Cookie>> cookiesToClear;
public CookieClearingLogoutHandler(String... cookiesToClear) {
Assert.notNull(cookiesToClear, "List of cookies cannot be null");
List<Function<HttpServletRequest, Cookie>> cookieList = new ArrayList<>();
for (String cookieName : cookiesToClear) {
cookieList.add((request) -> {
Cookie cookie = new Cookie(cookieName, null);
String contextPath = request.getContextPath();
String cookiePath = StringUtils.hasText(contextPath) ? contextPath : "/";
cookie.setPath(cookiePath);
cookie.setMaxAge(0);
cookie.setSecure(request.isSecure());
return cookie;
});
}
this.cookiesToClear = cookieList;
}
/**
* @param cookiesToClear - One or more Cookie objects that must have maxAge of 0
* @since 5.2
*/
public CookieClearingLogoutHandler(Cookie... cookiesToClear) {
Assert.notNull(cookiesToClear, "List of cookies cannot be null");
List<Function<HttpServletRequest, Cookie>> cookieList = new ArrayList<>();
for (Cookie cookie : cookiesToClear) {
Assert.isTrue(cookie.getMaxAge() == 0, "Cookie maxAge must be 0");
cookieList.add((request) -> cookie);
}
this.cookiesToClear = cookieList;
}
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
this.cookiesToClear.forEach((f) -> response.addCookie(f.apply(request)));
}
}
| 2,777 | 33.725 | 110 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutFilter.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.web.authentication.logout;
import java.io.IOException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.log.LogMessage;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
/**
* Logs a principal out.
* <p>
* Polls a series of {@link LogoutHandler}s. The handlers should be specified in the order
* they are required. Generally you will want to call logout handlers
* <code>TokenBasedRememberMeServices</code> and <code>SecurityContextLogoutHandler</code>
* (in that order).
* <p>
* After logout, a redirect will be performed to the URL determined by either the
* configured <tt>LogoutSuccessHandler</tt> or the <tt>logoutSuccessUrl</tt>, depending on
* which constructor was used.
*
* @author Ben Alex
* @author Eddú Meléndez
*/
public class LogoutFilter extends GenericFilterBean {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private RequestMatcher logoutRequestMatcher;
private final LogoutHandler handler;
private final LogoutSuccessHandler logoutSuccessHandler;
/**
* Constructor which takes a <tt>LogoutSuccessHandler</tt> instance to determine the
* target destination after logging out. The list of <tt>LogoutHandler</tt>s are
* intended to perform the actual logout functionality (such as clearing the security
* context, invalidating the session, etc.).
*/
public LogoutFilter(LogoutSuccessHandler logoutSuccessHandler, LogoutHandler... handlers) {
this.handler = new CompositeLogoutHandler(handlers);
Assert.notNull(logoutSuccessHandler, "logoutSuccessHandler cannot be null");
this.logoutSuccessHandler = logoutSuccessHandler;
setFilterProcessesUrl("/logout");
}
public LogoutFilter(String logoutSuccessUrl, LogoutHandler... handlers) {
this.handler = new CompositeLogoutHandler(handlers);
Assert.isTrue(!StringUtils.hasLength(logoutSuccessUrl) || UrlUtils.isValidRedirectUrl(logoutSuccessUrl),
() -> logoutSuccessUrl + " isn't a valid redirect URL");
SimpleUrlLogoutSuccessHandler urlLogoutSuccessHandler = new SimpleUrlLogoutSuccessHandler();
if (StringUtils.hasText(logoutSuccessUrl)) {
urlLogoutSuccessHandler.setDefaultTargetUrl(logoutSuccessUrl);
}
this.logoutSuccessHandler = urlLogoutSuccessHandler;
setFilterProcessesUrl("/logout");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
}
private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (requiresLogout(request, response)) {
Authentication auth = this.securityContextHolderStrategy.getContext().getAuthentication();
if (this.logger.isDebugEnabled()) {
this.logger.debug(LogMessage.format("Logging out [%s]", auth));
}
this.handler.logout(request, response, auth);
this.logoutSuccessHandler.onLogoutSuccess(request, response, auth);
return;
}
chain.doFilter(request, response);
}
/**
* Allow subclasses to modify when a logout should take place.
* @param request the request
* @param response the response
* @return <code>true</code> if logout should occur, <code>false</code> otherwise
*/
protected boolean requiresLogout(HttpServletRequest request, HttpServletResponse response) {
if (this.logoutRequestMatcher.matches(request)) {
return true;
}
if (this.logger.isTraceEnabled()) {
this.logger.trace(LogMessage.format("Did not match request to %s", this.logoutRequestMatcher));
}
return false;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
public void setLogoutRequestMatcher(RequestMatcher logoutRequestMatcher) {
Assert.notNull(logoutRequestMatcher, "logoutRequestMatcher cannot be null");
this.logoutRequestMatcher = logoutRequestMatcher;
}
public void setFilterProcessesUrl(String filterProcessesUrl) {
this.logoutRequestMatcher = new AntPathRequestMatcher(filterProcessesUrl);
}
}
| 5,893 | 39.095238 | 108 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandler.java | /*
* Copyright 2002-2016 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.web.authentication.logout;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
/**
* Handles the navigation on logout by delegating to the
* {@link AbstractAuthenticationTargetUrlRequestHandler} base class logic.
*
* @author Luke Taylor
* @since 3.0
*/
public class SimpleUrlLogoutSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler
implements LogoutSuccessHandler {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
super.handle(request, response, authentication);
}
}
| 1,558 | 33.644444 | 117 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/logout/HeaderWriterLogoutHandler.java | /*
* Copyright 2002-2019 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.web.authentication.logout;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.header.HeaderWriter;
import org.springframework.util.Assert;
/**
* @author Rafiullah Hamedy
* @since 5.2
*/
public final class HeaderWriterLogoutHandler implements LogoutHandler {
private final HeaderWriter headerWriter;
/**
* Constructs a new instance using the passed {@link HeaderWriter} implementation
* @param headerWriter
* @throws IllegalArgumentException if headerWriter is null.
*/
public HeaderWriterLogoutHandler(HeaderWriter headerWriter) {
Assert.notNull(headerWriter, "headerWriter cannot be null");
this.headerWriter = headerWriter;
}
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
this.headerWriter.writeHeaders(request, response);
}
}
| 1,637 | 31.76 | 110 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutHandler.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.web.authentication.logout;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
/**
* Indicates a class that is able to participate in logout handling.
*
* <p>
* Called by {@link LogoutFilter}.
*
* @author Ben Alex
*/
public interface LogoutHandler {
/**
* Causes a logout to be completed. The method must complete successfully.
* @param request the HTTP request
* @param response the HTTP response
* @param authentication the current principal details
*/
void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication);
}
| 1,349 | 30.395349 | 102 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutSuccessEventPublishingLogoutHandler.java | /*
* Copyright 2002-2019 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.web.authentication.logout;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.security.authentication.event.LogoutSuccessEvent;
import org.springframework.security.core.Authentication;
/**
* A logout handler which publishes {@link LogoutSuccessEvent}
*
* @author Onur Kagan Ozcan
* @since 5.2.0
*/
public final class LogoutSuccessEventPublishingLogoutHandler implements LogoutHandler, ApplicationEventPublisherAware {
private ApplicationEventPublisher eventPublisher;
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
if (this.eventPublisher == null) {
return;
}
if (authentication == null) {
return;
}
this.eventPublisher.publishEvent(new LogoutSuccessEvent(authentication));
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.eventPublisher = applicationEventPublisher;
}
}
| 1,807 | 32.481481 | 119 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/ObservationWebFilterChainDecorator.java | /*
* Copyright 2002-2023 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.web.server;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import io.micrometer.common.KeyValue;
import io.micrometer.common.KeyValues;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationConvention;
import io.micrometer.observation.ObservationRegistry;
import io.micrometer.observation.contextpropagation.ObservationThreadLocalAccessor;
import reactor.core.publisher.Mono;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.server.WebHandler;
/**
* A
* {@link org.springframework.security.web.server.WebFilterChainProxy.WebFilterChainDecorator}
* that wraps the chain in before and after observations
*
* @author Josh Cummings
* @since 6.0
*/
public final class ObservationWebFilterChainDecorator implements WebFilterChainProxy.WebFilterChainDecorator {
private static final String ATTRIBUTE = ObservationWebFilterChainDecorator.class + ".observation";
static final String UNSECURED_OBSERVATION_NAME = "spring.security.http.unsecured.requests";
static final String SECURED_OBSERVATION_NAME = "spring.security.http.secured.requests";
private final ObservationRegistry registry;
public ObservationWebFilterChainDecorator(ObservationRegistry registry) {
this.registry = registry;
}
@Override
public WebFilterChain decorate(WebFilterChain original) {
return wrapUnsecured(original);
}
@Override
public WebFilterChain decorate(WebFilterChain original, List<WebFilter> filters) {
return new ObservationWebFilterChain(wrapSecured(original)::filter, wrap(filters));
}
private static AroundWebFilterObservation observation(ServerWebExchange exchange) {
return exchange.getAttribute(ATTRIBUTE);
}
private WebFilterChain wrapSecured(WebFilterChain original) {
return (exchange) -> Mono.deferContextual((contextView) -> {
AroundWebFilterObservation parent = observation(exchange);
Observation parentObservation = contextView.getOrDefault(ObservationThreadLocalAccessor.KEY, null);
Observation observation = Observation.createNotStarted(SECURED_OBSERVATION_NAME, this.registry)
.contextualName("secured request").parentObservation(parentObservation);
return parent.wrap(WebFilterObservation.create(observation).wrap(original)).filter(exchange);
});
}
private WebFilterChain wrapUnsecured(WebFilterChain original) {
return (exchange) -> Mono.deferContextual((contextView) -> {
Observation parentObservation = contextView.getOrDefault(ObservationThreadLocalAccessor.KEY, null);
Observation observation = Observation.createNotStarted(UNSECURED_OBSERVATION_NAME, this.registry)
.contextualName("unsecured request").parentObservation(parentObservation);
return WebFilterObservation.create(observation).wrap(original).filter(exchange);
});
}
private List<ObservationWebFilter> wrap(List<WebFilter> filters) {
int size = filters.size();
List<ObservationWebFilter> observableFilters = new ArrayList<>();
int position = 1;
for (WebFilter filter : filters) {
observableFilters.add(new ObservationWebFilter(this.registry, filter, position, size));
position++;
}
return observableFilters;
}
static class ObservationWebFilterChain implements WebFilterChain {
private final WebHandler handler;
@Nullable
private final ObservationWebFilter currentFilter;
@Nullable
private final ObservationWebFilterChain chain;
/**
* Public constructor with the list of filters and the target handler to use.
* @param handler the target handler
* @param filters the filters ahead of the handler
* @since 5.1
*/
ObservationWebFilterChain(WebHandler handler, List<ObservationWebFilter> filters) {
Assert.notNull(handler, "WebHandler is required");
this.handler = handler;
ObservationWebFilterChain chain = initChain(filters, handler);
this.currentFilter = chain.currentFilter;
this.chain = chain.chain;
}
private static ObservationWebFilterChain initChain(List<ObservationWebFilter> filters, WebHandler handler) {
ObservationWebFilterChain chain = new ObservationWebFilterChain(handler, null, null);
ListIterator<? extends ObservationWebFilter> iterator = filters.listIterator(filters.size());
while (iterator.hasPrevious()) {
chain = new ObservationWebFilterChain(handler, iterator.previous(), chain);
}
return chain;
}
/**
* Private constructor to represent one link in the chain.
*/
private ObservationWebFilterChain(WebHandler handler, @Nullable ObservationWebFilter currentFilter,
@Nullable ObservationWebFilterChain chain) {
this.currentFilter = currentFilter;
this.handler = handler;
this.chain = chain;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange) {
return Mono.defer(() -> (this.currentFilter != null && this.chain != null)
? invokeFilter(this.currentFilter, this.chain, exchange) : this.handler.handle(exchange));
}
private Mono<Void> invokeFilter(ObservationWebFilter current, ObservationWebFilterChain chain,
ServerWebExchange exchange) {
String currentName = current.getName();
return current.filter(exchange, chain).checkpoint(currentName + " [DefaultWebFilterChain]");
}
}
static final class ObservationWebFilter implements WebFilter {
private final ObservationRegistry registry;
private final WebFilterChainObservationConvention convention = new WebFilterChainObservationConvention();
private final WebFilter filter;
private final String name;
private final int position;
private final int size;
ObservationWebFilter(ObservationRegistry registry, WebFilter filter, int position, int size) {
this.registry = registry;
this.filter = filter;
this.name = filter.getClass().getSimpleName();
this.position = position;
this.size = size;
}
String getName() {
return this.name;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
if (this.position == 1) {
return Mono.deferContextual((contextView) -> {
Observation parentObservation = contextView.getOrDefault(ObservationThreadLocalAccessor.KEY, null);
AroundWebFilterObservation parent = parent(exchange, parentObservation);
return parent.wrap(this::wrapFilter).filter(exchange, chain);
});
}
else {
return wrapFilter(exchange, chain);
}
}
private Mono<Void> wrapFilter(ServerWebExchange exchange, WebFilterChain chain) {
AroundWebFilterObservation parent = observation(exchange);
if (parent.before().getContext() instanceof WebFilterChainObservationContext parentBefore) {
parentBefore.setChainSize(this.size);
parentBefore.setFilterName(this.name);
parentBefore.setChainPosition(this.position);
}
return this.filter.filter(exchange, chain).doOnSuccess((result) -> {
parent.start();
if (parent.after().getContext() instanceof WebFilterChainObservationContext parentAfter) {
parentAfter.setChainSize(this.size);
parentAfter.setFilterName(this.name);
parentAfter.setChainPosition(this.size - this.position + 1);
}
});
}
private AroundWebFilterObservation parent(ServerWebExchange exchange, Observation parentObservation) {
WebFilterChainObservationContext beforeContext = WebFilterChainObservationContext.before();
WebFilterChainObservationContext afterContext = WebFilterChainObservationContext.after();
Observation before = Observation.createNotStarted(this.convention, () -> beforeContext, this.registry)
.parentObservation(parentObservation);
Observation after = Observation.createNotStarted(this.convention, () -> afterContext, this.registry)
.parentObservation(parentObservation);
AroundWebFilterObservation parent = AroundWebFilterObservation.create(before, after);
exchange.getAttributes().put(ATTRIBUTE, parent);
return parent;
}
}
interface AroundWebFilterObservation extends WebFilterObservation {
AroundWebFilterObservation NOOP = new AroundWebFilterObservation() {
};
static AroundWebFilterObservation create(Observation before, Observation after) {
if (before.isNoop() || after.isNoop()) {
return NOOP;
}
return new SimpleAroundWebFilterObservation(before, after);
}
default Observation before() {
return Observation.NOOP;
}
default Observation after() {
return Observation.NOOP;
}
class SimpleAroundWebFilterObservation implements AroundWebFilterObservation {
private final ObservationReference before;
private final ObservationReference after;
private final AtomicReference<ObservationReference> currentObservation = new AtomicReference<>(
ObservationReference.NOOP);
SimpleAroundWebFilterObservation(Observation before, Observation after) {
this.before = new ObservationReference(before);
this.after = new ObservationReference(after);
}
@Override
public Observation start() {
if (this.currentObservation.compareAndSet(ObservationReference.NOOP, this.before)) {
this.before.start();
return this.before.observation;
}
if (this.currentObservation.compareAndSet(this.before, this.after)) {
this.before.stop();
this.after.start();
return this.after.observation;
}
return Observation.NOOP;
}
@Override
public Observation error(Throwable ex) {
this.currentObservation.get().error(ex);
return this.currentObservation.get().observation;
}
@Override
public void stop() {
this.currentObservation.get().stop();
}
@Override
public Observation contextualName(String contextualName) {
return this.currentObservation.get().observation.contextualName(contextualName);
}
@Override
public Observation parentObservation(Observation parentObservation) {
return this.currentObservation.get().observation.parentObservation(parentObservation);
}
@Override
public Observation lowCardinalityKeyValue(KeyValue keyValue) {
return this.currentObservation.get().observation.lowCardinalityKeyValue(keyValue);
}
@Override
public Observation highCardinalityKeyValue(KeyValue keyValue) {
return this.currentObservation.get().observation.highCardinalityKeyValue(keyValue);
}
@Override
public Observation observationConvention(ObservationConvention<?> observationConvention) {
return this.currentObservation.get().observation.observationConvention(observationConvention);
}
@Override
public Observation event(Event event) {
return this.currentObservation.get().observation.event(event);
}
@Override
public Context getContext() {
return this.currentObservation.get().observation.getContext();
}
@Override
public Scope openScope() {
return this.currentObservation.get().observation.openScope();
}
@Override
public WebFilterChain wrap(WebFilterChain chain) {
return (exchange) -> {
stop();
// @formatter:off
return chain.filter(exchange)
.doOnSuccess((v) -> start())
.doOnCancel(this::start)
.doOnError((t) -> {
error(t);
start();
});
// @formatter:on
};
}
@Override
public WebFilter wrap(WebFilter filter) {
return (exchange, chain) -> {
start();
// @formatter:off
return filter.filter(exchange, chain)
.doOnSuccess((v) -> stop())
.doOnCancel(this::stop)
.doOnError((t) -> {
error(t);
stop();
})
.contextWrite((context) -> context.put(ObservationThreadLocalAccessor.KEY, this));
// @formatter:on
};
}
@Override
public Observation before() {
return this.before.observation;
}
@Override
public Observation after() {
return this.after.observation;
}
@Override
public String toString() {
return this.currentObservation.get().observation.toString();
}
private static final class ObservationReference {
private static final ObservationReference NOOP = new ObservationReference(Observation.NOOP);
private final Lock lock = new ReentrantLock();
private final AtomicInteger state = new AtomicInteger(0);
private final Observation observation;
private ObservationReference(Observation observation) {
this.observation = observation;
}
private void start() {
try {
this.lock.lock();
if (this.state.compareAndSet(0, 1)) {
this.observation.start();
}
}
finally {
this.lock.unlock();
}
}
private void error(Throwable ex) {
try {
this.lock.lock();
if (this.state.get() == 1) {
this.observation.error(ex);
}
}
finally {
this.lock.unlock();
}
}
private void stop() {
try {
this.lock.lock();
if (this.state.compareAndSet(1, 2)) {
this.observation.stop();
}
}
finally {
this.lock.unlock();
}
}
}
}
}
interface WebFilterObservation extends Observation {
WebFilterObservation NOOP = new WebFilterObservation() {
};
static WebFilterObservation create(Observation observation) {
if (observation.isNoop()) {
return NOOP;
}
return new SimpleWebFilterObservation(observation);
}
@Override
default Observation contextualName(String contextualName) {
return Observation.NOOP;
}
@Override
default Observation parentObservation(Observation parentObservation) {
return Observation.NOOP;
}
@Override
default Observation lowCardinalityKeyValue(KeyValue keyValue) {
return Observation.NOOP;
}
@Override
default Observation highCardinalityKeyValue(KeyValue keyValue) {
return Observation.NOOP;
}
@Override
default Observation observationConvention(ObservationConvention<?> observationConvention) {
return Observation.NOOP;
}
@Override
default Observation error(Throwable error) {
return Observation.NOOP;
}
@Override
default Observation event(Event event) {
return Observation.NOOP;
}
@Override
default Observation start() {
return Observation.NOOP;
}
@Override
default Context getContext() {
return new Observation.Context();
}
@Override
default void stop() {
}
@Override
default Scope openScope() {
return Scope.NOOP;
}
default WebFilter wrap(WebFilter filter) {
return filter;
}
default WebFilterChain wrap(WebFilterChain chain) {
return chain;
}
class SimpleWebFilterObservation implements WebFilterObservation {
private final Observation observation;
SimpleWebFilterObservation(Observation observation) {
this.observation = observation;
}
@Override
public Observation start() {
return this.observation.start();
}
@Override
public Observation error(Throwable ex) {
return this.observation.error(ex);
}
@Override
public void stop() {
this.observation.stop();
}
@Override
public Observation contextualName(String contextualName) {
return this.observation.contextualName(contextualName);
}
@Override
public Observation parentObservation(Observation parentObservation) {
return this.observation.parentObservation(parentObservation);
}
@Override
public Observation lowCardinalityKeyValue(KeyValue keyValue) {
return this.observation.lowCardinalityKeyValue(keyValue);
}
@Override
public Observation highCardinalityKeyValue(KeyValue keyValue) {
return this.observation.highCardinalityKeyValue(keyValue);
}
@Override
public Observation observationConvention(ObservationConvention<?> observationConvention) {
return this.observation.observationConvention(observationConvention);
}
@Override
public Observation event(Event event) {
return this.observation.event(event);
}
@Override
public Context getContext() {
return this.observation.getContext();
}
@Override
public Scope openScope() {
return this.observation.openScope();
}
@Override
public WebFilter wrap(WebFilter filter) {
if (this.observation.isNoop()) {
return filter;
}
return (exchange, chain) -> {
this.observation.start();
return filter.filter(exchange, chain).doOnSuccess((v) -> this.observation.stop())
.doOnCancel(this.observation::stop).doOnError((t) -> {
this.observation.error(t);
this.observation.stop();
});
};
}
@Override
public WebFilterChain wrap(WebFilterChain chain) {
if (this.observation.isNoop()) {
return chain;
}
return (exchange) -> {
this.observation.start();
return chain.filter(exchange).doOnSuccess((v) -> this.observation.stop())
.doOnCancel(this.observation::stop).doOnError((t) -> {
this.observation.error(t);
this.observation.stop();
}).contextWrite(
(context) -> context.put(ObservationThreadLocalAccessor.KEY, this.observation));
};
}
}
}
static final class WebFilterChainObservationContext extends Observation.Context {
private final String filterSection;
private String filterName;
private int chainPosition;
private int chainSize;
private WebFilterChainObservationContext(String filterSection) {
this.filterSection = filterSection;
}
static WebFilterChainObservationContext before() {
return new WebFilterChainObservationContext("before");
}
static WebFilterChainObservationContext after() {
return new WebFilterChainObservationContext("after");
}
String getFilterSection() {
return this.filterSection;
}
String getFilterName() {
return this.filterName;
}
void setFilterName(String filterName) {
this.filterName = filterName;
}
int getChainPosition() {
return this.chainPosition;
}
void setChainPosition(int chainPosition) {
this.chainPosition = chainPosition;
}
int getChainSize() {
return this.chainSize;
}
void setChainSize(int chainSize) {
this.chainSize = chainSize;
}
}
static final class WebFilterChainObservationConvention
implements ObservationConvention<WebFilterChainObservationContext> {
static final String CHAIN_OBSERVATION_NAME = "spring.security.filterchains";
private static final String CHAIN_POSITION_NAME = "spring.security.filterchain.position";
private static final String CHAIN_SIZE_NAME = "spring.security.filterchain.size";
private static final String FILTER_SECTION_NAME = "spring.security.reached.filter.section";
private static final String FILTER_NAME = "spring.security.reached.filter.name";
@Override
public String getName() {
return CHAIN_OBSERVATION_NAME;
}
@Override
public String getContextualName(WebFilterChainObservationContext context) {
return "security filterchain " + context.getFilterSection();
}
@Override
public KeyValues getLowCardinalityKeyValues(WebFilterChainObservationContext context) {
return KeyValues.of(CHAIN_SIZE_NAME, String.valueOf(context.getChainSize()))
.and(CHAIN_POSITION_NAME, String.valueOf(context.getChainPosition()))
.and(FILTER_SECTION_NAME, context.getFilterSection())
.and(FILTER_NAME, (StringUtils.hasText(context.getFilterName())) ? context.getFilterName()
: KeyValue.NONE_VALUE);
}
@Override
public boolean supportsContext(Observation.Context context) {
return context instanceof WebFilterChainObservationContext;
}
}
}
| 20,391 | 27.924823 | 110 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/DefaultServerRedirectStrategy.java | /*
* Copyright 2002-2020 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.web.server;
import java.net.URI;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Mono;
import org.springframework.core.log.LogMessage;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
/**
* The default {@link ServerRedirectStrategy} to use.
*
* @author Rob Winch
* @author Mathieu Ouellet
* @since 5.0
*/
public class DefaultServerRedirectStrategy implements ServerRedirectStrategy {
private static final Log logger = LogFactory.getLog(DefaultServerRedirectStrategy.class);
private HttpStatus httpStatus = HttpStatus.FOUND;
private boolean contextRelative = true;
@Override
public Mono<Void> sendRedirect(ServerWebExchange exchange, URI location) {
Assert.notNull(exchange, "exchange cannot be null");
Assert.notNull(location, "location cannot be null");
return Mono.fromRunnable(() -> {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(this.httpStatus);
URI newLocation = createLocation(exchange, location);
logger.debug(LogMessage.format("Redirecting to '%s'", newLocation));
response.getHeaders().setLocation(newLocation);
});
}
private URI createLocation(ServerWebExchange exchange, URI location) {
if (!this.contextRelative) {
return location;
}
String url = location.toASCIIString();
if (url.startsWith("/")) {
String context = exchange.getRequest().getPath().contextPath().value();
return URI.create(context + url);
}
return location;
}
/**
* The {@link HttpStatus} to use for the redirect.
* @param httpStatus the status to use. Cannot be null
*/
public void setHttpStatus(HttpStatus httpStatus) {
Assert.notNull(httpStatus, "httpStatus cannot be null");
this.httpStatus = httpStatus;
}
/**
* Sets if the location is relative to the context.
* @param contextRelative if redirects should be relative to the context. Default is
* true.
*/
public void setContextRelative(boolean contextRelative) {
this.contextRelative = contextRelative;
}
}
| 2,858 | 30.766667 | 90 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/ServerAuthenticationEntryPoint.java | /*
* Copyright 2002-2017 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.web.server;
import reactor.core.publisher.Mono;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.server.ServerWebExchange;
/**
* Used to request authentication
*
* @author Rob Winch
* @since 5.0
*/
@FunctionalInterface
public interface ServerAuthenticationEntryPoint {
/**
* Initiates the authentication flow
* @param exchange
* @param ex
* @return {@code Mono<Void>} to indicate when the request for authentication is
* complete
*/
Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex);
}
| 1,244 | 27.953488 | 81 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/SecurityWebFilterChain.java | /*
* Copyright 2002-2017 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.web.server;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
/**
* Defines a filter chain which is capable of being matched against a
* {@link ServerWebExchange} in order to decide whether it applies to that request.
*
* @author Rob Winch
* @since 5.0
*/
public interface SecurityWebFilterChain {
/**
* Determines if this {@link SecurityWebFilterChain} matches the provided
* {@link ServerWebExchange}
* @param exchange the {@link ServerWebExchange}
* @return true if it matches, else false
*/
Mono<Boolean> matches(ServerWebExchange exchange);
/**
* The {@link WebFilter} to use
* @return
*/
Flux<WebFilter> getWebFilters();
}
| 1,449 | 28.591837 | 83 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/ExchangeMatcherRedirectWebFilter.java | /*
* Copyright 2002-2021 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.web.server;
import java.net.URI;
import reactor.core.publisher.Mono;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
/**
* Web filter that redirects requests that match {@link ServerWebExchangeMatcher} to the
* specified URL.
*
* @author Evgeniy Cheban
* @since 5.6
*/
public final class ExchangeMatcherRedirectWebFilter implements WebFilter {
private final ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy();
private final ServerWebExchangeMatcher exchangeMatcher;
private final URI redirectUri;
/**
* Create and initialize an instance of the web filter.
* @param exchangeMatcher the exchange matcher
* @param redirectUrl the redirect URL
*/
public ExchangeMatcherRedirectWebFilter(ServerWebExchangeMatcher exchangeMatcher, String redirectUrl) {
Assert.notNull(exchangeMatcher, "exchangeMatcher cannot be null");
Assert.hasText(redirectUrl, "redirectUrl cannot be empty");
this.exchangeMatcher = exchangeMatcher;
this.redirectUri = URI.create(redirectUrl);
}
/**
* {@inheritDoc}
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
// @formatter:off
return this.exchangeMatcher.matches(exchange)
.filter(MatchResult::isMatch)
.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
.flatMap((result) -> this.redirectStrategy.sendRedirect(exchange, this.redirectUri));
// @formatter:on
}
}
| 2,416 | 33.042254 | 104 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/ServerRedirectStrategy.java | /*
* Copyright 2002-2017 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.web.server;
import java.net.URI;
import reactor.core.publisher.Mono;
import org.springframework.web.server.ServerWebExchange;
/**
* A strategy for performing redirects.
*
* @author Rob Winch
* @since 5.0
*/
@FunctionalInterface
public interface ServerRedirectStrategy {
/**
* Performs a redirect based upon the provided {@link ServerWebExchange} and
* {@link URI}
* @param exchange the {@link ServerWebExchange} to use
* @param location the location to redirect to
* @return {@code Mono<Void>} to indicate when redirect is complete
*/
Mono<Void> sendRedirect(ServerWebExchange exchange, URI location);
}
| 1,289 | 28.318182 | 77 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/WebFilterChainProxy.java | /*
* Copyright 2002-2022 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.web.server;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import jakarta.servlet.FilterChain;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.server.handler.DefaultWebFilterChain;
/**
* Used to delegate to a List of {@link SecurityWebFilterChain} instances.
*
* @author Rob Winch
* @since 5.0
*/
public class WebFilterChainProxy implements WebFilter {
private final List<SecurityWebFilterChain> filters;
private WebFilterChainDecorator filterChainDecorator = new DefaultWebFilterChainDecorator();
public WebFilterChainProxy(List<SecurityWebFilterChain> filters) {
this.filters = filters;
}
public WebFilterChainProxy(SecurityWebFilterChain... filters) {
this.filters = Arrays.asList(filters);
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return Flux.fromIterable(this.filters)
.filterWhen((securityWebFilterChain) -> securityWebFilterChain.matches(exchange)).next()
.switchIfEmpty(
Mono.defer(() -> this.filterChainDecorator.decorate(chain).filter(exchange).then(Mono.empty())))
.flatMap((securityWebFilterChain) -> securityWebFilterChain.getWebFilters().collectList())
.map((filters) -> this.filterChainDecorator.decorate(chain, filters))
.flatMap((securedChain) -> securedChain.filter(exchange));
}
/**
* Used to decorate the original {@link FilterChain} for each request
*
* <p>
* By default, this decorates the filter chain with a {@link DefaultWebFilterChain}
* that iterates through security filters and then delegates to the original chain
* @param filterChainDecorator the strategy for constructing the filter chain
* @since 6.0
*/
public void setFilterChainDecorator(WebFilterChainDecorator filterChainDecorator) {
Assert.notNull(filterChainDecorator, "filterChainDecorator cannot be null");
this.filterChainDecorator = filterChainDecorator;
}
/**
* A strategy for decorating the provided filter chain with one that accounts for the
* {@link SecurityFilterChain} for a given request.
*
* @author Josh Cummings
* @since 6.0
*/
public interface WebFilterChainDecorator {
/**
* Provide a new {@link FilterChain} that accounts for needed security
* considerations when there are no security filters.
* @param original the original {@link FilterChain}
* @return a security-enabled {@link FilterChain}
*/
default WebFilterChain decorate(WebFilterChain original) {
return decorate(original, Collections.emptyList());
}
/**
* Provide a new {@link FilterChain} that accounts for the provided filters as
* well as teh original filter chain.
* @param original the original {@link FilterChain}
* @param filters the security filters
* @return a security-enabled {@link FilterChain} that includes the provided
* filters
*/
WebFilterChain decorate(WebFilterChain original, List<WebFilter> filters);
}
/**
* A {@link WebFilterChainDecorator} that uses the {@link DefaultWebFilterChain}
*
* @author Josh Cummings
* @since 6.0
*/
public static class DefaultWebFilterChainDecorator implements WebFilterChainDecorator {
/**
* {@inheritDoc}
*/
@Override
public WebFilterChain decorate(WebFilterChain original) {
return original;
}
/**
* {@inheritDoc}
*/
@Override
public WebFilterChain decorate(WebFilterChain original, List<WebFilter> filters) {
return new DefaultWebFilterChain(original::filter, filters);
}
}
}
| 4,453 | 31.510949 | 102 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/WebFilterExchange.java | /*
* Copyright 2002-2017 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.web.server;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
/**
* A composite of the {@link ServerWebExchange} and the {@link WebFilterChain}. This is
* typically used as a value object for handling success and failures.
*
* @author Rob Winch
* @since 5.0
*/
public class WebFilterExchange {
private final ServerWebExchange exchange;
private final WebFilterChain chain;
public WebFilterExchange(ServerWebExchange exchange, WebFilterChain chain) {
Assert.notNull(exchange, "exchange cannot be null");
Assert.notNull(chain, "chain cannot be null");
this.exchange = exchange;
this.chain = chain;
}
/**
* Get the exchange
* @return the exchange. Cannot be {@code null}
*/
public ServerWebExchange getExchange() {
return this.exchange;
}
/**
* The filter chain
* @return the filter chain. Cannot be {@code null}
*/
public WebFilterChain getChain() {
return this.chain;
}
}
| 1,679 | 27 | 87 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/ServerFormLoginAuthenticationConverter.java | /*
* Copyright 2002-2022 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.web.server;
import java.util.function.Function;
import reactor.core.publisher.Mono;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
/**
* Converts a ServerWebExchange into a UsernamePasswordAuthenticationToken from the form
* data HTTP parameters.
*
* @author Rob Winch
* @since 5.0
* @deprecated use
* {@link org.springframework.security.web.server.authentication.ServerFormLoginAuthenticationConverter}
* instead.
*/
@Deprecated
public class ServerFormLoginAuthenticationConverter implements Function<ServerWebExchange, Mono<Authentication>> {
private String usernameParameter = "username";
private String passwordParameter = "password";
@Override
@Deprecated
public Mono<Authentication> apply(ServerWebExchange exchange) {
return exchange.getFormData().map(this::createAuthentication);
}
private UsernamePasswordAuthenticationToken createAuthentication(MultiValueMap<String, String> data) {
String username = data.getFirst(this.usernameParameter);
String password = data.getFirst(this.passwordParameter);
return UsernamePasswordAuthenticationToken.unauthenticated(username, password);
}
/**
* The parameter name of the form data to extract the username
* @param usernameParameter the username HTTP parameter
*/
public void setUsernameParameter(String usernameParameter) {
Assert.notNull(usernameParameter, "usernameParameter cannot be null");
this.usernameParameter = usernameParameter;
}
/**
* The parameter name of the form data to extract the password
* @param passwordParameter the password HTTP parameter
*/
public void setPasswordParameter(String passwordParameter) {
Assert.notNull(passwordParameter, "passwordParameter cannot be null");
this.passwordParameter = passwordParameter;
}
}
| 2,659 | 33.545455 | 114 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/ServerHttpBasicAuthenticationConverter.java | /*
* Copyright 2002-2022 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.web.server;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.function.Function;
import reactor.core.publisher.Mono;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
/**
* Converts from a {@link ServerWebExchange} to an {@link Authentication} that can be
* authenticated.
*
* @author Rob Winch
* @since 5.0
* @deprecated Use
* {@link org.springframework.security.web.server.authentication.ServerHttpBasicAuthenticationConverter}
* instead.
*/
@Deprecated
public class ServerHttpBasicAuthenticationConverter implements Function<ServerWebExchange, Mono<Authentication>> {
public static final String BASIC = "Basic ";
private Charset credentialsCharset = StandardCharsets.UTF_8;
@Override
@Deprecated
public Mono<Authentication> apply(ServerWebExchange exchange) {
ServerHttpRequest request = exchange.getRequest();
String authorization = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
if (!StringUtils.startsWithIgnoreCase(authorization, "basic ")) {
return Mono.empty();
}
String credentials = (authorization.length() <= BASIC.length()) ? "" : authorization.substring(BASIC.length());
String decoded = new String(base64Decode(credentials), this.credentialsCharset);
String[] parts = decoded.split(":", 2);
if (parts.length != 2) {
return Mono.empty();
}
return Mono.just(UsernamePasswordAuthenticationToken.unauthenticated(parts[0], parts[1]));
}
private byte[] base64Decode(String value) {
try {
return Base64.getDecoder().decode(value);
}
catch (Exception ex) {
return new byte[0];
}
}
/**
* Sets the {@link Charset} used to decode the Base64-encoded bytes of the basic
* authentication credentials. The default is <code>UTF_8</code>.
* @param credentialsCharset the {@link Charset} used to decode the Base64-encoded
* bytes of the basic authentication credentials
* @since 5.7
*/
public final void setCredentialsCharset(Charset credentialsCharset) {
Assert.notNull(credentialsCharset, "credentialsCharset cannot be null");
this.credentialsCharset = credentialsCharset;
}
}
| 3,149 | 34 | 114 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/DelegatingServerAuthenticationEntryPoint.java | /*
* Copyright 2002-2020 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.web.server;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.core.log.LogMessage;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
/**
* A {@link ServerAuthenticationEntryPoint} which delegates to multiple
* {@link ServerAuthenticationEntryPoint} based on a {@link ServerWebExchangeMatcher}
*
* @author Rob Winch
* @author Mathieu Ouellet
* @since 5.0
*/
public class DelegatingServerAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
private static final Log logger = LogFactory.getLog(DelegatingServerAuthenticationEntryPoint.class);
private final List<DelegateEntry> entryPoints;
private ServerAuthenticationEntryPoint defaultEntryPoint = (exchange, ex) -> {
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
};
public DelegatingServerAuthenticationEntryPoint(DelegateEntry... entryPoints) {
this(Arrays.asList(entryPoints));
}
public DelegatingServerAuthenticationEntryPoint(List<DelegateEntry> entryPoints) {
Assert.notEmpty(entryPoints, "entryPoints cannot be null");
this.entryPoints = entryPoints;
}
@Override
public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) {
return Flux.fromIterable(this.entryPoints).filterWhen((entry) -> isMatch(exchange, entry)).next()
.map((entry) -> entry.getEntryPoint())
.doOnNext((entryPoint) -> logger.debug(LogMessage.format("Match found! Executing %s", entryPoint)))
.switchIfEmpty(Mono.just(this.defaultEntryPoint)
.doOnNext((entryPoint) -> logger.debug(LogMessage
.format("No match found. Using default entry point %s", this.defaultEntryPoint))))
.flatMap((entryPoint) -> entryPoint.commence(exchange, ex));
}
private Mono<Boolean> isMatch(ServerWebExchange exchange, DelegateEntry entry) {
ServerWebExchangeMatcher matcher = entry.getMatcher();
logger.debug(LogMessage.format("Trying to match using %s", matcher));
return matcher.matches(exchange).map(MatchResult::isMatch);
}
/**
* EntryPoint which is used when no RequestMatcher returned true
*/
public void setDefaultEntryPoint(ServerAuthenticationEntryPoint defaultEntryPoint) {
this.defaultEntryPoint = defaultEntryPoint;
}
public static class DelegateEntry {
private final ServerWebExchangeMatcher matcher;
private final ServerAuthenticationEntryPoint entryPoint;
public DelegateEntry(ServerWebExchangeMatcher matcher, ServerAuthenticationEntryPoint entryPoint) {
this.matcher = matcher;
this.entryPoint = entryPoint;
}
public ServerWebExchangeMatcher getMatcher() {
return this.matcher;
}
public ServerAuthenticationEntryPoint getEntryPoint() {
return this.entryPoint;
}
}
}
| 3,896 | 34.752294 | 103 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/MatcherSecurityWebFilterChain.java | /*
* Copyright 2002-2018 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.web.server;
import java.util.List;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
/**
* A {@link SecurityWebFilterChain} that leverages a {@link ServerWebExchangeMatcher} to
* determine which {@link WebFilter} to execute.
*
* @author Rob Winch
* @since 5.0
*/
public class MatcherSecurityWebFilterChain implements SecurityWebFilterChain {
private final ServerWebExchangeMatcher matcher;
private final List<WebFilter> filters;
public MatcherSecurityWebFilterChain(ServerWebExchangeMatcher matcher, List<WebFilter> filters) {
Assert.notNull(matcher, "matcher cannot be null");
Assert.notEmpty(filters, () -> "filters cannot be null or empty. Got " + filters);
this.matcher = matcher;
this.filters = filters;
}
@Override
public Mono<Boolean> matches(ServerWebExchange exchange) {
return this.matcher.matches(exchange).map((m) -> m.isMatch());
}
@Override
public Flux<WebFilter> getWebFilters() {
return Flux.fromIterable(this.filters);
}
}
| 1,892 | 30.55 | 98 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/savedrequest/WebSessionServerRequestCache.java | /*
* Copyright 2002-2020 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.web.server.savedrequest;
import java.net.URI;
import java.util.Collections;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Mono;
import org.springframework.core.log.LogMessage;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.web.server.util.matcher.AndServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.MediaTypeServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.NegatedServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers;
import org.springframework.util.Assert;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebSession;
import org.springframework.web.util.UriComponentsBuilder;
/**
* An implementation of {@link ServerRequestCache} that saves the
* {@link ServerHttpRequest} in the {@link WebSession}.
*
* The current implementation only saves the URL that was requested.
*
* @author Rob Winch
* @author Mathieu Ouellet
* @since 5.0
*/
public class WebSessionServerRequestCache implements ServerRequestCache {
private static final String DEFAULT_SAVED_REQUEST_ATTR = "SPRING_SECURITY_SAVED_REQUEST";
private static final Log logger = LogFactory.getLog(WebSessionServerRequestCache.class);
private String sessionAttrName = DEFAULT_SAVED_REQUEST_ATTR;
private ServerWebExchangeMatcher saveRequestMatcher = createDefaultRequestMacher();
private String matchingRequestParameterName;
/**
* Sets the matcher to determine if the request should be saved. The default is to
* match on any GET request.
* @param saveRequestMatcher
*/
public void setSaveRequestMatcher(ServerWebExchangeMatcher saveRequestMatcher) {
Assert.notNull(saveRequestMatcher, "saveRequestMatcher cannot be null");
this.saveRequestMatcher = saveRequestMatcher;
}
@Override
public Mono<Void> saveRequest(ServerWebExchange exchange) {
return this.saveRequestMatcher.matches(exchange).filter(MatchResult::isMatch)
.flatMap((m) -> exchange.getSession()).map(WebSession::getAttributes).doOnNext((attrs) -> {
String requestPath = pathInApplication(exchange.getRequest());
attrs.put(this.sessionAttrName, requestPath);
logger.debug(LogMessage.format("Request added to WebSession: '%s'", requestPath));
}).then();
}
@Override
public Mono<URI> getRedirectUri(ServerWebExchange exchange) {
return exchange.getSession()
.flatMap((session) -> Mono.justOrEmpty(session.<String>getAttribute(this.sessionAttrName)))
.map(this::createRedirectUri);
}
@Override
public Mono<ServerHttpRequest> removeMatchingRequest(ServerWebExchange exchange) {
MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
if (this.matchingRequestParameterName != null && !queryParams.containsKey(this.matchingRequestParameterName)) {
this.logger.trace(
"matchingRequestParameterName is required for getMatchingRequest to lookup a value, but not provided");
return Mono.empty();
}
ServerHttpRequest request = stripMatchingRequestParameterName(exchange.getRequest());
return exchange.getSession().map(WebSession::getAttributes).filter((attributes) -> {
String requestPath = pathInApplication(request);
boolean removed = attributes.remove(this.sessionAttrName, requestPath);
if (removed) {
logger.debug(LogMessage.format("Request removed from WebSession: '%s'", requestPath));
}
return removed;
}).map((attributes) -> request);
}
/**
* Specify the name of a query parameter that is added to the URL in
* {@link #getRedirectUri(ServerWebExchange)} and is required for
* {@link #removeMatchingRequest(ServerWebExchange)} to look up the
* {@link ServerHttpRequest}.
* @param matchingRequestParameterName the parameter name that must be in the request
* for {@link #removeMatchingRequest(ServerWebExchange)} to check the session.
*/
public void setMatchingRequestParameterName(String matchingRequestParameterName) {
this.matchingRequestParameterName = matchingRequestParameterName;
}
private ServerHttpRequest stripMatchingRequestParameterName(ServerHttpRequest request) {
if (this.matchingRequestParameterName == null) {
return request;
}
// @formatter:off
URI uri = UriComponentsBuilder.fromUri(request.getURI())
.replaceQueryParam(this.matchingRequestParameterName)
.build()
.toUri();
return request.mutate()
.uri(uri)
.build();
// @formatter:on
}
private static String pathInApplication(ServerHttpRequest request) {
String path = request.getPath().pathWithinApplication().value();
String query = request.getURI().getRawQuery();
return path + ((query != null) ? "?" + query : "");
}
private URI createRedirectUri(String uri) {
if (this.matchingRequestParameterName == null) {
return URI.create(uri);
}
// @formatter:off
return UriComponentsBuilder.fromUriString(uri)
.queryParam(this.matchingRequestParameterName)
.build()
.toUri();
// @formatter:on
}
private static ServerWebExchangeMatcher createDefaultRequestMacher() {
ServerWebExchangeMatcher get = ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, "/**");
ServerWebExchangeMatcher notFavicon = new NegatedServerWebExchangeMatcher(
ServerWebExchangeMatchers.pathMatchers("/favicon.*"));
MediaTypeServerWebExchangeMatcher html = new MediaTypeServerWebExchangeMatcher(MediaType.TEXT_HTML);
html.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
return new AndServerWebExchangeMatcher(get, notFavicon, html);
}
private static String createQueryString(String queryString, String matchingRequestParameterName) {
if (matchingRequestParameterName == null) {
return queryString;
}
if (queryString == null || queryString.length() == 0) {
return matchingRequestParameterName;
}
if (queryString.endsWith("&")) {
return queryString + matchingRequestParameterName;
}
return queryString + "&" + matchingRequestParameterName;
}
}
| 7,081 | 38.786517 | 113 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/savedrequest/NoOpServerRequestCache.java | /*
* Copyright 2002-2017 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.web.server.savedrequest;
import java.net.URI;
import reactor.core.publisher.Mono;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
/**
* An implementation of {@link ServerRequestCache} that does nothing. This is used in
* stateless applications
*
* @author Rob Winch
* @since 5.0
*/
public final class NoOpServerRequestCache implements ServerRequestCache {
private NoOpServerRequestCache() {
}
@Override
public Mono<Void> saveRequest(ServerWebExchange exchange) {
return Mono.empty();
}
@Override
public Mono<URI> getRedirectUri(ServerWebExchange exchange) {
return Mono.empty();
}
@Override
public Mono<ServerHttpRequest> removeMatchingRequest(ServerWebExchange exchange) {
return Mono.empty();
}
public static NoOpServerRequestCache getInstance() {
return new NoOpServerRequestCache();
}
}
| 1,564 | 25.982759 | 85 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/savedrequest/ServerRequestCacheWebFilter.java | /*
* Copyright 2002-2017 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.web.server.savedrequest;
import reactor.core.publisher.Mono;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
/**
* A {@link WebFilter} that replays any matching request in {@link ServerRequestCache}
*
* @author Rob Winch
* @since 5.0
*/
public class ServerRequestCacheWebFilter implements WebFilter {
private ServerRequestCache requestCache = new WebSessionServerRequestCache();
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return this.requestCache.removeMatchingRequest(exchange).map((r) -> exchange.mutate().request(r).build())
.defaultIfEmpty(exchange).flatMap((e) -> chain.filter(e));
}
public void setRequestCache(ServerRequestCache requestCache) {
Assert.notNull(requestCache, "requestCache cannot be null");
this.requestCache = requestCache;
}
}
| 1,635 | 33.083333 | 107 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/savedrequest/ServerRequestCache.java | /*
* Copyright 2002-2017 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.web.server.savedrequest;
import java.net.URI;
import reactor.core.publisher.Mono;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
/**
* Saves a {@link ServerHttpRequest} so it can be "replayed" later. This is useful for
* when a page was requested and authentication is necessary.
*
* @author Rob Winch
* @since 5.0
*/
public interface ServerRequestCache {
/**
* Save the {@link ServerHttpRequest}
* @param exchange the exchange to save
* @return Return a {@code Mono<Void>} which only replays complete and error signals
* from this {@link Mono}.
*/
Mono<Void> saveRequest(ServerWebExchange exchange);
/**
* Get the URI that can be redirected to trigger the saved request to be used
* @param exchange the exchange to obtain the saved {@link ServerHttpRequest} from
* @return the URI that can be redirected to trigger the saved request to be used
*/
Mono<URI> getRedirectUri(ServerWebExchange exchange);
/**
* If the provided {@link ServerWebExchange} matches the saved
* {@link ServerHttpRequest} gets the saved {@link ServerHttpRequest}
* @param exchange the exchange to obtain the request from
* @return the {@link ServerHttpRequest}
*/
Mono<ServerHttpRequest> removeMatchingRequest(ServerWebExchange exchange);
}
| 2,000 | 32.915254 | 86 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/savedrequest/CookieServerRequestCache.java | /*
* Copyright 2002-2020 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.web.server.savedrequest;
import java.net.URI;
import java.time.Duration;
import java.util.Base64;
import java.util.Collections;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Mono;
import org.springframework.core.log.LogMessage;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.web.server.util.matcher.AndServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.MediaTypeServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.NegatedServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers;
import org.springframework.util.Assert;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
/**
* An implementation of {@link ServerRequestCache} that saves the requested URI in a
* cookie.
*
* @author Eleftheria Stein
* @author Mathieu Ouellet
* @since 5.4
*/
public class CookieServerRequestCache implements ServerRequestCache {
private static final String REDIRECT_URI_COOKIE_NAME = "REDIRECT_URI";
private static final Duration COOKIE_MAX_AGE = Duration.ofSeconds(-1);
private static final Log logger = LogFactory.getLog(CookieServerRequestCache.class);
private ServerWebExchangeMatcher saveRequestMatcher = createDefaultRequestMatcher();
/**
* Sets the matcher to determine if the request should be saved. The default is to
* match on any GET request.
* @param saveRequestMatcher the {@link ServerWebExchangeMatcher} that determines if
* the request should be saved
*/
public void setSaveRequestMatcher(ServerWebExchangeMatcher saveRequestMatcher) {
Assert.notNull(saveRequestMatcher, "saveRequestMatcher cannot be null");
this.saveRequestMatcher = saveRequestMatcher;
}
@Override
public Mono<Void> saveRequest(ServerWebExchange exchange) {
return this.saveRequestMatcher.matches(exchange).filter((m) -> m.isMatch()).map((m) -> exchange.getResponse())
.map(ServerHttpResponse::getCookies).doOnNext((cookies) -> {
ResponseCookie redirectUriCookie = createRedirectUriCookie(exchange.getRequest());
cookies.add(REDIRECT_URI_COOKIE_NAME, redirectUriCookie);
logger.debug(LogMessage.format("Request added to Cookie: %s", redirectUriCookie));
}).then();
}
@Override
public Mono<URI> getRedirectUri(ServerWebExchange exchange) {
MultiValueMap<String, HttpCookie> cookieMap = exchange.getRequest().getCookies();
return Mono.justOrEmpty(cookieMap.getFirst(REDIRECT_URI_COOKIE_NAME)).map(HttpCookie::getValue)
.map(CookieServerRequestCache::decodeCookie)
.onErrorResume(IllegalArgumentException.class, (ex) -> Mono.empty()).map(URI::create);
}
@Override
public Mono<ServerHttpRequest> removeMatchingRequest(ServerWebExchange exchange) {
return Mono.just(exchange.getResponse()).map(ServerHttpResponse::getCookies).doOnNext(
(cookies) -> cookies.add(REDIRECT_URI_COOKIE_NAME, invalidateRedirectUriCookie(exchange.getRequest())))
.thenReturn(exchange.getRequest());
}
private static ResponseCookie createRedirectUriCookie(ServerHttpRequest request) {
String path = request.getPath().pathWithinApplication().value();
String query = request.getURI().getRawQuery();
String redirectUri = path + ((query != null) ? "?" + query : "");
return createResponseCookie(request, encodeCookie(redirectUri), COOKIE_MAX_AGE);
}
private static ResponseCookie invalidateRedirectUriCookie(ServerHttpRequest request) {
return createResponseCookie(request, null, Duration.ZERO);
}
private static ResponseCookie createResponseCookie(ServerHttpRequest request, String cookieValue, Duration age) {
return ResponseCookie.from(REDIRECT_URI_COOKIE_NAME, cookieValue)
.path(request.getPath().contextPath().value() + "/").maxAge(age).httpOnly(true)
.secure("https".equalsIgnoreCase(request.getURI().getScheme())).sameSite("Lax").build();
}
private static String encodeCookie(String cookieValue) {
return new String(Base64.getEncoder().encode(cookieValue.getBytes()));
}
private static String decodeCookie(String encodedCookieValue) {
return new String(Base64.getDecoder().decode(encodedCookieValue.getBytes()));
}
private static ServerWebExchangeMatcher createDefaultRequestMatcher() {
ServerWebExchangeMatcher get = ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, "/**");
ServerWebExchangeMatcher notFavicon = new NegatedServerWebExchangeMatcher(
ServerWebExchangeMatchers.pathMatchers("/favicon.*"));
MediaTypeServerWebExchangeMatcher html = new MediaTypeServerWebExchangeMatcher(MediaType.TEXT_HTML);
html.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
return new AndServerWebExchangeMatcher(get, notFavicon, html);
}
}
| 5,833 | 42.864662 | 114 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/util/matcher/AndServerWebExchangeMatcher.java | /*
* Copyright 2002-2020 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.web.server.util.matcher;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.core.log.LogMessage;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
/**
* Matches if all the provided {@link ServerWebExchangeMatcher} match
*
* @author Rob Winch
* @author Mathieu Ouellet
* @since 5.0
* @see OrServerWebExchangeMatcher
*/
public class AndServerWebExchangeMatcher implements ServerWebExchangeMatcher {
private static final Log logger = LogFactory.getLog(AndServerWebExchangeMatcher.class);
private final List<ServerWebExchangeMatcher> matchers;
public AndServerWebExchangeMatcher(List<ServerWebExchangeMatcher> matchers) {
Assert.notEmpty(matchers, "matchers cannot be empty");
this.matchers = matchers;
}
public AndServerWebExchangeMatcher(ServerWebExchangeMatcher... matchers) {
this(Arrays.asList(matchers));
}
@Override
public Mono<MatchResult> matches(ServerWebExchange exchange) {
return Mono.defer(() -> {
Map<String, Object> variables = new HashMap<>();
return Flux.fromIterable(this.matchers)
.doOnNext((matcher) -> logger.debug(LogMessage.format("Trying to match using %s", matcher)))
.flatMap((matcher) -> matcher.matches(exchange))
.doOnNext((matchResult) -> variables.putAll(matchResult.getVariables())).all(MatchResult::isMatch)
.flatMap((allMatch) -> allMatch ? MatchResult.match(variables) : MatchResult.notMatch())
.doOnNext((matchResult) -> logger
.debug(matchResult.isMatch() ? "All requestMatchers returned true" : "Did not match"));
});
}
@Override
public String toString() {
return "AndServerWebExchangeMatcher{" + "matchers=" + this.matchers + '}';
}
}
| 2,587 | 33.052632 | 103 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/util/matcher/NegatedServerWebExchangeMatcher.java | /*
* Copyright 2002-2020 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.web.server.util.matcher;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Mono;
import org.springframework.core.log.LogMessage;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
/**
* Negates the provided matcher. If the provided matcher returns true, then the result
* will be false. If the provided matcher returns false, then the result will be true.
*
* @author Tao Qian
* @author Mathieu Ouellet
* @since 5.1
*/
public class NegatedServerWebExchangeMatcher implements ServerWebExchangeMatcher {
private static final Log logger = LogFactory.getLog(NegatedServerWebExchangeMatcher.class);
private final ServerWebExchangeMatcher matcher;
public NegatedServerWebExchangeMatcher(ServerWebExchangeMatcher matcher) {
Assert.notNull(matcher, "matcher cannot be null");
this.matcher = matcher;
}
@Override
public Mono<MatchResult> matches(ServerWebExchange exchange) {
return this.matcher.matches(exchange).flatMap(this::negate)
.doOnNext((matchResult) -> logger.debug(LogMessage.format("matches = %s", matchResult.isMatch())));
}
private Mono<MatchResult> negate(MatchResult matchResult) {
return matchResult.isMatch() ? MatchResult.notMatch() : MatchResult.match();
}
@Override
public String toString() {
return "NegatedServerWebExchangeMatcher{" + "matcher=" + this.matcher + '}';
}
}
| 2,100 | 32.887097 | 103 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/server/util/matcher/MediaTypeServerWebExchangeMatcher.java | /*
* Copyright 2002-2017 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.web.server.util.matcher;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Mono;
import org.springframework.core.log.LogMessage;
import org.springframework.http.InvalidMediaTypeException;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.accept.ContentNegotiationStrategy;
import org.springframework.web.server.NotAcceptableStatusException;
import org.springframework.web.server.ServerWebExchange;
/**
* Matches based upon the accept headers.
*
* @author Rob Winch
* @since 5.0
*/
public class MediaTypeServerWebExchangeMatcher implements ServerWebExchangeMatcher {
private final Log logger = LogFactory.getLog(getClass());
private final Collection<MediaType> matchingMediaTypes;
private boolean useEquals;
private Set<MediaType> ignoredMediaTypes = Collections.emptySet();
/**
* Creates a new instance
* @param matchingMediaTypes the types to match on
*/
public MediaTypeServerWebExchangeMatcher(MediaType... matchingMediaTypes) {
Assert.notEmpty(matchingMediaTypes, "matchingMediaTypes cannot be null");
Assert.noNullElements(matchingMediaTypes, "matchingMediaTypes cannot contain null");
this.matchingMediaTypes = Arrays.asList(matchingMediaTypes);
}
/**
* Creates a new instance
* @param matchingMediaTypes the types to match on
*/
public MediaTypeServerWebExchangeMatcher(Collection<MediaType> matchingMediaTypes) {
Assert.notEmpty(matchingMediaTypes, "matchingMediaTypes cannot be null");
Assert.noNullElements(matchingMediaTypes,
() -> "matchingMediaTypes cannot contain null. Got " + matchingMediaTypes);
this.matchingMediaTypes = matchingMediaTypes;
}
@Override
public Mono<MatchResult> matches(ServerWebExchange exchange) {
List<MediaType> httpRequestMediaTypes;
try {
httpRequestMediaTypes = resolveMediaTypes(exchange);
}
catch (NotAcceptableStatusException ex) {
this.logger.debug("Failed to parse MediaTypes, returning false", ex);
return MatchResult.notMatch();
}
this.logger.debug(LogMessage.format("httpRequestMediaTypes=%s", httpRequestMediaTypes));
for (MediaType httpRequestMediaType : httpRequestMediaTypes) {
this.logger.debug(LogMessage.format("Processing %s", httpRequestMediaType));
if (shouldIgnore(httpRequestMediaType)) {
this.logger.debug("Ignoring");
continue;
}
if (this.useEquals) {
boolean isEqualTo = this.matchingMediaTypes.contains(httpRequestMediaType);
this.logger.debug("isEqualTo " + isEqualTo);
return isEqualTo ? MatchResult.match() : MatchResult.notMatch();
}
for (MediaType matchingMediaType : this.matchingMediaTypes) {
boolean isCompatibleWith = matchingMediaType.isCompatibleWith(httpRequestMediaType);
this.logger.debug(LogMessage.format("%s .isCompatibleWith %s = %s", matchingMediaType,
httpRequestMediaType, isCompatibleWith));
if (isCompatibleWith) {
return MatchResult.match();
}
}
}
this.logger.debug("Did not match any media types");
return MatchResult.notMatch();
}
private boolean shouldIgnore(MediaType httpRequestMediaType) {
for (MediaType ignoredMediaType : this.ignoredMediaTypes) {
if (httpRequestMediaType.includes(ignoredMediaType)) {
return true;
}
}
return false;
}
/**
* If set to true, matches on exact {@link MediaType}, else uses
* {@link MediaType#isCompatibleWith(MediaType)}.
* @param useEquals specify if equals comparison should be used.
*/
public void setUseEquals(boolean useEquals) {
this.useEquals = useEquals;
}
/**
* Set the {@link MediaType} to ignore from the {@link ContentNegotiationStrategy}.
* This is useful if for example, you want to match on
* {@link MediaType#APPLICATION_JSON} but want to ignore {@link MediaType#ALL}.
* @param ignoredMediaTypes the {@link MediaType}'s to ignore from the
* {@link ContentNegotiationStrategy}
*/
public void setIgnoredMediaTypes(Set<MediaType> ignoredMediaTypes) {
this.ignoredMediaTypes = ignoredMediaTypes;
}
private List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException {
try {
List<MediaType> mediaTypes = exchange.getRequest().getHeaders().getAccept();
MediaType.sortBySpecificityAndQuality(mediaTypes);
return mediaTypes;
}
catch (InvalidMediaTypeException ex) {
String value = exchange.getRequest().getHeaders().getFirst("Accept");
throw new NotAcceptableStatusException(
"Could not parse 'Accept' header [" + value + "]: " + ex.getMessage());
}
}
@Override
public String toString() {
return "MediaTypeRequestMatcher [matchingMediaTypes=" + this.matchingMediaTypes + ", useEquals="
+ this.useEquals + ", ignoredMediaTypes=" + this.ignoredMediaTypes + "]";
}
}
| 5,603 | 34.468354 | 108 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.