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/servletapi/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.
*/
/**
* Populates a Servlet request with a new Spring Security compliant
* {@code HttpServletRequestWrapper}.
* <p>
* To use, simply add the {@code SecurityContextHolderAwareRequestFilter} to the Spring
* Security filter chain.
*/
package org.springframework.security.web.servletapi;
| 911 | 35.48 | 87 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/servletapi/HttpServlet3RequestFactory.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.servletapi;
import java.io.IOException;
import java.util.List;
import jakarta.servlet.AsyncContext;
import jakarta.servlet.AsyncListener;
import jakarta.servlet.ServletContext;
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.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.concurrent.DelegatingSecurityContextRunnable;
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.WebAuthenticationDetailsSource;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* Provides integration with the Servlet 3 APIs. The additional methods that are
* integrated with can be found below:
*
* <ul>
* <li>{@link HttpServletRequest#authenticate(HttpServletResponse)} - Allows the user to
* determine if they are authenticated and if not send the user to the login page. See
* {@link #setAuthenticationEntryPoint(AuthenticationEntryPoint)}.</li>
* <li>{@link HttpServletRequest#login(String, String)} - Allows the user to authenticate
* using the {@link AuthenticationManager}. See
* {@link #setAuthenticationManager(AuthenticationManager)}.</li>
* <li>{@link HttpServletRequest#logout()} - Allows the user to logout using the
* {@link LogoutHandler}s configured in Spring Security. See
* {@link #setLogoutHandlers(List)}.</li>
* <li>{@link AsyncContext#start(Runnable)} - Automatically copy the
* {@link SecurityContext} from the {@link SecurityContextHolder} found on the Thread that
* invoked {@link AsyncContext#start(Runnable)} to the Thread that processes the
* {@link Runnable}.</li>
* </ul>
*
* @author Rob Winch
* @see SecurityContextHolderAwareRequestFilter
* @see Servlet3SecurityContextHolderAwareRequestWrapper
* @see SecurityContextAsyncContext
*/
final class HttpServlet3RequestFactory implements HttpServletRequestFactory {
private Log logger = LogFactory.getLog(getClass());
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private final String rolePrefix;
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
private final AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
private AuthenticationEntryPoint authenticationEntryPoint;
private AuthenticationManager authenticationManager;
private List<LogoutHandler> logoutHandlers;
private SecurityContextRepository securityContextRepository;
HttpServlet3RequestFactory(String rolePrefix, SecurityContextRepository securityContextRepository) {
this.rolePrefix = rolePrefix;
this.securityContextRepository = securityContextRepository;
}
/**
* <p>
* Sets the {@link AuthenticationEntryPoint} used when integrating
* {@link HttpServletRequest} with Servlet 3 APIs. Specifically, it will be used when
* {@link HttpServletRequest#authenticate(HttpServletResponse)} is called and the user
* is not authenticated.
* </p>
* <p>
* If the value is null (default), then the default container behavior will be be
* retained when invoking {@link HttpServletRequest#authenticate(HttpServletResponse)}
* .
* </p>
* @param authenticationEntryPoint the {@link AuthenticationEntryPoint} to use when
* invoking {@link HttpServletRequest#authenticate(HttpServletResponse)} if the user
* is not authenticated.
*/
void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) {
this.authenticationEntryPoint = authenticationEntryPoint;
}
/**
* <p>
* Sets the {@link AuthenticationManager} used when integrating
* {@link HttpServletRequest} with Servlet 3 APIs. Specifically, it will be used when
* {@link HttpServletRequest#login(String, String)} is invoked to determine if the
* user is authenticated.
* </p>
* <p>
* If the value is null (default), then the default container behavior will be
* retained when invoking {@link HttpServletRequest#login(String, String)}.
* </p>
* @param authenticationManager the {@link AuthenticationManager} to use when invoking
* {@link HttpServletRequest#login(String, String)}
*/
void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
/**
* <p>
* Sets the {@link LogoutHandler}s used when integrating with
* {@link HttpServletRequest} with Servlet 3 APIs. Specifically it will be used when
* {@link HttpServletRequest#logout()} is invoked in order to log the user out. So
* long as the {@link LogoutHandler}s do not commit the {@link HttpServletResponse}
* (expected), then the user is in charge of handling the response.
* </p>
* <p>
* If the value is null (default), the default container behavior will be retained
* when invoking {@link HttpServletRequest#logout()}.
* </p>
* @param logoutHandlers the {@code List<LogoutHandler>}s when invoking
* {@link HttpServletRequest#logout()}.
*/
void setLogoutHandlers(List<LogoutHandler> logoutHandlers) {
this.logoutHandlers = logoutHandlers;
}
/**
* Sets the {@link AuthenticationTrustResolver} to be used. The default is
* {@link AuthenticationTrustResolverImpl}.
* @param trustResolver the {@link AuthenticationTrustResolver} to use. Cannot be
* null.
*/
void setTrustResolver(AuthenticationTrustResolver trustResolver) {
Assert.notNull(trustResolver, "trustResolver cannot be null");
this.trustResolver = trustResolver;
}
void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
@Override
public HttpServletRequest create(HttpServletRequest request, HttpServletResponse response) {
Servlet3SecurityContextHolderAwareRequestWrapper wrapper = new Servlet3SecurityContextHolderAwareRequestWrapper(
request, this.rolePrefix, response);
wrapper.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);
return wrapper;
}
private class Servlet3SecurityContextHolderAwareRequestWrapper extends SecurityContextHolderAwareRequestWrapper {
private final HttpServletResponse response;
Servlet3SecurityContextHolderAwareRequestWrapper(HttpServletRequest request, String rolePrefix,
HttpServletResponse response) {
super(request, HttpServlet3RequestFactory.this.trustResolver, rolePrefix);
this.response = response;
}
@Override
public AsyncContext getAsyncContext() {
AsyncContext asyncContext = super.getAsyncContext();
if (asyncContext == null) {
return null;
}
return new SecurityContextAsyncContext(asyncContext);
}
@Override
public AsyncContext startAsync() {
AsyncContext startAsync = super.startAsync();
return new SecurityContextAsyncContext(startAsync);
}
@Override
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse)
throws IllegalStateException {
AsyncContext startAsync = super.startAsync(servletRequest, servletResponse);
return new SecurityContextAsyncContext(startAsync);
}
@Override
public boolean authenticate(HttpServletResponse response) throws IOException, ServletException {
AuthenticationEntryPoint entryPoint = HttpServlet3RequestFactory.this.authenticationEntryPoint;
if (entryPoint == null) {
HttpServlet3RequestFactory.this.logger.debug(
"authenticationEntryPoint is null, so allowing original HttpServletRequest to handle authenticate");
return super.authenticate(response);
}
if (isAuthenticated()) {
return true;
}
entryPoint.commence(this, response,
new AuthenticationCredentialsNotFoundException("User is not Authenticated"));
return false;
}
@Override
public void login(String username, String password) throws ServletException {
if (isAuthenticated()) {
throw new ServletException("Cannot perform login for '" + username + "' already authenticated as '"
+ getRemoteUser() + "'");
}
AuthenticationManager authManager = HttpServlet3RequestFactory.this.authenticationManager;
if (authManager == null) {
HttpServlet3RequestFactory.this.logger.debug(
"authenticationManager is null, so allowing original HttpServletRequest to handle login");
super.login(username, password);
return;
}
Authentication authentication = getAuthentication(authManager, username, password);
SecurityContext context = HttpServlet3RequestFactory.this.securityContextHolderStrategy
.createEmptyContext();
context.setAuthentication(authentication);
HttpServlet3RequestFactory.this.securityContextHolderStrategy.setContext(context);
HttpServlet3RequestFactory.this.securityContextRepository.saveContext(context, this, this.response);
}
private Authentication getAuthentication(AuthenticationManager authManager, String username, String password)
throws ServletException {
try {
UsernamePasswordAuthenticationToken authentication = UsernamePasswordAuthenticationToken
.unauthenticated(username, password);
Object details = HttpServlet3RequestFactory.this.authenticationDetailsSource.buildDetails(this);
authentication.setDetails(details);
return authManager.authenticate(authentication);
}
catch (AuthenticationException ex) {
HttpServlet3RequestFactory.this.securityContextHolderStrategy.clearContext();
throw new ServletException(ex.getMessage(), ex);
}
}
@Override
public void logout() throws ServletException {
List<LogoutHandler> handlers = HttpServlet3RequestFactory.this.logoutHandlers;
if (CollectionUtils.isEmpty(handlers)) {
HttpServlet3RequestFactory.this.logger
.debug("logoutHandlers is null, so allowing original HttpServletRequest to handle logout");
super.logout();
return;
}
Authentication authentication = HttpServlet3RequestFactory.this.securityContextHolderStrategy.getContext()
.getAuthentication();
for (LogoutHandler handler : handlers) {
handler.logout(this, this.response, authentication);
}
}
private boolean isAuthenticated() {
return getUserPrincipal() != null;
}
}
private static class SecurityContextAsyncContext implements AsyncContext {
private final AsyncContext asyncContext;
SecurityContextAsyncContext(AsyncContext asyncContext) {
this.asyncContext = asyncContext;
}
@Override
public ServletRequest getRequest() {
return this.asyncContext.getRequest();
}
@Override
public ServletResponse getResponse() {
return this.asyncContext.getResponse();
}
@Override
public boolean hasOriginalRequestAndResponse() {
return this.asyncContext.hasOriginalRequestAndResponse();
}
@Override
public void dispatch() {
this.asyncContext.dispatch();
}
@Override
public void dispatch(String path) {
this.asyncContext.dispatch(path);
}
@Override
public void dispatch(ServletContext context, String path) {
this.asyncContext.dispatch(context, path);
}
@Override
public void complete() {
this.asyncContext.complete();
}
@Override
public void start(Runnable run) {
this.asyncContext.start(new DelegatingSecurityContextRunnable(run));
}
@Override
public void addListener(AsyncListener listener) {
this.asyncContext.addListener(listener);
}
@Override
public void addListener(AsyncListener listener, ServletRequest request, ServletResponse response) {
this.asyncContext.addListener(listener, request, response);
}
@Override
public <T extends AsyncListener> T createListener(Class<T> clazz) throws ServletException {
return this.asyncContext.createListener(clazz);
}
@Override
public long getTimeout() {
return this.asyncContext.getTimeout();
}
@Override
public void setTimeout(long timeout) {
this.asyncContext.setTimeout(timeout);
}
}
}
| 13,845 | 36.72752 | 133 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestWrapper.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.servletapi;
import java.security.Principal;
import java.util.Collection;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;
/**
* A Spring Security-aware <code>HttpServletRequestWrapper</code>, which uses the
* <code>SecurityContext</code>-defined <code>Authentication</code> object to implement
* the servlet API security methods:
*
* <ul>
* <li>{@link #getUserPrincipal()}</li>
* <li>{@link SecurityContextHolderAwareRequestWrapper#isUserInRole(String)}</li>
* <li>{@link HttpServletRequestWrapper#getRemoteUser()}.</li>
* </ul>
*
* @author Orlando Garcia Carmona
* @author Ben Alex
* @author Luke Taylor
* @author Rob Winch
* @see SecurityContextHolderAwareRequestFilter
*/
public class SecurityContextHolderAwareRequestWrapper extends HttpServletRequestWrapper {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private final AuthenticationTrustResolver trustResolver;
/**
* The prefix passed by the filter. It will be prepended to any supplied role values
* before comparing it with the roles obtained from the security context.
*/
private final String rolePrefix;
/**
* Creates a new instance with {@link AuthenticationTrustResolverImpl}.
* @param request
* @param rolePrefix
*/
public SecurityContextHolderAwareRequestWrapper(HttpServletRequest request, String rolePrefix) {
this(request, new AuthenticationTrustResolverImpl(), rolePrefix);
}
/**
* Creates a new instance
* @param request the original {@link HttpServletRequest}
* @param trustResolver the {@link AuthenticationTrustResolver} to use. Cannot be
* null.
* @param rolePrefix The prefix to be added to {@link #isUserInRole(String)} or null
* if no prefix.
*/
public SecurityContextHolderAwareRequestWrapper(HttpServletRequest request,
AuthenticationTrustResolver trustResolver, String rolePrefix) {
super(request);
Assert.notNull(trustResolver, "trustResolver cannot be null");
this.rolePrefix = rolePrefix;
this.trustResolver = trustResolver;
}
/**
* Obtain the current active <code>Authentication</code>
* @return the authentication object or <code>null</code>
*/
private Authentication getAuthentication() {
Authentication auth = this.securityContextHolderStrategy.getContext().getAuthentication();
return (!this.trustResolver.isAnonymous(auth)) ? auth : null;
}
/**
* Returns the principal's name, as obtained from the
* <code>SecurityContextHolder</code>. Properly handles both <code>String</code>-based
* and <code>UserDetails</code>-based principals.
* @return the username or <code>null</code> if unavailable
*/
@Override
public String getRemoteUser() {
Authentication auth = getAuthentication();
if ((auth == null) || (auth.getPrincipal() == null)) {
return null;
}
if (auth.getPrincipal() instanceof UserDetails) {
return ((UserDetails) auth.getPrincipal()).getUsername();
}
if (auth instanceof AbstractAuthenticationToken) {
return auth.getName();
}
return auth.getPrincipal().toString();
}
/**
* Returns the <code>Authentication</code> (which is a subclass of
* <code>Principal</code>), or <code>null</code> if unavailable.
* @return the <code>Authentication</code>, or <code>null</code>
*/
@Override
public Principal getUserPrincipal() {
Authentication auth = getAuthentication();
if ((auth == null) || (auth.getPrincipal() == null)) {
return null;
}
return auth;
}
private boolean isGranted(String role) {
Authentication auth = getAuthentication();
if (this.rolePrefix != null && role != null && !role.startsWith(this.rolePrefix)) {
role = this.rolePrefix + role;
}
if ((auth == null) || (auth.getPrincipal() == null)) {
return false;
}
Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
if (authorities == null) {
return false;
}
for (GrantedAuthority grantedAuthority : authorities) {
if (role.equals(grantedAuthority.getAuthority())) {
return true;
}
}
return false;
}
/**
* Simple searches for an exactly matching
* {@link org.springframework.security.core.GrantedAuthority#getAuthority()}.
* <p>
* Will always return <code>false</code> if the <code>SecurityContextHolder</code>
* contains an <code>Authentication</code> with <code>null</code>
* <code>principal</code> and/or <code>GrantedAuthority[]</code> objects.
* @param role the <code>GrantedAuthority</code><code>String</code> representation to
* check for
* @return <code>true</code> if an <b>exact</b> (case sensitive) matching granted
* authority is located, <code>false</code> otherwise
*/
@Override
public boolean isUserInRole(String role) {
return isGranted(role);
}
@Override
public String toString() {
return "SecurityContextHolderAwareRequestWrapper[ " + getRequest() + "]";
}
/**
* 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;
}
}
| 6,688 | 34.579787 | 108 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/servletapi/HttpServletRequestFactory.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.servletapi;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Internal interface for creating a {@link HttpServletRequest}.
*
* @author Rob Winch
* @since 3.2
* @see HttpServlet3RequestFactory
*/
interface HttpServletRequestFactory {
/**
* Given a {@link HttpServletRequest} returns a {@link HttpServletRequest} that in
* most cases wraps the original {@link HttpServletRequest}.
* @param request the original {@link HttpServletRequest}. Cannot be null.
* @param response the original {@link HttpServletResponse}. Cannot be null.
* @return a non-null HttpServletRequest
*/
HttpServletRequest create(HttpServletRequest request, HttpServletResponse response);
}
| 1,401 | 33.195122 | 85 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilter.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.servletapi;
import java.io.IOException;
import java.util.List;
import jakarta.servlet.AsyncContext;
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.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
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.logout.LogoutHandler;
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;
/**
* A <code>Filter</code> which populates the <code>ServletRequest</code> with a request
* wrapper which implements the servlet API security methods.
* <p>
* {@link SecurityContextHolderAwareRequestWrapper} is extended to provide the following
* additional methods:
* </p>
* <ul>
* <li>{@link HttpServletRequest#authenticate(HttpServletResponse)} - Allows the user to
* determine if they are authenticated and if not send the user to the login page. See
* {@link #setAuthenticationEntryPoint(AuthenticationEntryPoint)}.</li>
* <li>{@link HttpServletRequest#login(String, String)} - Allows the user to authenticate
* using the {@link AuthenticationManager}. See
* {@link #setAuthenticationManager(AuthenticationManager)}.</li>
* <li>{@link HttpServletRequest#logout()} - Allows the user to logout using the
* {@link LogoutHandler}s configured in Spring Security. See
* {@link #setLogoutHandlers(List)}.</li>
* <li>{@link AsyncContext#start(Runnable)} - Automatically copy the
* {@link SecurityContext} from the {@link SecurityContextHolder} found on the Thread that
* invoked {@link AsyncContext#start(Runnable)} to the Thread that processes the
* {@link Runnable}.</li>
* </ul>
*
* @author Orlando Garcia Carmona
* @author Ben Alex
* @author Luke Taylor
* @author Rob Winch
* @author Eddú Meléndez
*/
public class SecurityContextHolderAwareRequestFilter extends GenericFilterBean {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private String rolePrefix = "ROLE_";
private HttpServletRequestFactory requestFactory;
private AuthenticationEntryPoint authenticationEntryPoint;
private AuthenticationManager authenticationManager;
private List<LogoutHandler> logoutHandlers;
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
private SecurityContextRepository securityContextRepository = new HttpSessionSecurityContextRepository();
/**
* Sets the {@link SecurityContextRepository} to use. The default is to use
* {@link HttpSessionSecurityContextRepository}.
* @param securityContextRepository the {@link SecurityContextRepository} to use.
* @since 6.0
*/
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;
}
public void setRolePrefix(String rolePrefix) {
Assert.notNull(rolePrefix, "Role prefix must not be null");
this.rolePrefix = rolePrefix;
updateFactory();
}
/**
* <p>
* Sets the {@link AuthenticationEntryPoint} used when integrating
* {@link HttpServletRequest} with Servlet 3 APIs. Specifically, it will be used when
* {@link HttpServletRequest#authenticate(HttpServletResponse)} is called and the user
* is not authenticated.
* </p>
* <p>
* If the value is null (default), then the default container behavior will be be
* retained when invoking {@link HttpServletRequest#authenticate(HttpServletResponse)}
* .
* </p>
* @param authenticationEntryPoint the {@link AuthenticationEntryPoint} to use when
* invoking {@link HttpServletRequest#authenticate(HttpServletResponse)} if the user
* is not authenticated.
*/
public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) {
this.authenticationEntryPoint = authenticationEntryPoint;
}
/**
* <p>
* Sets the {@link AuthenticationManager} used when integrating
* {@link HttpServletRequest} with Servlet 3 APIs. Specifically, it will be used when
* {@link HttpServletRequest#login(String, String)} is invoked to determine if the
* user is authenticated.
* </p>
* <p>
* If the value is null (default), then the default container behavior will be
* retained when invoking {@link HttpServletRequest#login(String, String)}.
* </p>
* @param authenticationManager the {@link AuthenticationManager} to use when invoking
* {@link HttpServletRequest#login(String, String)}
*/
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
/**
* <p>
* Sets the {@link LogoutHandler}s used when integrating with
* {@link HttpServletRequest} with Servlet 3 APIs. Specifically it will be used when
* {@link HttpServletRequest#logout()} is invoked in order to log the user out. So
* long as the {@link LogoutHandler}s do not commit the {@link HttpServletResponse}
* (expected), then the user is in charge of handling the response.
* </p>
* <p>
* If the value is null (default), the default container behavior will be retained
* when invoking {@link HttpServletRequest#logout()}.
* </p>
* @param logoutHandlers the {@code List<LogoutHandler>}s when invoking
* {@link HttpServletRequest#logout()}.
*/
public void setLogoutHandlers(List<LogoutHandler> logoutHandlers) {
this.logoutHandlers = logoutHandlers;
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
chain.doFilter(this.requestFactory.create((HttpServletRequest) req, (HttpServletResponse) res), res);
}
@Override
public void afterPropertiesSet() throws ServletException {
super.afterPropertiesSet();
updateFactory();
}
private void updateFactory() {
String rolePrefix = this.rolePrefix;
this.requestFactory = createServlet3Factory(rolePrefix);
}
/**
* Sets the {@link AuthenticationTrustResolver} to be used. The default is
* {@link AuthenticationTrustResolverImpl}.
* @param trustResolver the {@link AuthenticationTrustResolver} to use. Cannot be
* null.
*/
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
Assert.notNull(trustResolver, "trustResolver cannot be null");
this.trustResolver = trustResolver;
updateFactory();
}
private HttpServletRequestFactory createServlet3Factory(String rolePrefix) {
HttpServlet3RequestFactory factory = new HttpServlet3RequestFactory(rolePrefix, this.securityContextRepository);
factory.setTrustResolver(this.trustResolver);
factory.setAuthenticationEntryPoint(this.authenticationEntryPoint);
factory.setAuthenticationManager(this.authenticationManager);
factory.setLogoutHandlers(this.logoutHandlers);
factory.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);
return factory;
}
}
| 8,862 | 40.032407 | 114 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/firewall/ObservationMarkingRequestRejectedHandler.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.firewall;
import java.io.IOException;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationRegistry;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public final class ObservationMarkingRequestRejectedHandler implements RequestRejectedHandler {
private final ObservationRegistry registry;
public ObservationMarkingRequestRejectedHandler(ObservationRegistry registry) {
this.registry = registry;
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, RequestRejectedException exception)
throws IOException, ServletException {
Observation observation = this.registry.getCurrentObservation();
if (observation != null) {
observation.error(exception);
}
}
}
| 1,505 | 32.466667 | 113 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/firewall/CompositeRequestRejectedHandler.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.firewall;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.Assert;
/**
* A {@link RequestRejectedHandler} that delegates to several other
* {@link RequestRejectedHandler}s.
*
* @author Adam Ostrožlík
* @since 5.7
*/
public final class CompositeRequestRejectedHandler implements RequestRejectedHandler {
private final List<RequestRejectedHandler> requestRejectedhandlers;
/**
* Creates a new instance.
* @param requestRejectedhandlers the {@link RequestRejectedHandler} instances to
* handle {@link org.springframework.security.web.firewall.RequestRejectedException}
*/
public CompositeRequestRejectedHandler(RequestRejectedHandler... requestRejectedhandlers) {
Assert.notEmpty(requestRejectedhandlers, "requestRejectedhandlers cannot be empty");
this.requestRejectedhandlers = Arrays.asList(requestRejectedhandlers);
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
RequestRejectedException requestRejectedException) throws IOException, ServletException {
for (RequestRejectedHandler requestRejectedhandler : this.requestRejectedhandlers) {
requestRejectedhandler.handle(request, response, requestRejectedException);
}
}
}
| 2,067 | 34.050847 | 92 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/firewall/RequestRejectedHandler.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.firewall;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Used by {@link org.springframework.security.web.FilterChainProxy} to handle an
* <code>RequestRejectedException</code>.
*
* @author Leonard Brünings
* @since 5.4
*/
public interface RequestRejectedHandler {
/**
* Handles an request rejected failure.
* @param request that resulted in an <code>RequestRejectedException</code>
* @param response so that the user agent can be advised of the failure
* @param requestRejectedException that caused the invocation
* @throws IOException in the event of an IOException
* @throws ServletException in the event of a ServletException
*/
void handle(HttpServletRequest request, HttpServletResponse response,
RequestRejectedException requestRejectedException) throws IOException, ServletException;
}
| 1,612 | 34.065217 | 91 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/firewall/FirewalledResponse.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.firewall;
import java.io.IOException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;
import org.springframework.util.Assert;
/**
* @author Luke Taylor
* @author Eddú Meléndez
* @author Gabriel Lavoie
* @author Luke Butters
*/
class FirewalledResponse extends HttpServletResponseWrapper {
private static final String LOCATION_HEADER = "Location";
private static final String SET_COOKIE_HEADER = "Set-Cookie";
FirewalledResponse(HttpServletResponse response) {
super(response);
}
@Override
public void sendRedirect(String location) throws IOException {
// TODO: implement pluggable validation, instead of simple blocklist.
// SEC-1790. Prevent redirects containing CRLF
validateCrlf(LOCATION_HEADER, location);
super.sendRedirect(location);
}
@Override
public void setHeader(String name, String value) {
validateCrlf(name, value);
super.setHeader(name, value);
}
@Override
public void addHeader(String name, String value) {
validateCrlf(name, value);
super.addHeader(name, value);
}
@Override
public void addCookie(Cookie cookie) {
if (cookie != null) {
validateCrlf(SET_COOKIE_HEADER, cookie.getName());
validateCrlf(SET_COOKIE_HEADER, cookie.getValue());
validateCrlf(SET_COOKIE_HEADER, cookie.getPath());
validateCrlf(SET_COOKIE_HEADER, cookie.getDomain());
validateCrlf(SET_COOKIE_HEADER, cookie.getComment());
}
super.addCookie(cookie);
}
void validateCrlf(String name, String value) {
Assert.isTrue(!hasCrlf(name) && !hasCrlf(value), () -> "Invalid characters (CR/LF) in header " + name);
}
private boolean hasCrlf(String value) {
return value != null && (value.indexOf('\n') != -1 || value.indexOf('\r') != -1);
}
}
| 2,461 | 28.309524 | 105 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/firewall/StrictHttpFirewall.java | /*
* Copyright 2012-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.firewall;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpMethod;
import org.springframework.util.Assert;
/**
* <p>
* A strict implementation of {@link HttpFirewall} that rejects any suspicious requests
* with a {@link RequestRejectedException}.
* </p>
* <p>
* The following rules are applied to the firewall:
* </p>
* <ul>
* <li>Rejects HTTP methods that are not allowed. This specified to block
* <a href="https://www.owasp.org/index.php/Test_HTTP_Methods_(OTG-CONFIG-006)">HTTP Verb
* tampering and XST attacks</a>. See {@link #setAllowedHttpMethods(Collection)}</li>
* <li>Rejects URLs that are not normalized to avoid bypassing security constraints. There
* is no way to disable this as it is considered extremely risky to disable this
* constraint. A few options to allow this behavior is to normalize the request prior to
* the firewall or using {@link DefaultHttpFirewall} instead. Please keep in mind that
* normalizing the request is fragile and why requests are rejected rather than
* normalized.</li>
* <li>Rejects URLs that contain characters that are not printable ASCII characters. There
* is no way to disable this as it is considered extremely risky to disable this
* constraint.</li>
* <li>Rejects URLs that contain semicolons. See {@link #setAllowSemicolon(boolean)}</li>
* <li>Rejects URLs that contain a URL encoded slash. See
* {@link #setAllowUrlEncodedSlash(boolean)}</li>
* <li>Rejects URLs that contain a backslash. See {@link #setAllowBackSlash(boolean)}</li>
* <li>Rejects URLs that contain a null character. See {@link #setAllowNull(boolean)}</li>
* <li>Rejects URLs that contain a URL encoded percent. See
* {@link #setAllowUrlEncodedPercent(boolean)}</li>
* <li>Rejects hosts that are not allowed. See {@link #setAllowedHostnames(Predicate)}
* </li>
* <li>Reject headers names that are not allowed. See
* {@link #setAllowedHeaderNames(Predicate)}</li>
* <li>Reject headers values that are not allowed. See
* {@link #setAllowedHeaderValues(Predicate)}</li>
* <li>Reject parameter names that are not allowed. See
* {@link #setAllowedParameterNames(Predicate)}</li>
* <li>Reject parameter values that are not allowed. See
* {@link #setAllowedParameterValues(Predicate)}</li>
* </ul>
*
* @author Rob Winch
* @author Eddú Meléndez
* @since 4.2.4
* @see DefaultHttpFirewall
*/
public class StrictHttpFirewall implements HttpFirewall {
/**
* Used to specify to {@link #setAllowedHttpMethods(Collection)} that any HTTP method
* should be allowed.
*/
private static final Set<String> ALLOW_ANY_HTTP_METHOD = Collections.emptySet();
private static final String ENCODED_PERCENT = "%25";
private static final String PERCENT = "%";
private static final List<String> FORBIDDEN_ENCODED_PERIOD = Collections
.unmodifiableList(Arrays.asList("%2e", "%2E"));
private static final List<String> FORBIDDEN_SEMICOLON = Collections
.unmodifiableList(Arrays.asList(";", "%3b", "%3B"));
private static final List<String> FORBIDDEN_FORWARDSLASH = Collections
.unmodifiableList(Arrays.asList("%2f", "%2F"));
private static final List<String> FORBIDDEN_DOUBLE_FORWARDSLASH = Collections
.unmodifiableList(Arrays.asList("//", "%2f%2f", "%2f%2F", "%2F%2f", "%2F%2F"));
private static final List<String> FORBIDDEN_BACKSLASH = Collections
.unmodifiableList(Arrays.asList("\\", "%5c", "%5C"));
private static final List<String> FORBIDDEN_NULL = Collections.unmodifiableList(Arrays.asList("\0", "%00"));
private static final List<String> FORBIDDEN_LF = Collections.unmodifiableList(Arrays.asList("\n", "%0a", "%0A"));
private static final List<String> FORBIDDEN_CR = Collections.unmodifiableList(Arrays.asList("\r", "%0d", "%0D"));
private static final List<String> FORBIDDEN_LINE_SEPARATOR = Collections.unmodifiableList(Arrays.asList("\u2028"));
private static final List<String> FORBIDDEN_PARAGRAPH_SEPARATOR = Collections
.unmodifiableList(Arrays.asList("\u2029"));
private Set<String> encodedUrlBlocklist = new HashSet<>();
private Set<String> decodedUrlBlocklist = new HashSet<>();
private Set<String> allowedHttpMethods = createDefaultAllowedHttpMethods();
private Predicate<String> allowedHostnames = (hostname) -> true;
private static final Pattern ASSIGNED_AND_NOT_ISO_CONTROL_PATTERN = Pattern
.compile("[\\p{IsAssigned}&&[^\\p{IsControl}]]*");
private static final Predicate<String> ASSIGNED_AND_NOT_ISO_CONTROL_PREDICATE = (
s) -> ASSIGNED_AND_NOT_ISO_CONTROL_PATTERN.matcher(s).matches();
private Predicate<String> allowedHeaderNames = ASSIGNED_AND_NOT_ISO_CONTROL_PREDICATE;
private Predicate<String> allowedHeaderValues = ASSIGNED_AND_NOT_ISO_CONTROL_PREDICATE;
private Predicate<String> allowedParameterNames = ASSIGNED_AND_NOT_ISO_CONTROL_PREDICATE;
private Predicate<String> allowedParameterValues = (value) -> true;
public StrictHttpFirewall() {
urlBlocklistsAddAll(FORBIDDEN_SEMICOLON);
urlBlocklistsAddAll(FORBIDDEN_FORWARDSLASH);
urlBlocklistsAddAll(FORBIDDEN_DOUBLE_FORWARDSLASH);
urlBlocklistsAddAll(FORBIDDEN_BACKSLASH);
urlBlocklistsAddAll(FORBIDDEN_NULL);
urlBlocklistsAddAll(FORBIDDEN_LF);
urlBlocklistsAddAll(FORBIDDEN_CR);
this.encodedUrlBlocklist.add(ENCODED_PERCENT);
this.encodedUrlBlocklist.addAll(FORBIDDEN_ENCODED_PERIOD);
this.decodedUrlBlocklist.add(PERCENT);
this.decodedUrlBlocklist.addAll(FORBIDDEN_LINE_SEPARATOR);
this.decodedUrlBlocklist.addAll(FORBIDDEN_PARAGRAPH_SEPARATOR);
}
/**
* Sets if any HTTP method is allowed. If this set to true, then no validation on the
* HTTP method will be performed. This can open the application up to
* <a href="https://www.owasp.org/index.php/Test_HTTP_Methods_(OTG-CONFIG-006)"> HTTP
* Verb tampering and XST attacks</a>
* @param unsafeAllowAnyHttpMethod if true, disables HTTP method validation, else
* resets back to the defaults. Default is false.
* @since 5.1
* @see #setAllowedHttpMethods(Collection)
*/
public void setUnsafeAllowAnyHttpMethod(boolean unsafeAllowAnyHttpMethod) {
this.allowedHttpMethods = unsafeAllowAnyHttpMethod ? ALLOW_ANY_HTTP_METHOD : createDefaultAllowedHttpMethods();
}
/**
* <p>
* Determines which HTTP methods should be allowed. The default is to allow "DELETE",
* "GET", "HEAD", "OPTIONS", "PATCH", "POST", and "PUT".
* </p>
* @param allowedHttpMethods the case-sensitive collection of HTTP methods that are
* allowed.
* @since 5.1
* @see #setUnsafeAllowAnyHttpMethod(boolean)
*/
public void setAllowedHttpMethods(Collection<String> allowedHttpMethods) {
Assert.notNull(allowedHttpMethods, "allowedHttpMethods cannot be null");
this.allowedHttpMethods = (allowedHttpMethods != ALLOW_ANY_HTTP_METHOD) ? new HashSet<>(allowedHttpMethods)
: ALLOW_ANY_HTTP_METHOD;
}
/**
* <p>
* Determines if semicolon is allowed in the URL (i.e. matrix variables). The default
* is to disable this behavior because it is a common way of attempting to perform
* <a href="https://www.owasp.org/index.php/Reflected_File_Download">Reflected File
* Download Attacks</a>. It is also the source of many exploits which bypass URL based
* security.
* </p>
* <p>
* For example, the following CVEs are a subset of the issues related to ambiguities
* in the Servlet Specification on how to treat semicolons that led to CVEs:
* </p>
* <ul>
* <li><a href="https://pivotal.io/security/cve-2016-5007">cve-2016-5007</a></li>
* <li><a href="https://pivotal.io/security/cve-2016-9879">cve-2016-9879</a></li>
* <li><a href="https://pivotal.io/security/cve-2018-1199">cve-2018-1199</a></li>
* </ul>
*
* <p>
* If you are wanting to allow semicolons, please reconsider as it is a very common
* source of security bypasses. A few common reasons users want semicolons and
* alternatives are listed below:
* </p>
* <ul>
* <li>Including the JSESSIONID in the path - You should not include session id (or
* any sensitive information) in a URL as it can lead to leaking. Instead use Cookies.
* </li>
* <li>Matrix Variables - Users wanting to leverage Matrix Variables should consider
* using HTTP parameters instead.</li>
* </ul>
* @param allowSemicolon should semicolons be allowed in the URL. Default is false
*/
public void setAllowSemicolon(boolean allowSemicolon) {
if (allowSemicolon) {
urlBlocklistsRemoveAll(FORBIDDEN_SEMICOLON);
}
else {
urlBlocklistsAddAll(FORBIDDEN_SEMICOLON);
}
}
/**
* <p>
* Determines if a slash "/" that is URL encoded "%2F" should be allowed in the path
* or not. The default is to not allow this behavior because it is a common way to
* bypass URL based security.
* </p>
* <p>
* For example, due to ambiguities in the servlet specification, the value is not
* parsed consistently which results in different values in {@code HttpServletRequest}
* path related values which allow bypassing certain security constraints.
* </p>
* @param allowUrlEncodedSlash should a slash "/" that is URL encoded "%2F" be allowed
* in the path or not. Default is false.
*/
public void setAllowUrlEncodedSlash(boolean allowUrlEncodedSlash) {
if (allowUrlEncodedSlash) {
urlBlocklistsRemoveAll(FORBIDDEN_FORWARDSLASH);
}
else {
urlBlocklistsAddAll(FORBIDDEN_FORWARDSLASH);
}
}
/**
* <p>
* Determines if double slash "//" that is URL encoded "%2F%2F" should be allowed in
* the path or not. The default is to not allow.
* </p>
* @param allowUrlEncodedDoubleSlash should a slash "//" that is URL encoded "%2F%2F"
* be allowed in the path or not. Default is false.
*/
public void setAllowUrlEncodedDoubleSlash(boolean allowUrlEncodedDoubleSlash) {
if (allowUrlEncodedDoubleSlash) {
urlBlocklistsRemoveAll(FORBIDDEN_DOUBLE_FORWARDSLASH);
}
else {
urlBlocklistsAddAll(FORBIDDEN_DOUBLE_FORWARDSLASH);
}
}
/**
* <p>
* Determines if a period "." that is URL encoded "%2E" should be allowed in the path
* or not. The default is to not allow this behavior because it is a frequent source
* of security exploits.
* </p>
* <p>
* For example, due to ambiguities in the servlet specification a URL encoded period
* might lead to bypassing security constraints through a directory traversal attack.
* This is because the path is not parsed consistently which results in different
* values in {@code HttpServletRequest} path related values which allow bypassing
* certain security constraints.
* </p>
* @param allowUrlEncodedPeriod should a period "." that is URL encoded "%2E" be
* allowed in the path or not. Default is false.
*/
public void setAllowUrlEncodedPeriod(boolean allowUrlEncodedPeriod) {
if (allowUrlEncodedPeriod) {
this.encodedUrlBlocklist.removeAll(FORBIDDEN_ENCODED_PERIOD);
}
else {
this.encodedUrlBlocklist.addAll(FORBIDDEN_ENCODED_PERIOD);
}
}
/**
* <p>
* Determines if a backslash "\" or a URL encoded backslash "%5C" should be allowed in
* the path or not. The default is not to allow this behavior because it is a frequent
* source of security exploits.
* </p>
* <p>
* For example, due to ambiguities in the servlet specification a URL encoded period
* might lead to bypassing security constraints through a directory traversal attack.
* This is because the path is not parsed consistently which results in different
* values in {@code HttpServletRequest} path related values which allow bypassing
* certain security constraints.
* </p>
* @param allowBackSlash a backslash "\" or a URL encoded backslash "%5C" be allowed
* in the path or not. Default is false
*/
public void setAllowBackSlash(boolean allowBackSlash) {
if (allowBackSlash) {
urlBlocklistsRemoveAll(FORBIDDEN_BACKSLASH);
}
else {
urlBlocklistsAddAll(FORBIDDEN_BACKSLASH);
}
}
/**
* <p>
* Determines if a null "\0" or a URL encoded nul "%00" should be allowed in the path
* or not. The default is not to allow this behavior because it is a frequent source
* of security exploits.
* </p>
* @param allowNull a null "\0" or a URL encoded null "%00" be allowed in the path or
* not. Default is false
* @since 5.4
*/
public void setAllowNull(boolean allowNull) {
if (allowNull) {
urlBlocklistsRemoveAll(FORBIDDEN_NULL);
}
else {
urlBlocklistsAddAll(FORBIDDEN_NULL);
}
}
/**
* <p>
* Determines if a percent "%" that is URL encoded "%25" should be allowed in the path
* or not. The default is not to allow this behavior because it is a frequent source
* of security exploits.
* </p>
* <p>
* For example, this can lead to exploits that involve double URL encoding that lead
* to bypassing security constraints.
* </p>
* @param allowUrlEncodedPercent if a percent "%" that is URL encoded "%25" should be
* allowed in the path or not. Default is false
*/
public void setAllowUrlEncodedPercent(boolean allowUrlEncodedPercent) {
if (allowUrlEncodedPercent) {
this.encodedUrlBlocklist.remove(ENCODED_PERCENT);
this.decodedUrlBlocklist.remove(PERCENT);
}
else {
this.encodedUrlBlocklist.add(ENCODED_PERCENT);
this.decodedUrlBlocklist.add(PERCENT);
}
}
/**
* Determines if a URL encoded Carriage Return is allowed in the path or not. The
* default is not to allow this behavior because it is a frequent source of security
* exploits.
* @param allowUrlEncodedCarriageReturn if URL encoded Carriage Return is allowed in
* the URL or not. Default is false.
*/
public void setAllowUrlEncodedCarriageReturn(boolean allowUrlEncodedCarriageReturn) {
if (allowUrlEncodedCarriageReturn) {
urlBlocklistsRemoveAll(FORBIDDEN_CR);
}
else {
urlBlocklistsAddAll(FORBIDDEN_CR);
}
}
/**
* Determines if a URL encoded Line Feed is allowed in the path or not. The default is
* not to allow this behavior because it is a frequent source of security exploits.
* @param allowUrlEncodedLineFeed if URL encoded Line Feed is allowed in the URL or
* not. Default is false.
*/
public void setAllowUrlEncodedLineFeed(boolean allowUrlEncodedLineFeed) {
if (allowUrlEncodedLineFeed) {
urlBlocklistsRemoveAll(FORBIDDEN_LF);
}
else {
urlBlocklistsAddAll(FORBIDDEN_LF);
}
}
/**
* Determines if a URL encoded paragraph separator is allowed in the path or not. The
* default is not to allow this behavior because it is a frequent source of security
* exploits.
* @param allowUrlEncodedParagraphSeparator if URL encoded paragraph separator is
* allowed in the URL or not. Default is false.
*/
public void setAllowUrlEncodedParagraphSeparator(boolean allowUrlEncodedParagraphSeparator) {
if (allowUrlEncodedParagraphSeparator) {
this.decodedUrlBlocklist.removeAll(FORBIDDEN_PARAGRAPH_SEPARATOR);
}
else {
this.decodedUrlBlocklist.addAll(FORBIDDEN_PARAGRAPH_SEPARATOR);
}
}
/**
* Determines if a URL encoded line separator is allowed in the path or not. The
* default is not to allow this behavior because it is a frequent source of security
* exploits.
* @param allowUrlEncodedLineSeparator if URL encoded line separator is allowed in the
* URL or not. Default is false.
*/
public void setAllowUrlEncodedLineSeparator(boolean allowUrlEncodedLineSeparator) {
if (allowUrlEncodedLineSeparator) {
this.decodedUrlBlocklist.removeAll(FORBIDDEN_LINE_SEPARATOR);
}
else {
this.decodedUrlBlocklist.addAll(FORBIDDEN_LINE_SEPARATOR);
}
}
/**
* <p>
* Determines which header names should be allowed. The default is to reject header
* names that contain ISO control characters and characters that are not defined.
* </p>
* @param allowedHeaderNames the predicate for testing header names
* @since 5.4
* @see Character#isISOControl(int)
* @see Character#isDefined(int)
*/
public void setAllowedHeaderNames(Predicate<String> allowedHeaderNames) {
Assert.notNull(allowedHeaderNames, "allowedHeaderNames cannot be null");
this.allowedHeaderNames = allowedHeaderNames;
}
/**
* <p>
* Determines which header values should be allowed. The default is to reject header
* values that contain ISO control characters and characters that are not defined.
* </p>
* @param allowedHeaderValues the predicate for testing hostnames
* @since 5.4
* @see Character#isISOControl(int)
* @see Character#isDefined(int)
*/
public void setAllowedHeaderValues(Predicate<String> allowedHeaderValues) {
Assert.notNull(allowedHeaderValues, "allowedHeaderValues cannot be null");
this.allowedHeaderValues = allowedHeaderValues;
}
/**
* Determines which parameter names should be allowed. The default is to reject header
* names that contain ISO control characters and characters that are not defined.
* @param allowedParameterNames the predicate for testing parameter names
* @since 5.4
* @see Character#isISOControl(int)
* @see Character#isDefined(int)
*/
public void setAllowedParameterNames(Predicate<String> allowedParameterNames) {
Assert.notNull(allowedParameterNames, "allowedParameterNames cannot be null");
this.allowedParameterNames = allowedParameterNames;
}
/**
* <p>
* Determines which parameter values should be allowed. The default is to allow any
* parameter value.
* </p>
* @param allowedParameterValues the predicate for testing parameter values
* @since 5.4
*/
public void setAllowedParameterValues(Predicate<String> allowedParameterValues) {
Assert.notNull(allowedParameterValues, "allowedParameterValues cannot be null");
this.allowedParameterValues = allowedParameterValues;
}
/**
* <p>
* Determines which hostnames should be allowed. The default is to allow any hostname.
* </p>
* @param allowedHostnames the predicate for testing hostnames
* @since 5.2
*/
public void setAllowedHostnames(Predicate<String> allowedHostnames) {
Assert.notNull(allowedHostnames, "allowedHostnames cannot be null");
this.allowedHostnames = allowedHostnames;
}
private void urlBlocklistsAddAll(Collection<String> values) {
this.encodedUrlBlocklist.addAll(values);
this.decodedUrlBlocklist.addAll(values);
}
private void urlBlocklistsRemoveAll(Collection<String> values) {
this.encodedUrlBlocklist.removeAll(values);
this.decodedUrlBlocklist.removeAll(values);
}
@Override
public FirewalledRequest getFirewalledRequest(HttpServletRequest request) throws RequestRejectedException {
rejectForbiddenHttpMethod(request);
rejectedBlocklistedUrls(request);
rejectedUntrustedHosts(request);
if (!isNormalized(request)) {
throw new RequestRejectedException("The request was rejected because the URL was not normalized.");
}
rejectNonPrintableAsciiCharactersInFieldName(request.getRequestURI(), "requestURI");
return new StrictFirewalledRequest(request);
}
private void rejectNonPrintableAsciiCharactersInFieldName(String toCheck, String propertyName) {
if (!containsOnlyPrintableAsciiCharacters(toCheck)) {
throw new RequestRejectedException(String.format(
"The %s was rejected because it can only contain printable ASCII characters.", propertyName));
}
}
private void rejectForbiddenHttpMethod(HttpServletRequest request) {
if (this.allowedHttpMethods == ALLOW_ANY_HTTP_METHOD) {
return;
}
if (!this.allowedHttpMethods.contains(request.getMethod())) {
throw new RequestRejectedException(
"The request was rejected because the HTTP method \"" + request.getMethod()
+ "\" was not included within the list of allowed HTTP methods " + this.allowedHttpMethods);
}
}
private void rejectedBlocklistedUrls(HttpServletRequest request) {
for (String forbidden : this.encodedUrlBlocklist) {
if (encodedUrlContains(request, forbidden)) {
throw new RequestRejectedException(
"The request was rejected because the URL contained a potentially malicious String \""
+ forbidden + "\"");
}
}
for (String forbidden : this.decodedUrlBlocklist) {
if (decodedUrlContains(request, forbidden)) {
throw new RequestRejectedException(
"The request was rejected because the URL contained a potentially malicious String \""
+ forbidden + "\"");
}
}
}
private void rejectedUntrustedHosts(HttpServletRequest request) {
String serverName = request.getServerName();
if (serverName != null && !this.allowedHostnames.test(serverName)) {
throw new RequestRejectedException(
"The request was rejected because the domain " + serverName + " is untrusted.");
}
}
@Override
public HttpServletResponse getFirewalledResponse(HttpServletResponse response) {
return new FirewalledResponse(response);
}
private static Set<String> createDefaultAllowedHttpMethods() {
Set<String> result = new HashSet<>();
result.add(HttpMethod.DELETE.name());
result.add(HttpMethod.GET.name());
result.add(HttpMethod.HEAD.name());
result.add(HttpMethod.OPTIONS.name());
result.add(HttpMethod.PATCH.name());
result.add(HttpMethod.POST.name());
result.add(HttpMethod.PUT.name());
return result;
}
private static boolean isNormalized(HttpServletRequest request) {
if (!isNormalized(request.getRequestURI())) {
return false;
}
if (!isNormalized(request.getContextPath())) {
return false;
}
if (!isNormalized(request.getServletPath())) {
return false;
}
if (!isNormalized(request.getPathInfo())) {
return false;
}
return true;
}
private static boolean encodedUrlContains(HttpServletRequest request, String value) {
if (valueContains(request.getContextPath(), value)) {
return true;
}
return valueContains(request.getRequestURI(), value);
}
private static boolean decodedUrlContains(HttpServletRequest request, String value) {
if (valueContains(request.getServletPath(), value)) {
return true;
}
if (valueContains(request.getPathInfo(), value)) {
return true;
}
return false;
}
private static boolean containsOnlyPrintableAsciiCharacters(String uri) {
if (uri == null) {
return true;
}
int length = uri.length();
for (int i = 0; i < length; i++) {
char ch = uri.charAt(i);
if (ch < '\u0020' || ch > '\u007e') {
return false;
}
}
return true;
}
private static boolean valueContains(String value, String contains) {
return value != null && value.contains(contains);
}
/**
* Checks whether a path is normalized (doesn't contain path traversal sequences like
* "./", "/../" or "/.")
* @param path the path to test
* @return true if the path doesn't contain any path-traversal character sequences.
*/
private static boolean isNormalized(String path) {
if (path == null) {
return true;
}
for (int i = path.length(); i > 0;) {
int slashIndex = path.lastIndexOf('/', i - 1);
int gap = i - slashIndex;
if (gap == 2 && path.charAt(slashIndex + 1) == '.') {
return false; // ".", "/./" or "/."
}
if (gap == 3 && path.charAt(slashIndex + 1) == '.' && path.charAt(slashIndex + 2) == '.') {
return false;
}
i = slashIndex;
}
return true;
}
/**
* Provides the existing encoded url blocklist which can add/remove entries from
* @return the existing encoded url blocklist, never null
*/
public Set<String> getEncodedUrlBlocklist() {
return this.encodedUrlBlocklist;
}
/**
* Provides the existing decoded url blocklist which can add/remove entries from
* @return the existing decoded url blocklist, never null
*/
public Set<String> getDecodedUrlBlocklist() {
return this.decodedUrlBlocklist;
}
/**
* Provides the existing encoded url blocklist which can add/remove entries from
* @return the existing encoded url blocklist, never null
* @deprecated Use {@link #getEncodedUrlBlocklist()} instead
*/
@Deprecated
public Set<String> getEncodedUrlBlacklist() {
return getEncodedUrlBlocklist();
}
/**
* Provides the existing decoded url blocklist which can add/remove entries from
* @return the existing decoded url blocklist, never null
*
*/
public Set<String> getDecodedUrlBlacklist() {
return getDecodedUrlBlocklist();
}
/**
* Strict {@link FirewalledRequest}.
*/
private class StrictFirewalledRequest extends FirewalledRequest {
StrictFirewalledRequest(HttpServletRequest request) {
super(request);
}
@Override
public long getDateHeader(String name) {
if (name != null) {
validateAllowedHeaderName(name);
}
return super.getDateHeader(name);
}
@Override
public int getIntHeader(String name) {
if (name != null) {
validateAllowedHeaderName(name);
}
return super.getIntHeader(name);
}
@Override
public String getHeader(String name) {
if (name != null) {
validateAllowedHeaderName(name);
}
String value = super.getHeader(name);
if (value != null) {
validateAllowedHeaderValue(value);
}
return value;
}
@Override
public Enumeration<String> getHeaders(String name) {
if (name != null) {
validateAllowedHeaderName(name);
}
Enumeration<String> headers = super.getHeaders(name);
return new Enumeration<String>() {
@Override
public boolean hasMoreElements() {
return headers.hasMoreElements();
}
@Override
public String nextElement() {
String value = headers.nextElement();
validateAllowedHeaderValue(value);
return value;
}
};
}
@Override
public Enumeration<String> getHeaderNames() {
Enumeration<String> names = super.getHeaderNames();
return new Enumeration<String>() {
@Override
public boolean hasMoreElements() {
return names.hasMoreElements();
}
@Override
public String nextElement() {
String headerNames = names.nextElement();
validateAllowedHeaderName(headerNames);
return headerNames;
}
};
}
@Override
public String getParameter(String name) {
if (name != null) {
validateAllowedParameterName(name);
}
String value = super.getParameter(name);
if (value != null) {
validateAllowedParameterValue(value);
}
return value;
}
@Override
public Map<String, String[]> getParameterMap() {
Map<String, String[]> parameterMap = super.getParameterMap();
for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
String name = entry.getKey();
String[] values = entry.getValue();
validateAllowedParameterName(name);
for (String value : values) {
validateAllowedParameterValue(value);
}
}
return parameterMap;
}
@Override
public Enumeration<String> getParameterNames() {
Enumeration<String> paramaterNames = super.getParameterNames();
return new Enumeration<String>() {
@Override
public boolean hasMoreElements() {
return paramaterNames.hasMoreElements();
}
@Override
public String nextElement() {
String name = paramaterNames.nextElement();
validateAllowedParameterName(name);
return name;
}
};
}
@Override
public String[] getParameterValues(String name) {
if (name != null) {
validateAllowedParameterName(name);
}
String[] values = super.getParameterValues(name);
if (values != null) {
for (String value : values) {
validateAllowedParameterValue(value);
}
}
return values;
}
private void validateAllowedHeaderName(String headerNames) {
if (!StrictHttpFirewall.this.allowedHeaderNames.test(headerNames)) {
throw new RequestRejectedException(
"The request was rejected because the header name \"" + headerNames + "\" is not allowed.");
}
}
private void validateAllowedHeaderValue(String value) {
if (!StrictHttpFirewall.this.allowedHeaderValues.test(value)) {
throw new RequestRejectedException(
"The request was rejected because the header value \"" + value + "\" is not allowed.");
}
}
private void validateAllowedParameterName(String name) {
if (!StrictHttpFirewall.this.allowedParameterNames.test(name)) {
throw new RequestRejectedException(
"The request was rejected because the parameter name \"" + name + "\" is not allowed.");
}
}
private void validateAllowedParameterValue(String value) {
if (!StrictHttpFirewall.this.allowedParameterValues.test(value)) {
throw new RequestRejectedException(
"The request was rejected because the parameter value \"" + value + "\" is not allowed.");
}
}
@Override
public void reset() {
}
};
}
| 29,277 | 33.083818 | 116 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/firewall/DefaultRequestRejectedHandler.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.firewall;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Default implementation of {@link RequestRejectedHandler} that simply rethrows the
* exception.
*
* @author Leonard Brünings
* @since 5.4
*/
public class DefaultRequestRejectedHandler implements RequestRejectedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
RequestRejectedException requestRejectedException) throws IOException, ServletException {
throw requestRejectedException;
}
}
| 1,297 | 30.658537 | 92 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/firewall/HttpStatusRequestRejectedHandler.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.firewall;
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.core.log.LogMessage;
/**
* A simple implementation of {@link RequestRejectedHandler} that sends an error with
* configurable status code.
*
* @author Leonard Brünings
* @since 5.4
*/
public class HttpStatusRequestRejectedHandler implements RequestRejectedHandler {
private static final Log logger = LogFactory.getLog(HttpStatusRequestRejectedHandler.class);
private final int httpError;
/**
* Constructs an instance which uses {@code 400} as response code.
*/
public HttpStatusRequestRejectedHandler() {
this.httpError = HttpServletResponse.SC_BAD_REQUEST;
}
/**
* Constructs an instance which uses a configurable http code as response.
* @param httpError http status code to use
*/
public HttpStatusRequestRejectedHandler(int httpError) {
this.httpError = httpError;
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
RequestRejectedException requestRejectedException) throws IOException {
logger.debug(LogMessage.format("Rejecting request due to: %s", requestRejectedException.getMessage()),
requestRejectedException);
response.sendError(this.httpError);
}
}
| 2,062 | 30.738462 | 104 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/firewall/FirewalledRequest.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.firewall;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
/**
* Request wrapper which is returned by the {@code HttpFirewall} interface.
* <p>
* The only difference is the {@code reset} method which allows some or all of the state
* to be reset by the {@code FilterChainProxy} when the request leaves the security filter
* chain.
*
* @author Luke Taylor
*/
public abstract class FirewalledRequest extends HttpServletRequestWrapper {
/**
* Constructs a request object wrapping the given request.
* @throws IllegalArgumentException if the request is null
*/
public FirewalledRequest(HttpServletRequest request) {
super(request);
}
/**
* This method will be called once the request has passed through the security filter
* chain, when it is about to proceed to the application proper.
* <p>
* An implementation can thus choose to modify the state of the request for the
* security infrastructure, while still maintaining the original
* {@link HttpServletRequest}.
*/
public abstract void reset();
@Override
public String toString() {
return "FirewalledRequest[ " + getRequest() + "]";
}
}
| 1,851 | 31.491228 | 90 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/firewall/DefaultHttpFirewall.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.firewall;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* <p>
* User's should consider using {@link StrictHttpFirewall} because rather than trying to
* sanitize a malicious URL it rejects the malicious URL providing better security
* guarantees.
* <p>
* Default implementation which wraps requests in order to provide consistent values of
* the {@code servletPath} and {@code pathInfo}, which do not contain path parameters (as
* defined in <a href="https://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>). Different
* servlet containers interpret the servlet spec differently as to how path parameters are
* treated and it is possible they might be added in order to bypass particular security
* constraints. When using this implementation, they will be removed for all requests as
* the request passes through the security filter chain. Note that this means that any
* segments in the decoded path which contain a semi-colon, will have the part following
* the semi-colon removed for request matching. Your application should not contain any
* valid paths which contain semi-colons.
* <p>
* If any un-normalized paths are found (containing directory-traversal character
* sequences), the request will be rejected immediately. Most containers normalize the
* paths before performing the servlet-mapping, but again this is not guaranteed by the
* servlet spec.
*
* @author Luke Taylor
* @see StrictHttpFirewall
*/
public class DefaultHttpFirewall implements HttpFirewall {
private boolean allowUrlEncodedSlash;
@Override
public FirewalledRequest getFirewalledRequest(HttpServletRequest request) throws RequestRejectedException {
FirewalledRequest firewalledRequest = new RequestWrapper(request);
if (!isNormalized(firewalledRequest.getServletPath()) || !isNormalized(firewalledRequest.getPathInfo())) {
throw new RequestRejectedException(
"Un-normalized paths are not supported: " + firewalledRequest.getServletPath()
+ ((firewalledRequest.getPathInfo() != null) ? firewalledRequest.getPathInfo() : ""));
}
String requestURI = firewalledRequest.getRequestURI();
if (containsInvalidUrlEncodedSlash(requestURI)) {
throw new RequestRejectedException("The requestURI cannot contain encoded slash. Got " + requestURI);
}
return firewalledRequest;
}
@Override
public HttpServletResponse getFirewalledResponse(HttpServletResponse response) {
return new FirewalledResponse(response);
}
/**
* <p>
* Sets if the application should allow a URL encoded slash character.
* </p>
* <p>
* If true (default is false), a URL encoded slash will be allowed in the URL.
* Allowing encoded slashes can cause security vulnerabilities in some situations
* depending on how the container constructs the HttpServletRequest.
* </p>
* @param allowUrlEncodedSlash the new value (default false)
*/
public void setAllowUrlEncodedSlash(boolean allowUrlEncodedSlash) {
this.allowUrlEncodedSlash = allowUrlEncodedSlash;
}
private boolean containsInvalidUrlEncodedSlash(String uri) {
if (this.allowUrlEncodedSlash || uri == null) {
return false;
}
if (uri.contains("%2f") || uri.contains("%2F")) {
return true;
}
return false;
}
/**
* Checks whether a path is normalized (doesn't contain path traversal sequences like
* "./", "/../" or "/.")
* @param path the path to test
* @return true if the path doesn't contain any path-traversal character sequences.
*/
private boolean isNormalized(String path) {
if (path == null) {
return true;
}
for (int i = path.length(); i > 0;) {
int slashIndex = path.lastIndexOf('/', i - 1);
int gap = i - slashIndex;
if (gap == 2 && path.charAt(slashIndex + 1) == '.') {
// ".", "/./" or "/."
return false;
}
if (gap == 3 && path.charAt(slashIndex + 1) == '.' && path.charAt(slashIndex + 2) == '.') {
return false;
}
i = slashIndex;
}
return true;
}
}
| 4,640 | 37.040984 | 108 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/firewall/RequestRejectedException.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.firewall;
/**
* @author Luke Taylor
*/
public class RequestRejectedException extends RuntimeException {
public RequestRejectedException(String message) {
super(message);
}
}
| 847 | 28.241379 | 75 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/firewall/RequestWrapper.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.firewall;
import java.io.IOException;
import java.util.StringTokenizer;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
/**
* Request wrapper which ensures values of {@code servletPath} and {@code pathInfo} are
* returned which are suitable for pattern matching against. It strips out path parameters
* and extra consecutive '/' characters.
*
* <h3>Path Parameters</h3> Parameters (as defined in
* <a href="https://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>) are stripped from the path
* segments of the {@code servletPath} and {@code pathInfo} values of the request.
* <p>
* The parameter sequence is demarcated by a semi-colon, so each segment is checked for
* the occurrence of a ";" character and truncated at that point if it is present.
* <p>
* The behaviour differs between servlet containers in how they interpret the servlet
* spec, which does not clearly state what the behaviour should be. For consistency, we
* make sure they are always removed, to avoid the risk of URL matching rules being
* bypassed by the malicious addition of parameters to the path component.
*
* @author Luke Taylor
*/
final class RequestWrapper extends FirewalledRequest {
private final String strippedServletPath;
private final String strippedPathInfo;
private boolean stripPaths = true;
RequestWrapper(HttpServletRequest request) {
super(request);
this.strippedServletPath = strip(request.getServletPath());
String pathInfo = strip(request.getPathInfo());
if (pathInfo != null && pathInfo.length() == 0) {
pathInfo = null;
}
this.strippedPathInfo = pathInfo;
}
/**
* Removes path parameters from each path segment in the supplied path and truncates
* sequences of multiple '/' characters to a single '/'.
* @param path either the {@code servletPath} and {@code pathInfo} from the original
* request
* @return the supplied value, with path parameters removed and sequences of multiple
* '/' characters truncated, or null if the supplied path was null.
*/
private String strip(String path) {
if (path == null) {
return null;
}
int semicolonIndex = path.indexOf(';');
if (semicolonIndex < 0) {
int doubleSlashIndex = path.indexOf("//");
if (doubleSlashIndex < 0) {
// Most likely case, no parameters in any segment and no '//', so no
// stripping required
return path;
}
}
StringTokenizer tokenizer = new StringTokenizer(path, "/");
StringBuilder stripped = new StringBuilder(path.length());
if (path.charAt(0) == '/') {
stripped.append('/');
}
while (tokenizer.hasMoreTokens()) {
String segment = tokenizer.nextToken();
semicolonIndex = segment.indexOf(';');
if (semicolonIndex >= 0) {
segment = segment.substring(0, semicolonIndex);
}
stripped.append(segment).append('/');
}
// Remove the trailing slash if the original path didn't have one
if (path.charAt(path.length() - 1) != '/') {
stripped.deleteCharAt(stripped.length() - 1);
}
return stripped.toString();
}
@Override
public String getPathInfo() {
return this.stripPaths ? this.strippedPathInfo : super.getPathInfo();
}
@Override
public String getServletPath() {
return this.stripPaths ? this.strippedServletPath : super.getServletPath();
}
@Override
public RequestDispatcher getRequestDispatcher(String path) {
return this.stripPaths ? new FirewalledRequestAwareRequestDispatcher(path) : super.getRequestDispatcher(path);
}
@Override
public void reset() {
this.stripPaths = false;
}
/**
* Ensures {@link FirewalledRequest#reset()} is called prior to performing a forward.
* It then delegates work to the {@link RequestDispatcher} from the original
* {@link HttpServletRequest}.
*
* @author Rob Winch
*/
private class FirewalledRequestAwareRequestDispatcher implements RequestDispatcher {
private final String path;
/**
* @param path the {@code path} that will be used to obtain the delegate
* {@link RequestDispatcher} from the original {@link HttpServletRequest}.
*/
FirewalledRequestAwareRequestDispatcher(String path) {
this.path = path;
}
@Override
public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException {
reset();
getDelegateDispatcher().forward(request, response);
}
@Override
public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException {
getDelegateDispatcher().include(request, response);
}
private RequestDispatcher getDelegateDispatcher() {
return RequestWrapper.super.getRequestDispatcher(this.path);
}
}
}
| 5,425 | 32.288344 | 112 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/firewall/HttpFirewall.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.firewall;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Interface which can be used to reject potentially dangerous requests and/or wrap them
* to control their behaviour.
* <p>
* The implementation is injected into the {@code FilterChainProxy} and will be invoked
* before sending any request through the filter chain. It can also provide a response
* wrapper if the response behaviour should also be restricted.
*
* @author Luke Taylor
*/
public interface HttpFirewall {
/**
* Provides the request object which will be passed through the filter chain.
* @throws RequestRejectedException if the request should be rejected immediately
*/
FirewalledRequest getFirewalledRequest(HttpServletRequest request) throws RequestRejectedException;
/**
* Provides the response which will be passed through the filter chain.
* @param response the original response
* @return either the original response or a replacement/wrapper.
*/
HttpServletResponse getFirewalledResponse(HttpServletResponse response);
}
| 1,749 | 35.458333 | 100 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/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.
*/
/**
* Web utility classes.
* <p>
* Should not depend on any other framework classes.
*/
package org.springframework.security.web.util;
| 762 | 32.173913 | 75 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/UrlUtils.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.util;
import java.util.regex.Pattern;
import jakarta.servlet.http.HttpServletRequest;
/**
* Provides static methods for composing URLs.
* <p>
* Placed into a separate class for visibility, so that changes to URL formatting
* conventions will affect all users.
*
* @author Ben Alex
*/
public final class UrlUtils {
private static final Pattern ABSOLUTE_URL = Pattern.compile("\\A[a-z0-9.+-]+://.*", Pattern.CASE_INSENSITIVE);
private UrlUtils() {
}
public static String buildFullRequestUrl(HttpServletRequest r) {
return buildFullRequestUrl(r.getScheme(), r.getServerName(), r.getServerPort(), r.getRequestURI(),
r.getQueryString());
}
/**
* Obtains the full URL the client used to make the request.
* <p>
* Note that the server port will not be shown if it is the default server port for
* HTTP or HTTPS (80 and 443 respectively).
* @return the full URL, suitable for redirects (not decoded).
*/
public static String buildFullRequestUrl(String scheme, String serverName, int serverPort, String requestURI,
String queryString) {
scheme = scheme.toLowerCase();
StringBuilder url = new StringBuilder();
url.append(scheme).append("://").append(serverName);
// Only add port if not default
if ("http".equals(scheme)) {
if (serverPort != 80) {
url.append(":").append(serverPort);
}
}
else if ("https".equals(scheme)) {
if (serverPort != 443) {
url.append(":").append(serverPort);
}
}
// Use the requestURI as it is encoded (RFC 3986) and hence suitable for
// redirects.
url.append(requestURI);
if (queryString != null) {
url.append("?").append(queryString);
}
return url.toString();
}
/**
* Obtains the web application-specific fragment of the request URL.
* <p>
* Under normal spec conditions,
*
* <pre>
* requestURI = contextPath + servletPath + pathInfo
* </pre>
*
* But the requestURI is not decoded, whereas the servletPath and pathInfo are
* (SEC-1255). This method is typically used to return a URL for matching against
* secured paths, hence the decoded form is used in preference to the requestURI for
* building the returned value. But this method may also be called using dummy request
* objects which just have the requestURI and contextPatth set, for example, so it
* will fall back to using those.
* @return the decoded URL, excluding any server name, context path or servlet path
*
*/
public static String buildRequestUrl(HttpServletRequest r) {
return buildRequestUrl(r.getServletPath(), r.getRequestURI(), r.getContextPath(), r.getPathInfo(),
r.getQueryString());
}
/**
* Obtains the web application-specific fragment of the URL.
*/
private static String buildRequestUrl(String servletPath, String requestURI, String contextPath, String pathInfo,
String queryString) {
StringBuilder url = new StringBuilder();
if (servletPath != null) {
url.append(servletPath);
if (pathInfo != null) {
url.append(pathInfo);
}
}
else {
url.append(requestURI.substring(contextPath.length()));
}
if (queryString != null) {
url.append("?").append(queryString);
}
return url.toString();
}
/**
* Returns true if the supplied URL starts with a "/" or is absolute.
*/
public static boolean isValidRedirectUrl(String url) {
return url != null && (url.startsWith("/") || isAbsoluteUrl(url));
}
/**
* Decides if a URL is absolute based on whether it contains a valid scheme name, as
* defined in RFC 1738.
*/
public static boolean isAbsoluteUrl(String url) {
return (url != null) ? ABSOLUTE_URL.matcher(url).matches() : false;
}
}
| 4,291 | 30.792593 | 114 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/TextEscapeUtils.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.util;
/**
* Internal utility for escaping characters in HTML strings.
*
* @author Luke Taylor
*
*/
public abstract class TextEscapeUtils {
public static String escapeEntities(String s) {
if (s == null || s.length() == 0) {
return s;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9') {
sb.append(ch);
}
else if (ch == '<') {
sb.append("<");
}
else if (ch == '>') {
sb.append(">");
}
else if (ch == '&') {
sb.append("&");
}
else if (Character.isWhitespace(ch)) {
sb.append("&#").append((int) ch).append(";");
}
else if (Character.isISOControl(ch)) {
// ignore control chars
}
else if (Character.isHighSurrogate(ch)) {
if (i + 1 >= s.length()) {
// Unexpected end
throw new IllegalArgumentException("Missing low surrogate character at end of string");
}
char low = s.charAt(i + 1);
if (!Character.isLowSurrogate(low)) {
throw new IllegalArgumentException(
"Expected low surrogate character but found value = " + (int) low);
}
int codePoint = Character.toCodePoint(ch, low);
if (Character.isDefined(codePoint)) {
sb.append("&#").append(codePoint).append(";");
}
i++; // skip the next character as we have already dealt with it
}
else if (Character.isLowSurrogate(ch)) {
throw new IllegalArgumentException("Unexpected low surrogate character, value = " + (int) ch);
}
else if (Character.isDefined(ch)) {
sb.append("&#").append((int) ch).append(";");
}
// Ignore anything else
}
return sb.toString();
}
}
| 2,387 | 28.85 | 98 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/RedirectUrlBuilder.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.util;
import org.springframework.util.Assert;
/**
* Internal class for building redirect URLs.
*
* Could probably make more use of the classes in java.net for this.
*
* @author Luke Taylor
* @since 2.0
*/
public class RedirectUrlBuilder {
private String scheme;
private String serverName;
private int port;
private String contextPath;
private String servletPath;
private String pathInfo;
private String query;
public void setScheme(String scheme) {
Assert.isTrue("http".equals(scheme) || "https".equals(scheme), () -> "Unsupported scheme '" + scheme + "'");
this.scheme = scheme;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
public void setPort(int port) {
this.port = port;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
public void setServletPath(String servletPath) {
this.servletPath = servletPath;
}
public void setPathInfo(String pathInfo) {
this.pathInfo = pathInfo;
}
public void setQuery(String query) {
this.query = query;
}
public String getUrl() {
StringBuilder sb = new StringBuilder();
Assert.notNull(this.scheme, "scheme cannot be null");
Assert.notNull(this.serverName, "serverName cannot be null");
sb.append(this.scheme).append("://").append(this.serverName);
// Append the port number if it's not standard for the scheme
if (this.port != (this.scheme.equals("http") ? 80 : 443)) {
sb.append(":").append(this.port);
}
if (this.contextPath != null) {
sb.append(this.contextPath);
}
if (this.servletPath != null) {
sb.append(this.servletPath);
}
if (this.pathInfo != null) {
sb.append(this.pathInfo);
}
if (this.query != null) {
sb.append("?").append(this.query);
}
return sb.toString();
}
}
| 2,457 | 23.828283 | 110 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/ThrowableCauseExtractor.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.util;
/**
* Interface for handlers extracting the cause out of a specific {@link Throwable} type.
*
* @author Andreas Senft
* @since 2.0
* @see ThrowableAnalyzer
*/
public interface ThrowableCauseExtractor {
/**
* Extracts the cause from the provided <code>Throwable</code>.
* @param throwable the <code>Throwable</code>
* @return the extracted cause (maybe <code>null</code>)
* @throws IllegalArgumentException if <code>throwable</code> is <code>null</code> or
* otherwise considered invalid for the implementation
*/
Throwable extractCause(Throwable throwable);
}
| 1,253 | 32 | 88 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/ThrowableAnalyzer.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.util;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.springframework.util.Assert;
/**
* Handler for analyzing {@link Throwable} instances.
*
* Can be subclassed to customize its behavior.
*
* @author Andreas Senft
* @since 2.0
*/
public class ThrowableAnalyzer {
/**
* Default extractor for {@link Throwable} instances.
*
* @see Throwable#getCause()
*/
public static final ThrowableCauseExtractor DEFAULT_EXTRACTOR = Throwable::getCause;
/**
* Default extractor for {@link InvocationTargetException} instances.
*
* @see InvocationTargetException#getTargetException()
*/
public static final ThrowableCauseExtractor INVOCATIONTARGET_EXTRACTOR = (throwable) -> {
verifyThrowableHierarchy(throwable, InvocationTargetException.class);
return ((InvocationTargetException) throwable).getTargetException();
};
/**
* Comparator to order classes ascending according to their hierarchy relation. If two
* classes have a hierarchical relation, the "higher" class is considered to be
* greater by this comparator.<br>
* For hierarchically unrelated classes their fully qualified name will be compared.
*/
private static final Comparator<Class<? extends Throwable>> CLASS_HIERARCHY_COMPARATOR = (class1, class2) -> {
if (class1.isAssignableFrom(class2)) {
return 1;
}
if (class2.isAssignableFrom(class1)) {
return -1;
}
return class1.getName().compareTo(class2.getName());
};
/**
* Map of registered cause extractors. key: Class<Throwable>; value:
* ThrowableCauseExctractor
*/
private final Map<Class<? extends Throwable>, ThrowableCauseExtractor> extractorMap;
/**
* Creates a new <code>ThrowableAnalyzer</code> instance.
*/
public ThrowableAnalyzer() {
this.extractorMap = new TreeMap<>(CLASS_HIERARCHY_COMPARATOR);
initExtractorMap();
}
/**
* Registers a <code>ThrowableCauseExtractor</code> for the specified type. <i>Can be
* used in subclasses overriding {@link #initExtractorMap()}.</i>
* @param throwableType the type (has to be a subclass of <code>Throwable</code>)
* @param extractor the associated <code>ThrowableCauseExtractor</code> (not
* <code>null</code>)
* @throws IllegalArgumentException if one of the arguments is invalid
*/
protected final void registerExtractor(Class<? extends Throwable> throwableType,
ThrowableCauseExtractor extractor) {
Assert.notNull(extractor, "Invalid extractor: null");
this.extractorMap.put(throwableType, extractor);
}
/**
* Initializes associations between <code>Throwable</code>s and
* <code>ThrowableCauseExtractor</code>s. The default implementation performs the
* following registrations:
* <ul>
* <li>{@link #DEFAULT_EXTRACTOR} for {@link Throwable}</li>
* <li>{@link #INVOCATIONTARGET_EXTRACTOR} for {@link InvocationTargetException}</li>
* </ul>
* <br>
* Subclasses overriding this method are encouraged to invoke the super method to
* perform the default registrations. They can register additional extractors as
* required.
* <p>
* Note: An extractor registered for a specific type is applicable for that type
* <i>and all subtypes thereof</i>. However, extractors registered to more specific
* types are guaranteed to be resolved first. So in the default case
* InvocationTargetExceptions will be handled by {@link #INVOCATIONTARGET_EXTRACTOR}
* while all other throwables are handled by {@link #DEFAULT_EXTRACTOR}.
*
* @see #registerExtractor(Class, ThrowableCauseExtractor)
*/
protected void initExtractorMap() {
registerExtractor(InvocationTargetException.class, INVOCATIONTARGET_EXTRACTOR);
registerExtractor(Throwable.class, DEFAULT_EXTRACTOR);
}
/**
* Returns an array containing the classes for which extractors are registered. The
* order of the classes is the order in which comparisons will occur for resolving a
* matching extractor.
* @return the types for which extractors are registered
*/
@SuppressWarnings("unchecked")
final Class<? extends Throwable>[] getRegisteredTypes() {
Set<Class<? extends Throwable>> typeList = this.extractorMap.keySet();
return typeList.toArray(new Class[0]);
}
/**
* Determines the cause chain of the provided <code>Throwable</code>. The returned
* array contains all throwables extracted from the stacktrace, using the registered
* {@link ThrowableCauseExtractor extractors}. The elements of the array are ordered:
* The first element is the passed in throwable itself. The following elements appear
* in their order downward the stacktrace.
* <p>
* Note: If no {@link ThrowableCauseExtractor} is registered for this instance then
* the returned array will always only contain the passed in throwable.
* @param throwable the <code>Throwable</code> to analyze
* @return an array of all determined throwables from the stacktrace
* @throws IllegalArgumentException if the throwable is <code>null</code>
*
* @see #initExtractorMap()
*/
public final Throwable[] determineCauseChain(Throwable throwable) {
Assert.notNull(throwable, "Invalid throwable: null");
List<Throwable> chain = new ArrayList<>();
Throwable currentThrowable = throwable;
while (currentThrowable != null) {
chain.add(currentThrowable);
currentThrowable = extractCause(currentThrowable);
}
return chain.toArray(new Throwable[0]);
}
/**
* Extracts the cause of the given throwable using an appropriate extractor.
* @param throwable the <code>Throwable</code> (not <code>null</code>
* @return the cause, may be <code>null</code> if none could be resolved
*/
private Throwable extractCause(Throwable throwable) {
for (Map.Entry<Class<? extends Throwable>, ThrowableCauseExtractor> entry : this.extractorMap.entrySet()) {
Class<? extends Throwable> throwableType = entry.getKey();
if (throwableType.isInstance(throwable)) {
ThrowableCauseExtractor extractor = entry.getValue();
return extractor.extractCause(throwable);
}
}
return null;
}
/**
* Returns the first throwable from the passed in array that is assignable to the
* provided type. A returned instance is safe to be cast to the specified type.
* <p>
* If the passed in array is null or empty this method returns <code>null</code>.
* @param throwableType the type to look for
* @param chain the array (will be processed in element order)
* @return the found <code>Throwable</code>, <code>null</code> if not found
* @throws IllegalArgumentException if the provided type is <code>null</code> or no
* subclass of <code>Throwable</code>
*/
public final Throwable getFirstThrowableOfType(Class<? extends Throwable> throwableType, Throwable[] chain) {
if (chain != null) {
for (Throwable t : chain) {
if ((t != null) && throwableType.isInstance(t)) {
return t;
}
}
}
return null;
}
/**
* Verifies that the provided throwable is a valid subclass of the provided type (or
* of the type itself). If <code>expectdBaseType</code> is <code>null</code>, no check
* will be performed.
* <p>
* Can be used for verification purposes in implementations of
* {@link ThrowableCauseExtractor extractors}.
* @param throwable the <code>Throwable</code> to check
* @param expectedBaseType the type to check against
* @throws IllegalArgumentException if <code>throwable</code> is either
* <code>null</code> or its type is not assignable to <code>expectedBaseType</code>
*/
public static void verifyThrowableHierarchy(Throwable throwable, Class<? extends Throwable> expectedBaseType) {
if (expectedBaseType == null) {
return;
}
Assert.notNull(throwable, "Invalid throwable: null");
Class<? extends Throwable> throwableType = throwable.getClass();
Assert.isTrue(expectedBaseType.isAssignableFrom(throwableType), () -> "Invalid type: '"
+ throwableType.getName() + "'. Has to be a subclass of '" + expectedBaseType.getName() + "'");
}
}
| 8,714 | 37.733333 | 112 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/OnCommittedResponseWrapper.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.util;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.WriteListener;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;
/**
* Base class for response wrappers which encapsulate the logic for handling an event when
* the {@link jakarta.servlet.http.HttpServletResponse} is committed.
*
* @author Rob Winch
* @since 4.0.2
*/
public abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper {
private boolean disableOnCommitted;
/**
* The Content-Length response header. If this is greater than 0, then once
* {@link #contentWritten} is larger than or equal the response is considered
* committed.
*/
private long contentLength;
/**
* The size of data written to the response body. The field will only be updated when
* {@link #disableOnCommitted} is false.
*/
private long contentWritten;
/**
* @param response the response to be wrapped
*/
public OnCommittedResponseWrapper(HttpServletResponse response) {
super(response);
}
@Override
public void addHeader(String name, String value) {
if ("Content-Length".equalsIgnoreCase(name)) {
setContentLength(Long.parseLong(value));
}
super.addHeader(name, value);
}
@Override
public void setContentLength(int len) {
setContentLength((long) len);
super.setContentLength(len);
}
@Override
public void setContentLengthLong(long len) {
setContentLength(len);
super.setContentLengthLong(len);
}
private void setContentLength(long len) {
this.contentLength = len;
checkContentLength(0);
}
/**
* Invoke this method to disable invoking
* {@link OnCommittedResponseWrapper#onResponseCommitted()} when the
* {@link jakarta.servlet.http.HttpServletResponse} is committed. This can be useful
* in the event that Async Web Requests are made.
*/
protected void disableOnResponseCommitted() {
this.disableOnCommitted = true;
}
/**
* Returns true if {@link #onResponseCommitted()} will be invoked when the response is
* committed, else false.
* @return if {@link #onResponseCommitted()} is enabled
*/
protected boolean isDisableOnResponseCommitted() {
return this.disableOnCommitted;
}
/**
* Implement the logic for handling the
* {@link jakarta.servlet.http.HttpServletResponse} being committed
*/
protected abstract void onResponseCommitted();
/**
* Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked
* before calling the superclass <code>sendError()</code>
*/
@Override
public final void sendError(int sc) throws IOException {
doOnResponseCommitted();
super.sendError(sc);
}
/**
* Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked
* before calling the superclass <code>sendError()</code>
*/
@Override
public final void sendError(int sc, String msg) throws IOException {
doOnResponseCommitted();
super.sendError(sc, msg);
}
/**
* Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked
* before calling the superclass <code>sendRedirect()</code>
*/
@Override
public final void sendRedirect(String location) throws IOException {
doOnResponseCommitted();
super.sendRedirect(location);
}
/**
* Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked
* before calling the calling <code>getOutputStream().close()</code> or
* <code>getOutputStream().flush()</code>
*/
@Override
public ServletOutputStream getOutputStream() throws IOException {
return new SaveContextServletOutputStream(super.getOutputStream());
}
/**
* Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked
* before calling the <code>getWriter().close()</code> or
* <code>getWriter().flush()</code>
*/
@Override
public PrintWriter getWriter() throws IOException {
return new SaveContextPrintWriter(super.getWriter());
}
/**
* Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked
* before calling the superclass <code>flushBuffer()</code>
*/
@Override
public void flushBuffer() throws IOException {
doOnResponseCommitted();
super.flushBuffer();
}
private void trackContentLength(boolean content) {
if (!this.disableOnCommitted) {
checkContentLength(content ? 4 : 5); // TODO Localization
}
}
private void trackContentLength(char content) {
if (!this.disableOnCommitted) {
checkContentLength(1);
}
}
private void trackContentLength(Object content) {
if (!this.disableOnCommitted) {
trackContentLength(String.valueOf(content));
}
}
private void trackContentLength(byte[] content) {
if (!this.disableOnCommitted) {
checkContentLength((content != null) ? content.length : 0);
}
}
private void trackContentLength(char[] content) {
if (!this.disableOnCommitted) {
checkContentLength((content != null) ? content.length : 0);
}
}
private void trackContentLength(int content) {
if (!this.disableOnCommitted) {
trackContentLength(String.valueOf(content));
}
}
private void trackContentLength(float content) {
if (!this.disableOnCommitted) {
trackContentLength(String.valueOf(content));
}
}
private void trackContentLength(double content) {
if (!this.disableOnCommitted) {
trackContentLength(String.valueOf(content));
}
}
private void trackContentLengthLn() {
if (!this.disableOnCommitted) {
trackContentLength("\r\n");
}
}
private void trackContentLength(String content) {
if (!this.disableOnCommitted) {
int contentLength = (content != null) ? content.length() : 4;
checkContentLength(contentLength);
}
}
/**
* Adds the contentLengthToWrite to the total contentWritten size and checks to see if
* the response should be written.
* @param contentLengthToWrite the size of the content that is about to be written.
*/
private void checkContentLength(long contentLengthToWrite) {
this.contentWritten += contentLengthToWrite;
boolean isBodyFullyWritten = this.contentLength > 0 && this.contentWritten >= this.contentLength;
int bufferSize = getBufferSize();
boolean requiresFlush = bufferSize > 0 && this.contentWritten >= bufferSize;
if (isBodyFullyWritten || requiresFlush) {
doOnResponseCommitted();
}
}
/**
* Calls <code>onResponseCommmitted()</code> with the current contents as long as
* {@link #disableOnResponseCommitted()} was not invoked.
*/
private void doOnResponseCommitted() {
if (!this.disableOnCommitted) {
onResponseCommitted();
disableOnResponseCommitted();
}
}
/**
* Ensures {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked before
* calling the prior to methods that commit the response. We delegate all methods to
* the original {@link java.io.PrintWriter} to ensure that the behavior is as close to
* the original {@link java.io.PrintWriter} as possible. See SEC-2039
*
* @author Rob Winch
*/
private class SaveContextPrintWriter extends PrintWriter {
private final PrintWriter delegate;
SaveContextPrintWriter(PrintWriter delegate) {
super(delegate);
this.delegate = delegate;
}
@Override
public void flush() {
doOnResponseCommitted();
this.delegate.flush();
}
@Override
public void close() {
doOnResponseCommitted();
this.delegate.close();
}
@Override
public boolean equals(Object obj) {
return this.delegate.equals(obj);
}
@Override
public int hashCode() {
return this.delegate.hashCode();
}
@Override
public String toString() {
return getClass().getName() + "[delegate=" + this.delegate.toString() + "]";
}
@Override
public boolean checkError() {
return this.delegate.checkError();
}
@Override
public void write(int c) {
trackContentLength(c);
this.delegate.write(c);
}
@Override
public void write(char[] buf, int off, int len) {
checkContentLength(len);
this.delegate.write(buf, off, len);
}
@Override
public void write(char[] buf) {
trackContentLength(buf);
this.delegate.write(buf);
}
@Override
public void write(String s, int off, int len) {
checkContentLength(len);
this.delegate.write(s, off, len);
}
@Override
public void write(String s) {
trackContentLength(s);
this.delegate.write(s);
}
@Override
public void print(boolean b) {
trackContentLength(b);
this.delegate.print(b);
}
@Override
public void print(char c) {
trackContentLength(c);
this.delegate.print(c);
}
@Override
public void print(int i) {
trackContentLength(i);
this.delegate.print(i);
}
@Override
public void print(long l) {
trackContentLength(l);
this.delegate.print(l);
}
@Override
public void print(float f) {
trackContentLength(f);
this.delegate.print(f);
}
@Override
public void print(double d) {
trackContentLength(d);
this.delegate.print(d);
}
@Override
public void print(char[] s) {
trackContentLength(s);
this.delegate.print(s);
}
@Override
public void print(String s) {
trackContentLength(s);
this.delegate.print(s);
}
@Override
public void print(Object obj) {
trackContentLength(obj);
this.delegate.print(obj);
}
@Override
public void println() {
trackContentLengthLn();
this.delegate.println();
}
@Override
public void println(boolean x) {
trackContentLength(x);
trackContentLengthLn();
this.delegate.println(x);
}
@Override
public void println(char x) {
trackContentLength(x);
trackContentLengthLn();
this.delegate.println(x);
}
@Override
public void println(int x) {
trackContentLength(x);
trackContentLengthLn();
this.delegate.println(x);
}
@Override
public void println(long x) {
trackContentLength(x);
trackContentLengthLn();
this.delegate.println(x);
}
@Override
public void println(float x) {
trackContentLength(x);
trackContentLengthLn();
this.delegate.println(x);
}
@Override
public void println(double x) {
trackContentLength(x);
trackContentLengthLn();
this.delegate.println(x);
}
@Override
public void println(char[] x) {
trackContentLength(x);
trackContentLengthLn();
this.delegate.println(x);
}
@Override
public void println(String x) {
trackContentLength(x);
trackContentLengthLn();
this.delegate.println(x);
}
@Override
public void println(Object x) {
trackContentLength(x);
trackContentLengthLn();
this.delegate.println(x);
}
@Override
public PrintWriter printf(String format, Object... args) {
return this.delegate.printf(format, args);
}
@Override
public PrintWriter printf(Locale l, String format, Object... args) {
return this.delegate.printf(l, format, args);
}
@Override
public PrintWriter format(String format, Object... args) {
return this.delegate.format(format, args);
}
@Override
public PrintWriter format(Locale l, String format, Object... args) {
return this.delegate.format(l, format, args);
}
@Override
public PrintWriter append(CharSequence csq) {
checkContentLength(csq.length());
return this.delegate.append(csq);
}
@Override
public PrintWriter append(CharSequence csq, int start, int end) {
checkContentLength(end - start);
return this.delegate.append(csq, start, end);
}
@Override
public PrintWriter append(char c) {
trackContentLength(c);
return this.delegate.append(c);
}
}
/**
* Ensures{@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked before
* calling methods that commit the response. We delegate all methods to the original
* {@link jakarta.servlet.ServletOutputStream} to ensure that the behavior is as close
* to the original {@link jakarta.servlet.ServletOutputStream} as possible. See
* SEC-2039
*
* @author Rob Winch
*/
private class SaveContextServletOutputStream extends ServletOutputStream {
private final ServletOutputStream delegate;
SaveContextServletOutputStream(ServletOutputStream delegate) {
this.delegate = delegate;
}
@Override
public void write(int b) throws IOException {
trackContentLength(b);
this.delegate.write(b);
}
@Override
public void flush() throws IOException {
doOnResponseCommitted();
this.delegate.flush();
}
@Override
public void close() throws IOException {
doOnResponseCommitted();
this.delegate.close();
}
@Override
public void print(boolean b) throws IOException {
trackContentLength(b);
this.delegate.print(b);
}
@Override
public void print(char c) throws IOException {
trackContentLength(c);
this.delegate.print(c);
}
@Override
public void print(double d) throws IOException {
trackContentLength(d);
this.delegate.print(d);
}
@Override
public void print(float f) throws IOException {
trackContentLength(f);
this.delegate.print(f);
}
@Override
public void print(int i) throws IOException {
trackContentLength(i);
this.delegate.print(i);
}
@Override
public void print(long l) throws IOException {
trackContentLength(l);
this.delegate.print(l);
}
@Override
public void print(String s) throws IOException {
trackContentLength(s);
this.delegate.print(s);
}
@Override
public void println() throws IOException {
trackContentLengthLn();
this.delegate.println();
}
@Override
public void println(boolean b) throws IOException {
trackContentLength(b);
trackContentLengthLn();
this.delegate.println(b);
}
@Override
public void println(char c) throws IOException {
trackContentLength(c);
trackContentLengthLn();
this.delegate.println(c);
}
@Override
public void println(double d) throws IOException {
trackContentLength(d);
trackContentLengthLn();
this.delegate.println(d);
}
@Override
public void println(float f) throws IOException {
trackContentLength(f);
trackContentLengthLn();
this.delegate.println(f);
}
@Override
public void println(int i) throws IOException {
trackContentLength(i);
trackContentLengthLn();
this.delegate.println(i);
}
@Override
public void println(long l) throws IOException {
trackContentLength(l);
trackContentLengthLn();
this.delegate.println(l);
}
@Override
public void println(String s) throws IOException {
trackContentLength(s);
trackContentLengthLn();
this.delegate.println(s);
}
@Override
public void write(byte[] b) throws IOException {
trackContentLength(b);
this.delegate.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
checkContentLength(len);
this.delegate.write(b, off, len);
}
@Override
public boolean isReady() {
return this.delegate.isReady();
}
@Override
public void setWriteListener(WriteListener writeListener) {
this.delegate.setWriteListener(writeListener);
}
@Override
public boolean equals(Object obj) {
return this.delegate.equals(obj);
}
@Override
public int hashCode() {
return this.delegate.hashCode();
}
@Override
public String toString() {
return getClass().getName() + "[delegate=" + this.delegate.toString() + "]";
}
}
}
| 15,937 | 22.78806 | 99 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/matcher/DispatcherTypeRequestMatcher.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.util.matcher;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpMethod;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
/**
* Checks the {@link DispatcherType} to decide whether to match a given request.
* {@code HttpServletRequest}.
*
* Can also be configured to match a specific HTTP method.
*
* @author Nick McKinney
* @since 5.5
*/
public class DispatcherTypeRequestMatcher implements RequestMatcher {
private final DispatcherType dispatcherType;
@Nullable
private final HttpMethod httpMethod;
/**
* Creates an instance which matches requests with the provided {@link DispatcherType}
* @param dispatcherType the type to match against
*/
public DispatcherTypeRequestMatcher(DispatcherType dispatcherType) {
this(dispatcherType, null);
}
/**
* Creates an instance which matches requests with the provided {@link DispatcherType}
* and {@link HttpMethod}
* @param dispatcherType the type to match against
* @param httpMethod the HTTP method to match. May be null to match all methods.
*/
public DispatcherTypeRequestMatcher(DispatcherType dispatcherType, @Nullable HttpMethod httpMethod) {
this.dispatcherType = dispatcherType;
this.httpMethod = httpMethod;
}
/**
* Performs the match against the request's method and dispatcher type.
* @param request the request to check for a match
* @return true if the http method and dispatcher type align
*/
@Override
public boolean matches(HttpServletRequest request) {
if (this.httpMethod != null && StringUtils.hasText(request.getMethod())
&& this.httpMethod != HttpMethod.valueOf(request.getMethod())) {
return false;
}
return this.dispatcherType == request.getDispatcherType();
}
@Override
public String toString() {
return "DispatcherTypeRequestMatcher{" + "dispatcherType=" + this.dispatcherType + ", httpMethod="
+ this.httpMethod + '}';
}
}
| 2,649 | 31.317073 | 102 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/matcher/RequestVariablesExtractor.java | /*
* Copyright 2012-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.util.matcher;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
/**
* An interface for extracting URI variables from the {@link HttpServletRequest}.
*
* @author Rob Winch
* @since 4.1.1
* @deprecated use {@link RequestMatcher.MatchResult} from
* {@link RequestMatcher#matcher(HttpServletRequest)}
*/
@Deprecated
public interface RequestVariablesExtractor {
/**
* Extract URL template variables from the request.
* @param request the HttpServletRequest to obtain a URL to extract the variables from
* @return the URL variables or empty if no variables are found
*/
Map<String, String> extractUriTemplateVariables(HttpServletRequest request);
}
| 1,349 | 31.142857 | 87 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/matcher/RequestMatchers.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.util.matcher;
import java.util.List;
/**
* A factory class to create {@link RequestMatcher} instances.
*
* @author Christian Schuster
* @since 6.1
*/
public final class RequestMatchers {
/**
* Creates a {@link RequestMatcher} that matches if at least one of the given
* {@link RequestMatcher}s matches, if <code>matchers</code> are empty then the
* returned matcher never matches.
* @param matchers the {@link RequestMatcher}s to use
* @return the any-of composed {@link RequestMatcher}
* @see OrRequestMatcher
*/
public static RequestMatcher anyOf(RequestMatcher... matchers) {
return (matchers.length > 0) ? new OrRequestMatcher(List.of(matchers)) : (request) -> false;
}
/**
* Creates a {@link RequestMatcher} that matches if all the given
* {@link RequestMatcher}s match, if <code>matchers</code> are empty then the returned
* matcher always matches.
* @param matchers the {@link RequestMatcher}s to use
* @return the all-of composed {@link RequestMatcher}
* @see AndRequestMatcher
*/
public static RequestMatcher allOf(RequestMatcher... matchers) {
return (matchers.length > 0) ? new AndRequestMatcher(List.of(matchers)) : (request) -> true;
}
/**
* Creates a {@link RequestMatcher} that matches if the given {@link RequestMatcher}
* does not match.
* @param matcher the {@link RequestMatcher} to use
* @return the inverted {@link RequestMatcher}
*/
public static RequestMatcher not(RequestMatcher matcher) {
return (request) -> !matcher.matches(request);
}
private RequestMatchers() {
}
}
| 2,226 | 32.238806 | 94 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/matcher/NegatedRequestMatcher.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.util.matcher;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
/**
* A {@link RequestMatcher} that will negate the {@link RequestMatcher} passed in. For
* example, if the {@link RequestMatcher} passed in returns true,
* {@link NegatedRequestMatcher} will return false. If the {@link RequestMatcher} passed
* in returns false, {@link NegatedRequestMatcher} will return true.
*
* @author Rob Winch
* @since 3.2
*/
public class NegatedRequestMatcher implements RequestMatcher {
private final Log logger = LogFactory.getLog(getClass());
private final RequestMatcher requestMatcher;
/**
* Creates a new instance
* @param requestMatcher the {@link RequestMatcher} that will be negated.
*/
public NegatedRequestMatcher(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "requestMatcher cannot be null");
this.requestMatcher = requestMatcher;
}
@Override
public boolean matches(HttpServletRequest request) {
return !this.requestMatcher.matches(request);
}
@Override
public String toString() {
return "Not [" + this.requestMatcher + "]";
}
}
| 1,876 | 30.283333 | 88 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/matcher/ELRequestMatcher.java | /*
* Copyright 2010-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.util.matcher;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint;
/**
* A RequestMatcher implementation which uses a SpEL expression
*
* <p>
* With the default EvaluationContext ({@link ELRequestMatcherContext}) you can use
* <code>hasIpAddress()</code> and <code>hasHeader()</code>
* </p>
*
* <p>
* See {@link DelegatingAuthenticationEntryPoint} for an example configuration.
* </p>
*
* @author Mike Wiesner
* @since 3.0.2
*/
public class ELRequestMatcher implements RequestMatcher {
private final Expression expression;
public ELRequestMatcher(String el) {
SpelExpressionParser parser = new SpelExpressionParser();
this.expression = parser.parseExpression(el);
}
@Override
public boolean matches(HttpServletRequest request) {
EvaluationContext context = createELContext(request);
return this.expression.getValue(context, Boolean.class);
}
/**
* Subclasses can override this methode if they want to use a different EL root
* context
* @return EL root context which is used to evaluate the expression
*/
public EvaluationContext createELContext(HttpServletRequest request) {
return new StandardEvaluationContext(new ELRequestMatcherContext(request));
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("EL [el=\"").append(this.expression.getExpressionString()).append("\"");
sb.append("]");
return sb.toString();
}
}
| 2,426 | 31.36 | 90 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/matcher/RequestMatcherEditor.java | /*
* Copyright 2010-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.util.matcher;
import java.beans.PropertyEditorSupport;
import org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint;
/**
* PropertyEditor which creates ELRequestMatcher instances from Strings
*
* This allows to use a String in a BeanDefinition instead of an (inner) bean if a
* RequestMatcher is required, e.g. in {@link DelegatingAuthenticationEntryPoint}
*
* @author Mike Wiesner
* @since 3.0.2
*/
public class RequestMatcherEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(new ELRequestMatcher(text));
}
}
| 1,298 | 31.475 | 90 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/matcher/RegexRequestMatcher.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.util.matcher;
import java.util.regex.Pattern;
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.http.HttpMethod;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Uses a regular expression to decide whether a supplied the URL of a supplied
* {@code HttpServletRequest}.
*
* Can also be configured to match a specific HTTP method.
*
* The match is performed against the {@code servletPath + pathInfo + queryString} of the
* request and is case-sensitive by default. Case-insensitive matching can be used by
* using the constructor which takes the {@code caseInsensitive} argument.
*
* @author Luke Taylor
* @author Rob Winch
* @since 3.1
*/
public final class RegexRequestMatcher implements RequestMatcher {
private static final int DEFAULT = Pattern.DOTALL;
private static final int CASE_INSENSITIVE = DEFAULT | Pattern.CASE_INSENSITIVE;
private static final Log logger = LogFactory.getLog(RegexRequestMatcher.class);
private final Pattern pattern;
private final HttpMethod httpMethod;
/**
* Creates a case-sensitive {@code Pattern} instance to match against the request.
* @param pattern the regular expression to compile into a pattern.
* @since 5.8
*/
public static RegexRequestMatcher regexMatcher(String pattern) {
Assert.hasText(pattern, "pattern cannot be empty");
return new RegexRequestMatcher(pattern, null);
}
/**
* Creates an instance that matches to all requests with the same {@link HttpMethod}.
* @param method the HTTP method to match. Must not be null.
* @since 5.8
*/
public static RegexRequestMatcher regexMatcher(HttpMethod method) {
Assert.notNull(method, "method cannot be null");
return new RegexRequestMatcher(".*", method.name());
}
/**
* Creates a case-sensitive {@code Pattern} instance to match against the request.
* @param method the HTTP method to match. May be null to match all methods.
* @param pattern the regular expression to compile into a pattern.
* @since 5.8
*/
public static RegexRequestMatcher regexMatcher(HttpMethod method, String pattern) {
Assert.notNull(method, "method cannot be null");
Assert.hasText(pattern, "pattern cannot be empty");
return new RegexRequestMatcher(pattern, method.name());
}
/**
* Creates a case-sensitive {@code Pattern} instance to match against the request.
* @param pattern the regular expression to compile into a pattern.
* @param httpMethod the HTTP method to match. May be null to match all methods.
*/
public RegexRequestMatcher(String pattern, String httpMethod) {
this(pattern, httpMethod, false);
}
/**
* As above, but allows setting of whether case-insensitive matching should be used.
* @param pattern the regular expression to compile into a pattern.
* @param httpMethod the HTTP method to match. May be null to match all methods.
* @param caseInsensitive if true, the pattern will be compiled with the
* {@link Pattern#CASE_INSENSITIVE} flag set.
*/
public RegexRequestMatcher(String pattern, String httpMethod, boolean caseInsensitive) {
this.pattern = Pattern.compile(pattern, caseInsensitive ? CASE_INSENSITIVE : DEFAULT);
this.httpMethod = StringUtils.hasText(httpMethod) ? HttpMethod.valueOf(httpMethod) : null;
}
/**
* Performs the match of the request URL ({@code servletPath + pathInfo + queryString}
* ) against the compiled pattern. If the query string is present, a question mark
* will be prepended.
* @param request the request to match
* @return true if the pattern matches the URL, false otherwise.
*/
@Override
public boolean matches(HttpServletRequest request) {
if (this.httpMethod != null && request.getMethod() != null
&& this.httpMethod != HttpMethod.valueOf(request.getMethod())) {
return false;
}
String url = request.getServletPath();
String pathInfo = request.getPathInfo();
String query = request.getQueryString();
if (pathInfo != null || query != null) {
StringBuilder sb = new StringBuilder(url);
if (pathInfo != null) {
sb.append(pathInfo);
}
if (query != null) {
sb.append('?').append(query);
}
url = sb.toString();
}
logger.debug(LogMessage.format("Checking match of request : '%s'; against '%s'", url, this.pattern));
return this.pattern.matcher(url).matches();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Regex [pattern='").append(this.pattern).append("'");
if (this.httpMethod != null) {
sb.append(", ").append(this.httpMethod);
}
sb.append("]");
return sb.toString();
}
}
| 5,404 | 34.794702 | 103 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/matcher/ELRequestMatcherContext.java | /*
* Copyright 2009-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.util.matcher;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.StringUtils;
class ELRequestMatcherContext {
private final HttpServletRequest request;
ELRequestMatcherContext(HttpServletRequest request) {
this.request = request;
}
public boolean hasIpAddress(String ipAddress) {
return (new IpAddressMatcher(ipAddress).matches(this.request));
}
public boolean hasHeader(String headerName, String value) {
String header = this.request.getHeader(headerName);
return StringUtils.hasText(header) && header.contains(value);
}
}
| 1,240 | 29.268293 | 75 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/matcher/OrRequestMatcher.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.util.matcher;
import java.util.Arrays;
import java.util.List;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.Assert;
/**
* {@link RequestMatcher} that will return true if any of the passed in
* {@link RequestMatcher} instances match.
*
* @author Rob Winch
* @since 3.2
*/
public final class OrRequestMatcher implements RequestMatcher {
private final List<RequestMatcher> requestMatchers;
/**
* Creates a new instance
* @param requestMatchers the {@link RequestMatcher} instances to try
*/
public OrRequestMatcher(List<RequestMatcher> requestMatchers) {
Assert.notEmpty(requestMatchers, "requestMatchers must contain a value");
Assert.noNullElements(requestMatchers, "requestMatchers cannot contain null values");
this.requestMatchers = requestMatchers;
}
/**
* Creates a new instance
* @param requestMatchers the {@link RequestMatcher} instances to try
*/
public OrRequestMatcher(RequestMatcher... requestMatchers) {
this(Arrays.asList(requestMatchers));
}
@Override
public boolean matches(HttpServletRequest request) {
for (RequestMatcher matcher : this.requestMatchers) {
if (matcher.matches(request)) {
return true;
}
}
return false;
}
/**
* Returns a {@link MatchResult} for this {@link HttpServletRequest}. In the case of a
* match, request variables are any request variables from the first underlying
* matcher.
* @param request the HTTP request
* @return a {@link MatchResult} based on the given HTTP request
* @since 6.1
*/
@Override
public MatchResult matcher(HttpServletRequest request) {
for (RequestMatcher matcher : this.requestMatchers) {
MatchResult result = matcher.matcher(request);
if (result.isMatch()) {
return result;
}
}
return MatchResult.notMatch();
}
@Override
public String toString() {
return "Or " + this.requestMatchers;
}
}
| 2,557 | 27.422222 | 87 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/matcher/RequestMatcherEntry.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.util.matcher;
/**
* A rich object for associating a {@link RequestMatcher} to another object.
*
* @author Marcus Da Coregio
* @since 5.5.5
*/
public class RequestMatcherEntry<T> {
private final RequestMatcher requestMatcher;
private final T entry;
public RequestMatcherEntry(RequestMatcher requestMatcher, T entry) {
this.requestMatcher = requestMatcher;
this.entry = entry;
}
public RequestMatcher getRequestMatcher() {
return this.requestMatcher;
}
public T getEntry() {
return this.entry;
}
}
| 1,188 | 25.422222 | 76 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/matcher/AnyRequestMatcher.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.util.matcher;
import jakarta.servlet.http.HttpServletRequest;
/**
* Matches any supplied request.
*
* @author Luke Taylor
* @since 3.1
*/
public final class AnyRequestMatcher implements RequestMatcher {
public static final RequestMatcher INSTANCE = new AnyRequestMatcher();
private AnyRequestMatcher() {
}
@Override
public boolean matches(HttpServletRequest request) {
return true;
}
@Override
@SuppressWarnings("deprecation")
public boolean equals(Object obj) {
return obj instanceof AnyRequestMatcher
|| obj instanceof org.springframework.security.web.util.matcher.AnyRequestMatcher;
}
@Override
public int hashCode() {
return 1;
}
@Override
public String toString() {
return "any request";
}
}
| 1,403 | 23.631579 | 86 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/matcher/AndRequestMatcher.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.util.matcher;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
/**
* {@link RequestMatcher} that will return true if all of the passed in
* {@link RequestMatcher} instances match.
*
* @author Rob Winch
* @since 3.2
*/
public final class AndRequestMatcher implements RequestMatcher {
private final Log logger = LogFactory.getLog(getClass());
private final List<RequestMatcher> requestMatchers;
/**
* Creates a new instance
* @param requestMatchers the {@link RequestMatcher} instances to try
*/
public AndRequestMatcher(List<RequestMatcher> requestMatchers) {
Assert.notEmpty(requestMatchers, "requestMatchers must contain a value");
Assert.noNullElements(requestMatchers, "requestMatchers cannot contain null values");
this.requestMatchers = requestMatchers;
}
/**
* Creates a new instance
* @param requestMatchers the {@link RequestMatcher} instances to try
*/
public AndRequestMatcher(RequestMatcher... requestMatchers) {
this(Arrays.asList(requestMatchers));
}
@Override
public boolean matches(HttpServletRequest request) {
for (RequestMatcher matcher : this.requestMatchers) {
if (!matcher.matches(request)) {
return false;
}
}
return true;
}
/**
* Returns a {@link MatchResult} for this {@link HttpServletRequest}. In the case of a
* match, request variables are a composition of the request variables in underlying
* matchers. In the event that two matchers have the same key, the last key is the one
* propagated.
* @param request the HTTP request
* @return a {@link MatchResult} based on the given HTTP request
* @since 6.1
*/
@Override
public MatchResult matcher(HttpServletRequest request) {
Map<String, String> variables = new LinkedHashMap<>();
for (RequestMatcher matcher : this.requestMatchers) {
MatchResult result = matcher.matcher(request);
if (!result.isMatch()) {
return MatchResult.notMatch();
}
variables.putAll(result.getVariables());
}
return MatchResult.match(variables);
}
@Override
public String toString() {
return "And " + this.requestMatchers;
}
}
| 2,981 | 29.121212 | 87 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/matcher/RequestMatcher.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.util.matcher;
import java.util.Collections;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
/**
* Simple strategy to match an <tt>HttpServletRequest</tt>.
*
* @author Luke Taylor
* @author Eddú Meléndez
* @since 3.0.2
*/
public interface RequestMatcher {
/**
* Decides whether the rule implemented by the strategy matches the supplied request.
* @param request the request to check for a match
* @return true if the request matches, false otherwise
*/
boolean matches(HttpServletRequest request);
/**
* Returns a MatchResult for this RequestMatcher The default implementation returns
* {@link Collections#emptyMap()} when {@link MatchResult#getVariables()} is invoked.
* @return the MatchResult from comparing this RequestMatcher against the
* HttpServletRequest
* @since 5.2
*/
default MatchResult matcher(HttpServletRequest request) {
boolean match = matches(request);
return new MatchResult(match, Collections.emptyMap());
}
/**
* The result of matching against an HttpServletRequest Contains the status, true or
* false, of the match and if present, any variables extracted from the match
*
* @since 5.2
*/
class MatchResult {
private final boolean match;
private final Map<String, String> variables;
MatchResult(boolean match, Map<String, String> variables) {
this.match = match;
this.variables = variables;
}
/**
* @return true if the comparison against the HttpServletRequest produced a
* successful match
*/
public boolean isMatch() {
return this.match;
}
/**
* Returns the extracted variable values where the key is the variable name and
* the value is the variable value
* @return a map containing key-value pairs representing extracted variable names
* and variable values
*/
public Map<String, String> getVariables() {
return this.variables;
}
/**
* Creates an instance of {@link MatchResult} that is a match with no variables
* @return
*/
public static MatchResult match() {
return new MatchResult(true, Collections.emptyMap());
}
/**
* Creates an instance of {@link MatchResult} that is a match with the specified
* variables
* @param variables
* @return
*/
public static MatchResult match(Map<String, String> variables) {
return new MatchResult(true, variables);
}
/**
* Creates an instance of {@link MatchResult} that is not a match.
* @return
*/
public static MatchResult notMatch() {
return new MatchResult(false, Collections.emptyMap());
}
}
}
| 3,229 | 26.844828 | 86 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/matcher/RequestHeaderRequestMatcher.java | /*
* Copyright 2002-2014 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.util.matcher;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.Assert;
/**
* A {@link RequestMatcher} that can be used to match request that contain a header with
* an expected header name and an expected value.
*
* <p>
* For example, the following will match an request that contains a header with the name
* X-Requested-With no matter what the value is.
* </p>
*
* <pre>
* RequestMatcher matcher = new RequestHeaderRequestMatcher("X-Requested-With");
* </pre>
*
* Alternatively, the RequestHeaderRequestMatcher can be more precise and require a
* specific value. For example the following will match on requests with the header name
* of X-Requested-With with the value of "XMLHttpRequest", but will not match on header
* name of "X-Requested-With" with the value of "Other".
*
* <pre>
* RequestMatcher matcher = new RequestHeaderRequestMatcher("X-Requested-With",
* "XMLHttpRequest");
* </pre>
*
* The value used to compare is the first header value, so in the previous example if the
* header "X-Requested-With" contains the values "Other" and "XMLHttpRequest", then it
* will not match.
*
* @author Rob Winch
* @since 3.2
*/
public final class RequestHeaderRequestMatcher implements RequestMatcher {
private final String expectedHeaderName;
private final String expectedHeaderValue;
/**
* Creates a new instance that will match if a header by the name of
* {@link #expectedHeaderName} is present. In this instance, the value does not
* matter.
* @param expectedHeaderName the name of the expected header that if present the
* request will match. Cannot be null.
*/
public RequestHeaderRequestMatcher(String expectedHeaderName) {
this(expectedHeaderName, null);
}
/**
* Creates a new instance that will match if a header by the name of
* {@link #expectedHeaderName} is present and if the {@link #expectedHeaderValue} is
* non-null the first value is the same.
* @param expectedHeaderName the name of the expected header. Cannot be null
* @param expectedHeaderValue the expected header value or null if the value does not
* matter
*/
public RequestHeaderRequestMatcher(String expectedHeaderName, String expectedHeaderValue) {
Assert.notNull(expectedHeaderName, "headerName cannot be null");
this.expectedHeaderName = expectedHeaderName;
this.expectedHeaderValue = expectedHeaderValue;
}
@Override
public boolean matches(HttpServletRequest request) {
String actualHeaderValue = request.getHeader(this.expectedHeaderName);
if (this.expectedHeaderValue == null) {
return actualHeaderValue != null;
}
return this.expectedHeaderValue.equals(actualHeaderValue);
}
@Override
public String toString() {
return "RequestHeaderRequestMatcher [expectedHeaderName=" + this.expectedHeaderName + ", expectedHeaderValue="
+ this.expectedHeaderValue + "]";
}
}
| 3,578 | 34.79 | 112 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/matcher/MediaTypeRequestMatcher.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.util.matcher;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.accept.ContentNegotiationStrategy;
import org.springframework.web.accept.HeaderContentNegotiationStrategy;
import org.springframework.web.context.request.ServletWebRequest;
/**
* Allows matching {@link HttpServletRequest} based upon the {@link MediaType}'s resolved
* from a {@link ContentNegotiationStrategy}.
*
* By default, the matching process will perform the following:
*
* <ul>
* <li>The {@link ContentNegotiationStrategy} will resolve the {@link MediaType} 's for
* the current request</li>
* <li>Each matchingMediaTypes that was passed into the constructor will be compared
* against the {@link MediaType} instances resolved from the
* {@link ContentNegotiationStrategy}.</li>
* <li>If one of the matchingMediaTypes is compatible with one of the resolved
* {@link MediaType} returned from the {@link ContentNegotiationStrategy}, then it returns
* true</li>
* </ul>
*
* For example, consider the following example
*
* <pre>
* GET /
* Accept: application/json
*
* ContentNegotiationStrategy negotiationStrategy = new HeaderContentNegotiationStrategy()
* MediaTypeRequestMatcher matcher = new MediaTypeRequestMatcher(negotiationStrategy, MediaType.APPLICATION_JSON);
* assert matcher.matches(request) == true // returns true
* </pre>
*
* The following will also return true
*
* <pre>
* GET /
* Accept: */*
*
* ContentNegotiationStrategy negotiationStrategy = new HeaderContentNegotiationStrategy()
* MediaTypeRequestMatcher matcher = new MediaTypeRequestMatcher(negotiationStrategy, MediaType.APPLICATION_JSON);
* assert matcher.matches(request) == true // returns true
* </pre>
*
* <h3>Ignoring Media Types</h3>
*
* Sometimes you may want to ignore certain types of media types. For example, you may
* want to match on "application/json" but ignore "*/" sent by a web browser.
*
* <pre>
* GET /
* Accept: */*
*
* ContentNegotiationStrategy negotiationStrategy = new HeaderContentNegotiationStrategy()
* MediaTypeRequestMatcher matcher = new MediaTypeRequestMatcher(negotiationStrategy, MediaType.APPLICATION_JSON);
* matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
* assert matcher.matches(request) == false // returns false
* </pre>
*
* <pre>
* GET /
* Accept: application/json
*
* ContentNegotiationStrategy negotiationStrategy = new HeaderContentNegotiationStrategy()
* MediaTypeRequestMatcher matcher = new MediaTypeRequestMatcher(negotiationStrategy, MediaType.APPLICATION_JSON);
* matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
* assert matcher.matches(request) == true // returns true
* </pre>
*
* <h3>Exact media type comparison</h3>
*
* By default as long as the {@link MediaType} discovered by
* {@link ContentNegotiationStrategy} returns true for
* {@link MediaType#isCompatibleWith(MediaType)} on the matchingMediaTypes, the result of
* the match is true. However, sometimes you may want to perform an exact match. This can
* be done with the following examples:
*
* <pre>
* GET /
* Accept: application/json
*
* ContentNegotiationStrategy negotiationStrategy = new HeaderContentNegotiationStrategy()
* MediaTypeRequestMatcher matcher = new MediaTypeRequestMatcher(negotiationStrategy, MediaType.APPLICATION_JSON);
* matcher.setUseEquals(true);
* assert matcher.matches(request) == true // returns true
* </pre>
*
* <pre>
* GET /
* Accept: application/*
*
* ContentNegotiationStrategy negotiationStrategy = new HeaderContentNegotiationStrategy()
* MediaTypeRequestMatcher matcher = new MediaTypeRequestMatcher(negotiationStrategy, MediaType.APPLICATION_JSON);
* matcher.setUseEquals(true);
* assert matcher.matches(request) == false // returns false
* </pre>
*
* <pre>
* GET /
* Accept: */*
*
* ContentNegotiationStrategy negotiationStrategy = new HeaderContentNegotiationStrategy()
* MediaTypeRequestMatcher matcher = new MediaTypeRequestMatcher(negotiationStrategy, MediaType.APPLICATION_JSON);
* matcher.setUseEquals(true);
* assert matcher.matches(request) == false // returns false
* </pre>
*
* @author Rob Winch
* @author Dan Zheng
* @since 3.2
*/
public final class MediaTypeRequestMatcher implements RequestMatcher {
private final Log logger = LogFactory.getLog(getClass());
private final ContentNegotiationStrategy contentNegotiationStrategy;
private final Collection<MediaType> matchingMediaTypes;
private boolean useEquals;
private Set<MediaType> ignoredMediaTypes = Collections.emptySet();
/**
* Creates an instance
* @param matchingMediaTypes the {@link MediaType} that will make the http request.
* @since 5.2
*/
public MediaTypeRequestMatcher(MediaType... matchingMediaTypes) {
this(new HeaderContentNegotiationStrategy(), Arrays.asList(matchingMediaTypes));
}
/**
* Creates an instance
* @param matchingMediaTypes the {@link MediaType} that will make the http request.
* @since 5.2
*/
public MediaTypeRequestMatcher(Collection<MediaType> matchingMediaTypes) {
this(new HeaderContentNegotiationStrategy(), matchingMediaTypes);
}
/**
* Creates an instance
* @param contentNegotiationStrategy the {@link ContentNegotiationStrategy} to use
* @param matchingMediaTypes the {@link MediaType} that will make the
* {@link RequestMatcher} return true
*/
public MediaTypeRequestMatcher(ContentNegotiationStrategy contentNegotiationStrategy,
MediaType... matchingMediaTypes) {
this(contentNegotiationStrategy, Arrays.asList(matchingMediaTypes));
}
/**
* Creates an instance
* @param contentNegotiationStrategy the {@link ContentNegotiationStrategy} to use
* @param matchingMediaTypes the {@link MediaType} that will make the
* {@link RequestMatcher} return true
*/
public MediaTypeRequestMatcher(ContentNegotiationStrategy contentNegotiationStrategy,
Collection<MediaType> matchingMediaTypes) {
Assert.notNull(contentNegotiationStrategy, "ContentNegotiationStrategy cannot be null");
Assert.notEmpty(matchingMediaTypes, "matchingMediaTypes cannot be null or empty");
this.contentNegotiationStrategy = contentNegotiationStrategy;
this.matchingMediaTypes = matchingMediaTypes;
}
@Override
public boolean matches(HttpServletRequest request) {
List<MediaType> httpRequestMediaTypes;
try {
httpRequestMediaTypes = this.contentNegotiationStrategy.resolveMediaTypes(new ServletWebRequest(request));
}
catch (HttpMediaTypeNotAcceptableException ex) {
this.logger.debug("Failed to match request since failed to parse MediaTypes", ex);
return false;
}
for (MediaType httpRequestMediaType : httpRequestMediaTypes) {
if (shouldIgnore(httpRequestMediaType)) {
continue;
}
if (this.useEquals) {
return this.matchingMediaTypes.contains(httpRequestMediaType);
}
for (MediaType matchingMediaType : this.matchingMediaTypes) {
boolean isCompatibleWith = matchingMediaType.isCompatibleWith(httpRequestMediaType);
if (isCompatibleWith) {
return true;
}
}
}
return false;
}
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;
}
@Override
public String toString() {
return "MediaTypeRequestMatcher [contentNegotiationStrategy=" + this.contentNegotiationStrategy
+ ", matchingMediaTypes=" + this.matchingMediaTypes + ", useEquals=" + this.useEquals
+ ", ignoredMediaTypes=" + this.ignoredMediaTypes + "]";
}
}
| 9,380 | 34.805344 | 114 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.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.util.matcher;
import java.net.InetAddress;
import java.net.UnknownHostException;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Matches a request based on IP Address or subnet mask matching against the remote
* address.
* <p>
* Both IPv6 and IPv4 addresses are supported, but a matcher which is configured with an
* IPv4 address will never match a request which returns an IPv6 address, and vice-versa.
*
* @author Luke Taylor
* @since 3.0.2
*/
public final class IpAddressMatcher implements RequestMatcher {
private final int nMaskBits;
private final InetAddress requiredAddress;
/**
* Takes a specific IP address or a range specified using the IP/Netmask (e.g.
* 192.168.1.0/24 or 202.24.0.0/14).
* @param ipAddress the address or range of addresses from which the request must
* come.
*/
public IpAddressMatcher(String ipAddress) {
if (ipAddress.indexOf('/') > 0) {
String[] addressAndMask = StringUtils.split(ipAddress, "/");
ipAddress = addressAndMask[0];
this.nMaskBits = Integer.parseInt(addressAndMask[1]);
}
else {
this.nMaskBits = -1;
}
this.requiredAddress = parseAddress(ipAddress);
Assert.isTrue(this.requiredAddress.getAddress().length * 8 >= this.nMaskBits,
String.format("IP address %s is too short for bitmask of length %d", ipAddress, this.nMaskBits));
}
@Override
public boolean matches(HttpServletRequest request) {
return matches(request.getRemoteAddr());
}
public boolean matches(String address) {
InetAddress remoteAddress = parseAddress(address);
if (!this.requiredAddress.getClass().equals(remoteAddress.getClass())) {
return false;
}
if (this.nMaskBits < 0) {
return remoteAddress.equals(this.requiredAddress);
}
byte[] remAddr = remoteAddress.getAddress();
byte[] reqAddr = this.requiredAddress.getAddress();
int nMaskFullBytes = this.nMaskBits / 8;
byte finalByte = (byte) (0xFF00 >> (this.nMaskBits & 0x07));
for (int i = 0; i < nMaskFullBytes; i++) {
if (remAddr[i] != reqAddr[i]) {
return false;
}
}
if (finalByte != 0) {
return (remAddr[nMaskFullBytes] & finalByte) == (reqAddr[nMaskFullBytes] & finalByte);
}
return true;
}
private InetAddress parseAddress(String address) {
try {
return InetAddress.getByName(address);
}
catch (UnknownHostException ex) {
throw new IllegalArgumentException("Failed to parse address '" + address + "'", ex);
}
}
}
| 3,169 | 30.386139 | 101 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/util/matcher/AntPathRequestMatcher.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.util.matcher;
import java.util.Collections;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpMethod;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UrlPathHelper;
/**
* Matcher which compares a pre-defined ant-style pattern against the URL (
* {@code servletPath + pathInfo}) of an {@code HttpServletRequest}. The query string of
* the URL is ignored and matching is case-insensitive or case-sensitive depending on the
* arguments passed into the constructor.
* <p>
* Using a pattern value of {@code /**} or {@code **} is treated as a universal match,
* which will match any request. Patterns which end with {@code /**} (and have no other
* wildcards) are optimized by using a substring match — a pattern of
* {@code /aaa/**} will match {@code /aaa}, {@code /aaa/} and any sub-directories, such as
* {@code /aaa/bbb/ccc}.
* </p>
* <p>
* For all other cases, Spring's {@link AntPathMatcher} is used to perform the match. See
* the Spring documentation for this class for comprehensive information on the syntax
* used.
* </p>
*
* @author Luke Taylor
* @author Rob Winch
* @author Eddú Meléndez
* @author Evgeniy Cheban
* @author Manuel Jordan
* @since 3.1
* @see org.springframework.util.AntPathMatcher
*/
public final class AntPathRequestMatcher implements RequestMatcher, RequestVariablesExtractor {
private static final String MATCH_ALL = "/**";
private final Matcher matcher;
private final String pattern;
private final HttpMethod httpMethod;
private final boolean caseSensitive;
private final UrlPathHelper urlPathHelper;
/**
* Creates a matcher with the specific pattern which will match all HTTP methods in a
* case-sensitive manner.
* @param pattern the ant pattern to use for matching
* @since 5.8
*/
public static AntPathRequestMatcher antMatcher(String pattern) {
Assert.hasText(pattern, "pattern cannot be empty");
return new AntPathRequestMatcher(pattern);
}
/**
* Creates a matcher that will match all request with the supplied HTTP method in a
* case-sensitive manner.
* @param method the HTTP method. The {@code matches} method will return false if the
* incoming request doesn't have the same method.
* @since 5.8
*/
public static AntPathRequestMatcher antMatcher(HttpMethod method) {
Assert.notNull(method, "method cannot be null");
return new AntPathRequestMatcher(MATCH_ALL, method.name());
}
/**
* Creates a matcher with the supplied pattern and HTTP method in a case-sensitive
* manner.
* @param method the HTTP method. The {@code matches} method will return false if the
* incoming request doesn't have the same method.
* @param pattern the ant pattern to use for matching
* @since 5.8
*/
public static AntPathRequestMatcher antMatcher(HttpMethod method, String pattern) {
Assert.notNull(method, "method cannot be null");
Assert.hasText(pattern, "pattern cannot be empty");
return new AntPathRequestMatcher(pattern, method.name());
}
/**
* Creates a matcher with the specific pattern which will match all HTTP methods in a
* case sensitive manner.
* @param pattern the ant pattern to use for matching
*/
public AntPathRequestMatcher(String pattern) {
this(pattern, null);
}
/**
* Creates a matcher with the supplied pattern and HTTP method in a case sensitive
* manner.
* @param pattern the ant pattern to use for matching
* @param httpMethod the HTTP method. The {@code matches} method will return false if
* the incoming request doesn't have the same method.
*/
public AntPathRequestMatcher(String pattern, String httpMethod) {
this(pattern, httpMethod, true);
}
/**
* Creates a matcher with the supplied pattern which will match the specified Http
* method
* @param pattern the ant pattern to use for matching
* @param httpMethod the HTTP method. The {@code matches} method will return false if
* the incoming request doesn't doesn't have the same method.
* @param caseSensitive true if the matcher should consider case, else false
*/
public AntPathRequestMatcher(String pattern, String httpMethod, boolean caseSensitive) {
this(pattern, httpMethod, caseSensitive, null);
}
/**
* Creates a matcher with the supplied pattern which will match the specified Http
* method
* @param pattern the ant pattern to use for matching
* @param httpMethod the HTTP method. The {@code matches} method will return false if
* the incoming request doesn't have the same method.
* @param caseSensitive true if the matcher should consider case, else false
* @param urlPathHelper if non-null, will be used for extracting the path from the
* HttpServletRequest
*/
public AntPathRequestMatcher(String pattern, String httpMethod, boolean caseSensitive,
UrlPathHelper urlPathHelper) {
Assert.hasText(pattern, "Pattern cannot be null or empty");
this.caseSensitive = caseSensitive;
if (pattern.equals(MATCH_ALL) || pattern.equals("**")) {
pattern = MATCH_ALL;
this.matcher = null;
}
else {
// If the pattern ends with {@code /**} and has no other wildcards or path
// variables, then optimize to a sub-path match
if (pattern.endsWith(MATCH_ALL)
&& (pattern.indexOf('?') == -1 && pattern.indexOf('{') == -1 && pattern.indexOf('}') == -1)
&& pattern.indexOf("*") == pattern.length() - 2) {
this.matcher = new SubpathMatcher(pattern.substring(0, pattern.length() - 3), caseSensitive);
}
else {
this.matcher = new SpringAntMatcher(pattern, caseSensitive);
}
}
this.pattern = pattern;
this.httpMethod = StringUtils.hasText(httpMethod) ? HttpMethod.valueOf(httpMethod) : null;
this.urlPathHelper = urlPathHelper;
}
/**
* Returns true if the configured pattern (and HTTP-Method) match those of the
* supplied request.
* @param request the request to match against. The ant pattern will be matched
* against the {@code servletPath} + {@code pathInfo} of the request.
*/
@Override
public boolean matches(HttpServletRequest request) {
if (this.httpMethod != null && StringUtils.hasText(request.getMethod())
&& this.httpMethod != HttpMethod.valueOf(request.getMethod())) {
return false;
}
if (this.pattern.equals(MATCH_ALL)) {
return true;
}
String url = getRequestPath(request);
return this.matcher.matches(url);
}
@Override
@Deprecated
public Map<String, String> extractUriTemplateVariables(HttpServletRequest request) {
return matcher(request).getVariables();
}
@Override
public MatchResult matcher(HttpServletRequest request) {
if (!matches(request)) {
return MatchResult.notMatch();
}
if (this.matcher == null) {
return MatchResult.match();
}
String url = getRequestPath(request);
return MatchResult.match(this.matcher.extractUriTemplateVariables(url));
}
private String getRequestPath(HttpServletRequest request) {
if (this.urlPathHelper != null) {
return this.urlPathHelper.getPathWithinApplication(request);
}
String url = request.getServletPath();
String pathInfo = request.getPathInfo();
if (pathInfo != null) {
url = StringUtils.hasLength(url) ? url + pathInfo : pathInfo;
}
return url;
}
public String getPattern() {
return this.pattern;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof AntPathRequestMatcher other)) {
return false;
}
return this.pattern.equals(other.pattern) && this.httpMethod == other.httpMethod
&& this.caseSensitive == other.caseSensitive;
}
@Override
public int hashCode() {
int result = (this.pattern != null) ? this.pattern.hashCode() : 0;
result = 31 * result + ((this.httpMethod != null) ? this.httpMethod.hashCode() : 0);
result = 31 * result + (this.caseSensitive ? 1231 : 1237);
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Ant [pattern='").append(this.pattern).append("'");
if (this.httpMethod != null) {
sb.append(", ").append(this.httpMethod);
}
sb.append("]");
return sb.toString();
}
private interface Matcher {
boolean matches(String path);
Map<String, String> extractUriTemplateVariables(String path);
}
private static final class SpringAntMatcher implements Matcher {
private final AntPathMatcher antMatcher;
private final String pattern;
private SpringAntMatcher(String pattern, boolean caseSensitive) {
this.pattern = pattern;
this.antMatcher = createMatcher(caseSensitive);
}
@Override
public boolean matches(String path) {
return this.antMatcher.match(this.pattern, path);
}
@Override
public Map<String, String> extractUriTemplateVariables(String path) {
return this.antMatcher.extractUriTemplateVariables(this.pattern, path);
}
private static AntPathMatcher createMatcher(boolean caseSensitive) {
AntPathMatcher matcher = new AntPathMatcher();
matcher.setTrimTokens(false);
matcher.setCaseSensitive(caseSensitive);
return matcher;
}
}
/**
* Optimized matcher for trailing wildcards
*/
private static final class SubpathMatcher implements Matcher {
private final String subpath;
private final int length;
private final boolean caseSensitive;
private SubpathMatcher(String subpath, boolean caseSensitive) {
Assert.isTrue(!subpath.contains("*"), "subpath cannot contain \"*\"");
this.subpath = caseSensitive ? subpath : subpath.toLowerCase();
this.length = subpath.length();
this.caseSensitive = caseSensitive;
}
@Override
public boolean matches(String path) {
if (!this.caseSensitive) {
path = path.toLowerCase();
}
return path.startsWith(this.subpath) && (path.length() == this.length || path.charAt(this.length) == '/');
}
@Override
public Map<String, String> extractUriTemplateVariables(String path) {
return Collections.emptyMap();
}
}
}
| 10,628 | 31.504587 | 109 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/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.
*/
/**
* Session management filters, {@code HttpSession} events and publisher classes.
*/
package org.springframework.security.web.session;
| 762 | 35.333333 | 80 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/session/HttpSessionIdChangedEvent.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.session;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.core.session.SessionIdChangedEvent;
/**
* Published by the {@link HttpSessionEventPublisher} when an {@link HttpSession} ID is
* changed.
*
* @since 5.4
*/
public class HttpSessionIdChangedEvent extends SessionIdChangedEvent {
private final String oldSessionId;
private final String newSessionId;
public HttpSessionIdChangedEvent(HttpSession session, String oldSessionId) {
super(session);
this.oldSessionId = oldSessionId;
this.newSessionId = session.getId();
}
@Override
public String getOldSessionId() {
return this.oldSessionId;
}
@Override
public String getNewSessionId() {
return this.newSessionId;
}
}
| 1,393 | 25.807692 | 87 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/session/InvalidSessionAccessDeniedHandler.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.session;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.util.Assert;
/**
* An adapter of {@link InvalidSessionStrategy} to {@link AccessDeniedHandler}
*
* @author Rob Winch
* @since 3.2
*/
public final class InvalidSessionAccessDeniedHandler implements AccessDeniedHandler {
private final InvalidSessionStrategy invalidSessionStrategy;
/**
* Creates a new instance
* @param invalidSessionStrategy the {@link InvalidSessionStrategy} to delegate to
*/
public InvalidSessionAccessDeniedHandler(InvalidSessionStrategy invalidSessionStrategy) {
Assert.notNull(invalidSessionStrategy, "invalidSessionStrategy cannot be null");
this.invalidSessionStrategy = invalidSessionStrategy;
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
this.invalidSessionStrategy.onInvalidSessionDetected(request, response);
}
}
| 1,904 | 33.636364 | 90 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/session/ForceEagerSessionCreationFilter.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.session;
import java.io.IOException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.core.log.LogMessage;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* Eagerly creates {@link HttpSession} if it does not already exist.
*
* @author Rob Winch
* @since 5.7
*/
public class ForceEagerSessionCreationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
HttpSession session = request.getSession();
if (this.logger.isDebugEnabled() && session.isNew()) {
this.logger.debug(LogMessage.format("Created session eagerly"));
}
filterChain.doFilter(request, response);
}
}
| 1,613 | 31.938776 | 115 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/session/HttpSessionEventPublisher.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.session;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionIdListener;
import jakarta.servlet.http.HttpSessionListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.core.log.LogMessage;
import org.springframework.security.web.context.support.SecurityWebApplicationContextUtils;
/**
* Declared in web.xml as
*
* <pre>
* <listener>
* <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
* </listener>
* </pre>
*
* Publishes <code>HttpSessionApplicationEvent</code>s to the Spring Root
* WebApplicationContext. Maps jakarta.servlet.http.HttpSessionListener.sessionCreated()
* to {@link HttpSessionCreatedEvent}. Maps
* jakarta.servlet.http.HttpSessionListener.sessionDestroyed() to
* {@link HttpSessionDestroyedEvent}.
*
* @author Ray Krueger
*/
public class HttpSessionEventPublisher implements HttpSessionListener, HttpSessionIdListener {
private static final String LOGGER_NAME = HttpSessionEventPublisher.class.getName();
ApplicationContext getContext(ServletContext servletContext) {
return SecurityWebApplicationContextUtils.findRequiredWebApplicationContext(servletContext);
}
/**
* Handles the HttpSessionEvent by publishing a {@link HttpSessionCreatedEvent} to the
* application appContext.
* @param event HttpSessionEvent passed in by the container
*/
@Override
public void sessionCreated(HttpSessionEvent event) {
extracted(event.getSession(), new HttpSessionCreatedEvent(event.getSession()));
}
/**
* Handles the HttpSessionEvent by publishing a {@link HttpSessionDestroyedEvent} to
* the application appContext.
* @param event The HttpSessionEvent pass in by the container
*/
@Override
public void sessionDestroyed(HttpSessionEvent event) {
extracted(event.getSession(), new HttpSessionDestroyedEvent(event.getSession()));
}
@Override
public void sessionIdChanged(HttpSessionEvent event, String oldSessionId) {
extracted(event.getSession(), new HttpSessionIdChangedEvent(event.getSession(), oldSessionId));
}
private void extracted(HttpSession session, ApplicationEvent e) {
Log log = LogFactory.getLog(LOGGER_NAME);
log.debug(LogMessage.format("Publishing event: %s", e));
getContext(session.getServletContext()).publishEvent(e);
}
}
| 3,250 | 35.52809 | 118 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/session/HttpSessionCreatedEvent.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.session;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.core.session.SessionCreationEvent;
/**
* Published by the {@link HttpSessionEventPublisher} when an {@code HttpSession} is
* created by the container
*
* @author Ray Krueger
* @author Luke Taylor
*/
public class HttpSessionCreatedEvent extends SessionCreationEvent {
public HttpSessionCreatedEvent(HttpSession session) {
super(session);
}
public HttpSession getSession() {
return (HttpSession) getSource();
}
}
| 1,185 | 27.926829 | 84 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/session/SessionManagementFilter.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.session;
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.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
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.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.util.Assert;
import org.springframework.web.filter.GenericFilterBean;
/**
* Detects that a user has been authenticated since the start of the request and, if they
* have, calls the configured {@link SessionAuthenticationStrategy} to perform any
* session-related activity such as activating session-fixation protection mechanisms or
* checking for multiple concurrent logins.
*
* @author Martin Algesten
* @author Luke Taylor
* @since 2.0
*/
public class SessionManagementFilter extends GenericFilterBean {
static final String FILTER_APPLIED = "__spring_security_session_mgmt_filter_applied";
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private final SecurityContextRepository securityContextRepository;
private SessionAuthenticationStrategy sessionAuthenticationStrategy;
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
private InvalidSessionStrategy invalidSessionStrategy = null;
private AuthenticationFailureHandler failureHandler = new SimpleUrlAuthenticationFailureHandler();
public SessionManagementFilter(SecurityContextRepository securityContextRepository) {
this(securityContextRepository, new SessionFixationProtectionStrategy());
}
public SessionManagementFilter(SecurityContextRepository securityContextRepository,
SessionAuthenticationStrategy sessionStrategy) {
Assert.notNull(securityContextRepository, "SecurityContextRepository cannot be null");
Assert.notNull(sessionStrategy, "SessionAuthenticationStrategy cannot be null");
this.securityContextRepository = securityContextRepository;
this.sessionAuthenticationStrategy = sessionStrategy;
}
@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 (request.getAttribute(FILTER_APPLIED) != null) {
chain.doFilter(request, response);
return;
}
request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
if (!this.securityContextRepository.containsContext(request)) {
Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication();
if (authentication != null && !this.trustResolver.isAnonymous(authentication)) {
// The user has been authenticated during the current request, so call the
// session strategy
try {
this.sessionAuthenticationStrategy.onAuthentication(authentication, request, response);
}
catch (SessionAuthenticationException ex) {
// The session strategy can reject the authentication
this.logger.debug("SessionAuthenticationStrategy rejected the authentication object", ex);
this.securityContextHolderStrategy.clearContext();
this.failureHandler.onAuthenticationFailure(request, response, ex);
return;
}
// Eagerly save the security context to make it available for any possible
// re-entrant requests which may occur before the current request
// completes. SEC-1396.
this.securityContextRepository.saveContext(this.securityContextHolderStrategy.getContext(), request,
response);
}
else {
// No security context or authentication present. Check for a session
// timeout
if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {
if (this.logger.isDebugEnabled()) {
this.logger.debug(LogMessage.format("Request requested invalid session id %s",
request.getRequestedSessionId()));
}
if (this.invalidSessionStrategy != null) {
this.invalidSessionStrategy.onInvalidSessionDetected(request, response);
return;
}
}
}
}
chain.doFilter(request, response);
}
/**
* Sets the strategy which will be invoked instead of allowing the filter chain to
* proceed, if the user agent requests an invalid session ID. If the property is not
* set, no action will be taken.
* @param invalidSessionStrategy the strategy to invoke. Typically a
* {@link SimpleRedirectInvalidSessionStrategy}.
*/
public void setInvalidSessionStrategy(InvalidSessionStrategy invalidSessionStrategy) {
this.invalidSessionStrategy = invalidSessionStrategy;
}
/**
* The handler which will be invoked if the <tt>AuthenticatedSessionStrategy</tt>
* raises a <tt>SessionAuthenticationException</tt>, indicating that the user is not
* allowed to be authenticated for this session (typically because they already have
* too many sessions open).
*
*/
public void setAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) {
Assert.notNull(failureHandler, "failureHandler cannot be null");
this.failureHandler = failureHandler;
}
/**
* Sets the {@link AuthenticationTrustResolver} to be used. The default is
* {@link AuthenticationTrustResolverImpl}.
* @param trustResolver the {@link AuthenticationTrustResolver} to use. Cannot be
* null.
*/
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
Assert.notNull(trustResolver, "trustResolver cannot be null");
this.trustResolver = trustResolver;
}
/**
* 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;
}
}
| 7,772 | 42.183333 | 108 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/session/DisableEncodeUrlFilter.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.session;
import java.io.IOException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* Disables encoding URLs using the {@link HttpServletResponse} to prevent including the
* session id in URLs which is not considered URL because the session id can be leaked in
* things like HTTP access logs.
*
* @author Rob Winch
* @since 5.7
*/
public class DisableEncodeUrlFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
filterChain.doFilter(request, new DisableEncodeUrlResponseWrapper(response));
}
/**
* Disables URL rewriting for the {@link HttpServletResponse} to prevent including the
* session id in URLs which is not considered URL because the session id can be leaked
* in things like HTTP access logs.
*
* @author Rob Winch
* @since 5.7
*/
private static final class DisableEncodeUrlResponseWrapper extends HttpServletResponseWrapper {
/**
* Constructs a response adaptor wrapping the given response.
* @param response the {@link HttpServletResponse} to be wrapped.
* @throws IllegalArgumentException if the response is null
*/
private DisableEncodeUrlResponseWrapper(HttpServletResponse response) {
super(response);
}
@Override
public String encodeRedirectURL(String url) {
return url;
}
@Override
public String encodeURL(String url) {
return url;
}
}
}
| 2,399 | 30.168831 | 115 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/session/SessionInformationExpiredEvent.java | /*
* Copyright 2012-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.session;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationEvent;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.util.Assert;
/**
* An event for when a {@link SessionInformation} is expired.
*
* @author Rob Winch
* @since 4.2
*/
public final class SessionInformationExpiredEvent extends ApplicationEvent {
private final HttpServletRequest request;
private final HttpServletResponse response;
/**
* Creates a new instance
* @param sessionInformation the SessionInformation that is expired
* @param request the HttpServletRequest
* @param response the HttpServletResponse
*/
public SessionInformationExpiredEvent(SessionInformation sessionInformation, HttpServletRequest request,
HttpServletResponse response) {
super(sessionInformation);
Assert.notNull(request, "request cannot be null");
Assert.notNull(response, "response cannot be null");
this.request = request;
this.response = response;
}
/**
* @return the request
*/
public HttpServletRequest getRequest() {
return this.request;
}
/**
* @return the response
*/
public HttpServletResponse getResponse() {
return this.response;
}
public SessionInformation getSessionInformation() {
return (SessionInformation) getSource();
}
}
| 2,051 | 27.5 | 105 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/session/HttpSessionDestroyedEvent.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.session;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.session.SessionDestroyedEvent;
/**
* Published by the {@link HttpSessionEventPublisher} when a HttpSession is removed from
* the container
*
* @author Ray Krueger
* @author Luke Taylor
* @author Rob Winch
*/
public class HttpSessionDestroyedEvent extends SessionDestroyedEvent {
public HttpSessionDestroyedEvent(HttpSession session) {
super(session);
}
public HttpSession getSession() {
return (HttpSession) getSource();
}
@SuppressWarnings("unchecked")
@Override
public List<SecurityContext> getSecurityContexts() {
HttpSession session = getSession();
Enumeration<String> attributes = session.getAttributeNames();
ArrayList<SecurityContext> contexts = new ArrayList<>();
while (attributes.hasMoreElements()) {
String attributeName = attributes.nextElement();
Object attributeValue = session.getAttribute(attributeName);
if (attributeValue instanceof SecurityContext) {
contexts.add((SecurityContext) attributeValue);
}
}
return contexts;
}
@Override
public String getId() {
return getSession().getId();
}
}
| 1,975 | 28.058824 | 88 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/session/SimpleRedirectInvalidSessionStrategy.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.session;
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.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;
/**
* Performs a redirect to a fixed URL when an invalid requested session is detected by the
* {@code SessionManagementFilter}.
*
* @author Luke Taylor
*/
public final class SimpleRedirectInvalidSessionStrategy implements InvalidSessionStrategy {
private final Log logger = LogFactory.getLog(getClass());
private final String destinationUrl;
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private boolean createNewSession = true;
public SimpleRedirectInvalidSessionStrategy(String invalidSessionUrl) {
Assert.isTrue(UrlUtils.isValidRedirectUrl(invalidSessionUrl), "url must start with '/' or with 'http(s)'");
this.destinationUrl = invalidSessionUrl;
}
@Override
public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Starting new session (if required) and redirecting to '" + this.destinationUrl + "'");
}
if (this.createNewSession) {
request.getSession();
}
this.redirectStrategy.sendRedirect(request, response, this.destinationUrl);
}
/**
* Determines whether a new session should be created before redirecting (to avoid
* possible looping issues where the same session ID is sent with the redirected
* request). Alternatively, ensure that the configured URL does not pass through the
* {@code SessionManagementFilter}.
* @param createNewSession defaults to {@code true}.
*/
public void setCreateNewSession(boolean createNewSession) {
this.createNewSession = createNewSession;
}
}
| 2,699 | 35 | 116 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/session/RequestedUrlRedirectInvalidSessionStrategy.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.session;
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.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
/**
* Performs a redirect to the original request URL when an invalid requested session is
* detected by the {@code SessionManagementFilter}.
*
* @author Craig Andrews
*/
public final class RequestedUrlRedirectInvalidSessionStrategy implements InvalidSessionStrategy {
private final Log logger = LogFactory.getLog(getClass());
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private boolean createNewSession = true;
@Override
public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException {
String destinationUrl = ServletUriComponentsBuilder.fromRequest(request).host(null).scheme(null).port(null)
.toUriString();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Starting new session (if required) and redirecting to '" + destinationUrl + "'");
}
if (this.createNewSession) {
request.getSession();
}
this.redirectStrategy.sendRedirect(request, response, destinationUrl);
}
/**
* Determines whether a new session should be created before redirecting (to avoid
* possible looping issues where the same session ID is sent with the redirected
* request). Alternatively, ensure that the configured URL does not pass through the
* {@code SessionManagementFilter}.
* @param createNewSession defaults to {@code true}.
*/
public void setCreateNewSession(boolean createNewSession) {
this.createNewSession = createNewSession;
}
}
| 2,552 | 36 | 116 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/session/ConcurrentSessionFilter.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.session;
import java.io.IOException;
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 jakarta.servlet.http.HttpSession;
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.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.logout.CompositeLogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;
import org.springframework.web.filter.GenericFilterBean;
/**
* Filter required by concurrent session handling package.
* <p>
* This filter performs two functions. First, it calls
* {@link org.springframework.security.core.session.SessionRegistry#refreshLastRequest(String)}
* for each request so that registered sessions always have a correct "last update"
* date/time. Second, it retrieves a
* {@link org.springframework.security.core.session.SessionInformation} from the
* <code>SessionRegistry</code> for each request and checks if the session has been marked
* as expired. If it has been marked as expired, the configured logout handlers will be
* called (as happens with
* {@link org.springframework.security.web.authentication.logout.LogoutFilter}), typically
* to invalidate the session. To handle the expired session a call to the
* {@link SessionInformationExpiredStrategy} is made. The session invalidation will cause
* an {@link org.springframework.security.web.session.HttpSessionDestroyedEvent} to be
* published via the
* {@link org.springframework.security.web.session.HttpSessionEventPublisher} registered
* in <code>web.xml</code>.
* </p>
*
* @author Ben Alex
* @author Eddú Meléndez
* @author Marten Deinum
* @author Onur Kagan Ozcan
*/
public class ConcurrentSessionFilter extends GenericFilterBean {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private final SessionRegistry sessionRegistry;
private String expiredUrl;
private RedirectStrategy redirectStrategy;
private LogoutHandler handlers = new CompositeLogoutHandler(new SecurityContextLogoutHandler());
private SessionInformationExpiredStrategy sessionInformationExpiredStrategy;
public ConcurrentSessionFilter(SessionRegistry sessionRegistry) {
Assert.notNull(sessionRegistry, "SessionRegistry required");
this.sessionRegistry = sessionRegistry;
this.sessionInformationExpiredStrategy = new ResponseBodySessionInformationExpiredStrategy();
}
/**
* Creates a new instance
* @param sessionRegistry the SessionRegistry to use
* @param expiredUrl the URL to redirect to
* @deprecated use
* {@link #ConcurrentSessionFilter(SessionRegistry, SessionInformationExpiredStrategy)}
* with {@link SimpleRedirectSessionInformationExpiredStrategy} instead.
*/
@Deprecated
public ConcurrentSessionFilter(SessionRegistry sessionRegistry, String expiredUrl) {
Assert.notNull(sessionRegistry, "SessionRegistry required");
Assert.isTrue(expiredUrl == null || UrlUtils.isValidRedirectUrl(expiredUrl),
() -> expiredUrl + " isn't a valid redirect URL");
this.expiredUrl = expiredUrl;
this.sessionRegistry = sessionRegistry;
this.sessionInformationExpiredStrategy = (event) -> {
HttpServletRequest request = event.getRequest();
HttpServletResponse response = event.getResponse();
SessionInformation info = event.getSessionInformation();
this.redirectStrategy.sendRedirect(request, response, determineExpiredUrl(request, info));
};
}
public ConcurrentSessionFilter(SessionRegistry sessionRegistry,
SessionInformationExpiredStrategy sessionInformationExpiredStrategy) {
Assert.notNull(sessionRegistry, "sessionRegistry required");
Assert.notNull(sessionInformationExpiredStrategy, "sessionInformationExpiredStrategy cannot be null");
this.sessionRegistry = sessionRegistry;
this.sessionInformationExpiredStrategy = sessionInformationExpiredStrategy;
}
@Override
public void afterPropertiesSet() {
Assert.notNull(this.sessionRegistry, "SessionRegistry 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 {
HttpSession session = request.getSession(false);
if (session != null) {
SessionInformation info = this.sessionRegistry.getSessionInformation(session.getId());
if (info != null) {
if (info.isExpired()) {
// Expired - abort processing
this.logger.debug(LogMessage
.of(() -> "Requested session ID " + request.getRequestedSessionId() + " has expired."));
doLogout(request, response);
this.sessionInformationExpiredStrategy
.onExpiredSessionDetected(new SessionInformationExpiredEvent(info, request, response));
return;
}
// Non-expired - update last request date/time
this.sessionRegistry.refreshLastRequest(info.getSessionId());
}
}
chain.doFilter(request, response);
}
/**
* Determine the URL for expiration
* @param request the HttpServletRequest
* @param info the {@link SessionInformation}
* @return the URL for expiration
* @deprecated Use
* {@link #ConcurrentSessionFilter(SessionRegistry, SessionInformationExpiredStrategy)}
* instead.
*/
@Deprecated
protected String determineExpiredUrl(HttpServletRequest request, SessionInformation info) {
return this.expiredUrl;
}
private void doLogout(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = this.securityContextHolderStrategy.getContext().getAuthentication();
this.handlers.logout(request, response, auth);
}
/**
* 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 setLogoutHandlers(LogoutHandler[] handlers) {
this.handlers = new CompositeLogoutHandler(handlers);
}
/**
* Set list of {@link LogoutHandler}
* @param handlers list of {@link LogoutHandler}
* @since 5.2.0
*/
public void setLogoutHandlers(List<LogoutHandler> handlers) {
this.handlers = new CompositeLogoutHandler(handlers);
}
/**
* Sets the {@link RedirectStrategy} used with
* {@link #ConcurrentSessionFilter(SessionRegistry, String)}
* @param redirectStrategy the {@link RedirectStrategy} to use
* @deprecated use
* {@link #ConcurrentSessionFilter(SessionRegistry, SessionInformationExpiredStrategy)}
* instead.
*/
@Deprecated
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
/**
* A {@link SessionInformationExpiredStrategy} that writes an error message to the
* response body.
*
* @author Rob Winch
* @since 4.2
*/
private static final class ResponseBodySessionInformationExpiredStrategy
implements SessionInformationExpiredStrategy {
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException {
HttpServletResponse response = event.getResponse();
response.getWriter().print("This session has been expired (possibly due to multiple concurrent "
+ "logins being attempted as the same user).");
response.flushBuffer();
}
}
}
| 9,115 | 38.293103 | 108 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/session/SimpleRedirectSessionInformationExpiredStrategy.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.session;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;
/**
* Performs a redirect to a fixed URL when an expired session is detected by the
* {@code ConcurrentSessionFilter}.
*
* @author Marten Deinum
* @since 4.2.0
*/
public final class SimpleRedirectSessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {
private final Log logger = LogFactory.getLog(getClass());
private final String destinationUrl;
private final RedirectStrategy redirectStrategy;
public SimpleRedirectSessionInformationExpiredStrategy(String invalidSessionUrl) {
this(invalidSessionUrl, new DefaultRedirectStrategy());
}
public SimpleRedirectSessionInformationExpiredStrategy(String invalidSessionUrl,
RedirectStrategy redirectStrategy) {
Assert.isTrue(UrlUtils.isValidRedirectUrl(invalidSessionUrl), "url must start with '/' or with 'http(s)'");
this.destinationUrl = invalidSessionUrl;
this.redirectStrategy = redirectStrategy;
}
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException {
this.logger.debug("Redirecting to '" + this.destinationUrl + "'");
this.redirectStrategy.sendRedirect(event.getRequest(), event.getResponse(), this.destinationUrl);
}
}
| 2,194 | 34.403226 | 113 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/session/SessionInformationExpiredStrategy.java | /*
* Copyright 2015-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.session;
import java.io.IOException;
import jakarta.servlet.ServletException;
/**
* Determines the behaviour of the {@code ConcurrentSessionFilter} when an expired session
* is detected in the {@code ConcurrentSessionFilter}.
*
* @author Marten Deinum
* @author Rob Winch
* @since 4.2.0
*/
public interface SessionInformationExpiredStrategy {
void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException;
}
| 1,128 | 30.361111 | 106 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/session/InvalidSessionStrategy.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.session;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Determines the behaviour of the {@code SessionManagementFilter} when an invalid session
* Id is submitted and detected in the {@code SessionManagementFilter}.
*
* @author Luke Taylor
*/
public interface InvalidSessionStrategy {
void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException;
}
| 1,215 | 31.864865 | 90 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/bind/support/AuthenticationPrincipalArgumentResolver.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.bind.support;
import java.lang.annotation.Annotation;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
* Allows resolving the {@link Authentication#getPrincipal()} using the
* {@link AuthenticationPrincipal} annotation. For example, the following
* {@link Controller}:
*
* <pre>
* @Controller
* public class MyController {
* @RequestMapping("/user/current/show")
* public String show(@AuthenticationPrincipal CustomUser customUser) {
* // do something with CustomUser
* return "view";
* }
* }
* </pre>
*
* <p>
* Will resolve the CustomUser argument using {@link Authentication#getPrincipal()} from
* the {@link SecurityContextHolder}. If the {@link Authentication} or
* {@link Authentication#getPrincipal()} is null, it will return null. If the types do not
* match, null will be returned unless
* {@link AuthenticationPrincipal#errorOnInvalidType()} is true in which case a
* {@link ClassCastException} will be thrown.
*
* <p>
* Alternatively, users can create a custom meta annotation as shown below:
*
* <pre>
* @Target({ ElementType.PARAMETER })
* @Retention(RetentionPolicy.RUNTIME)
* @AuthenticationPrincipal
* public @interface CurrentUser {
* }
* </pre>
*
* <p>
* The custom annotation can then be used instead. For example:
*
* <pre>
* @Controller
* public class MyController {
* @RequestMapping("/user/current/show")
* public String show(@CurrentUser CustomUser customUser) {
* // do something with CustomUser
* return "view";
* }
* }
* </pre>
*
* @author Rob Winch
* @since 3.2
* @deprecated Use
* {@link org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver}
* instead.
*/
@Deprecated
public final class AuthenticationPrincipalArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return findMethodAnnotation(AuthenticationPrincipal.class, parameter) != null;
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
return null;
}
Object principal = authentication.getPrincipal();
if (principal != null && !parameter.getParameterType().isAssignableFrom(principal.getClass())) {
AuthenticationPrincipal authPrincipal = findMethodAnnotation(AuthenticationPrincipal.class, parameter);
if (authPrincipal.errorOnInvalidType()) {
throw new ClassCastException(principal + " is not assignable to " + parameter.getParameterType());
}
return null;
}
return principal;
}
/**
* Obtains the specified {@link Annotation} on the specified {@link MethodParameter}.
* @param annotationClass the class of the {@link Annotation} to find on the
* {@link MethodParameter}
* @param parameter the {@link MethodParameter} to search for an {@link Annotation}
* @return the {@link Annotation} that was found or null.
*/
private <T extends Annotation> T findMethodAnnotation(Class<T> annotationClass, MethodParameter parameter) {
T annotation = parameter.getParameterAnnotation(annotationClass);
if (annotation != null) {
return annotation;
}
Annotation[] annotationsToSearch = parameter.getParameterAnnotations();
for (Annotation toSearch : annotationsToSearch) {
annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), annotationClass);
if (annotation != null) {
return annotation;
}
}
return null;
}
}
| 4,956 | 35.448529 | 109 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/bind/annotation/AuthenticationPrincipal.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.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.security.core.Authentication;
/**
* Annotation that binds a method parameter or method return value to the
* {@link Authentication#getPrincipal()}. This is necessary to signal that the argument
* should be resolved to the current user rather than a user that might be edited on a
* form.
* @deprecated Use
* {@link org.springframework.security.core.annotation.AuthenticationPrincipal} instead.
*
* @author Rob Winch
* @since 3.2
*/
@Target({ ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Deprecated
public @interface AuthenticationPrincipal {
/**
* True if a {@link ClassCastException} should be thrown when the current
* {@link Authentication#getPrincipal()} is the incorrect type. Default is false.
* @return
*/
boolean errorOnInvalidType() default false;
}
| 1,751 | 32.692308 | 88 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/CsrfTokenRequestHandler.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.csrf;
import java.util.function.Supplier;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.Assert;
/**
* A callback interface that is used to make the {@link CsrfToken} created by the
* {@link CsrfTokenRepository} available as a request attribute. Implementations of this
* interface may choose to perform additional tasks or customize how the token is made
* available to the application through request attributes.
*
* @author Steve Riesenberg
* @since 5.8
* @see CsrfTokenRequestAttributeHandler
*/
@FunctionalInterface
public interface CsrfTokenRequestHandler extends CsrfTokenRequestResolver {
/**
* Handles a request using a {@link CsrfToken}.
* @param request the {@code HttpServletRequest} being handled
* @param response the {@code HttpServletResponse} being handled
* @param csrfToken the {@link CsrfToken} created by the {@link CsrfTokenRepository}
*/
void handle(HttpServletRequest request, HttpServletResponse response, Supplier<CsrfToken> csrfToken);
@Override
default String resolveCsrfTokenValue(HttpServletRequest request, CsrfToken csrfToken) {
Assert.notNull(request, "request cannot be null");
Assert.notNull(csrfToken, "csrfToken cannot be null");
String actualToken = request.getHeader(csrfToken.getHeaderName());
if (actualToken == null) {
actualToken = request.getParameter(csrfToken.getParameterName());
}
return actualToken;
}
}
| 2,145 | 35.372881 | 102 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/CookieCsrfTokenRepository.java | /*
* Copyright 2012-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.csrf;
import java.util.UUID;
import java.util.function.Consumer;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils;
/**
* A {@link CsrfTokenRepository} that persists the CSRF token in a cookie named
* "XSRF-TOKEN" and reads from the header "X-XSRF-TOKEN" following the conventions of
* AngularJS. When using with AngularJS be sure to use {@link #withHttpOnlyFalse()}.
*
* @author Rob Winch
* @author Steve Riesenberg
* @author Alex Montoya
* @since 4.1
*/
public final class CookieCsrfTokenRepository implements CsrfTokenRepository {
static final String DEFAULT_CSRF_COOKIE_NAME = "XSRF-TOKEN";
static final String DEFAULT_CSRF_PARAMETER_NAME = "_csrf";
static final String DEFAULT_CSRF_HEADER_NAME = "X-XSRF-TOKEN";
private static final String CSRF_TOKEN_REMOVED_ATTRIBUTE_NAME = CookieCsrfTokenRepository.class.getName()
.concat(".REMOVED");
private String parameterName = DEFAULT_CSRF_PARAMETER_NAME;
private String headerName = DEFAULT_CSRF_HEADER_NAME;
private String cookieName = DEFAULT_CSRF_COOKIE_NAME;
private boolean cookieHttpOnly = true;
private String cookiePath;
private String cookieDomain;
private Boolean secure;
private int cookieMaxAge = -1;
private Consumer<ResponseCookie.ResponseCookieBuilder> cookieCustomizer = (builder) -> {
};
/**
* Add a {@link Consumer} for a {@code ResponseCookieBuilder} that will be invoked for
* each cookie being built, just before the call to {@code build()}.
* @param cookieCustomizer consumer for a cookie builder
* @since 6.1
*/
public void setCookieCustomizer(Consumer<ResponseCookie.ResponseCookieBuilder> cookieCustomizer) {
Assert.notNull(cookieCustomizer, "cookieCustomizer must not be null");
this.cookieCustomizer = cookieCustomizer;
}
@Override
public CsrfToken generateToken(HttpServletRequest request) {
return new DefaultCsrfToken(this.headerName, this.parameterName, createNewToken());
}
@Override
public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
String tokenValue = (token != null) ? token.getToken() : "";
ResponseCookie.ResponseCookieBuilder cookieBuilder = ResponseCookie.from(this.cookieName, tokenValue)
.secure((this.secure != null) ? this.secure : request.isSecure())
.path(StringUtils.hasLength(this.cookiePath) ? this.cookiePath : this.getRequestContext(request))
.maxAge((token != null) ? this.cookieMaxAge : 0).httpOnly(this.cookieHttpOnly)
.domain(this.cookieDomain);
this.cookieCustomizer.accept(cookieBuilder);
response.addHeader(HttpHeaders.SET_COOKIE, cookieBuilder.build().toString());
// Set request attribute to signal that response has blank cookie value,
// which allows loadToken to return null when token has been removed
if (!StringUtils.hasLength(tokenValue)) {
request.setAttribute(CSRF_TOKEN_REMOVED_ATTRIBUTE_NAME, Boolean.TRUE);
}
else {
request.removeAttribute(CSRF_TOKEN_REMOVED_ATTRIBUTE_NAME);
}
}
@Override
public CsrfToken loadToken(HttpServletRequest request) {
// Return null when token has been removed during the current request
// which allows loadDeferredToken to re-generate the token
if (Boolean.TRUE.equals(request.getAttribute(CSRF_TOKEN_REMOVED_ATTRIBUTE_NAME))) {
return null;
}
Cookie cookie = WebUtils.getCookie(request, this.cookieName);
if (cookie == null) {
return null;
}
String token = cookie.getValue();
if (!StringUtils.hasLength(token)) {
return null;
}
return new DefaultCsrfToken(this.headerName, this.parameterName, token);
}
/**
* Sets the name of the HTTP request parameter that should be used to provide a token.
* @param parameterName the name of the HTTP request parameter that should be used to
* provide a token
*/
public void setParameterName(String parameterName) {
Assert.notNull(parameterName, "parameterName cannot be null");
this.parameterName = parameterName;
}
/**
* Sets the name of the HTTP header that should be used to provide the token.
* @param headerName the name of the HTTP header that should be used to provide the
* token
*/
public void setHeaderName(String headerName) {
Assert.notNull(headerName, "headerName cannot be null");
this.headerName = headerName;
}
/**
* Sets the name of the cookie that the expected CSRF token is saved to and read from.
* @param cookieName the name of the cookie that the expected CSRF token is saved to
* and read from
*/
public void setCookieName(String cookieName) {
Assert.notNull(cookieName, "cookieName cannot be null");
this.cookieName = cookieName;
}
/**
* @deprecated Use {@link #setCookieCustomizer(Consumer)} instead.
*/
@Deprecated(since = "6.1")
public void setCookieHttpOnly(boolean cookieHttpOnly) {
this.cookieHttpOnly = cookieHttpOnly;
}
private String getRequestContext(HttpServletRequest request) {
String contextPath = request.getContextPath();
return (contextPath.length() > 0) ? contextPath : "/";
}
/**
* Factory method to conveniently create an instance that creates cookies where
* {@link Cookie#isHttpOnly()} is set to false.
* @return an instance of CookieCsrfTokenRepository that creates cookies where
* {@link Cookie#isHttpOnly()} is set to false.
*/
public static CookieCsrfTokenRepository withHttpOnlyFalse() {
CookieCsrfTokenRepository result = new CookieCsrfTokenRepository();
result.setCookieCustomizer((cookie) -> cookie.httpOnly(false));
return result;
}
private String createNewToken() {
return UUID.randomUUID().toString();
}
/**
* Set the path that the Cookie will be created with. This will override the default
* functionality which uses the request context as the path.
* @param path the path to use
*/
public void setCookiePath(String path) {
this.cookiePath = path;
}
/**
* Get the path that the CSRF cookie will be set to.
* @return the path to be used.
*/
public String getCookiePath() {
return this.cookiePath;
}
/**
* @since 5.2
* @deprecated Use {@link #setCookieCustomizer(Consumer)} instead.
*/
@Deprecated(since = "6.1")
public void setCookieDomain(String cookieDomain) {
this.cookieDomain = cookieDomain;
}
/**
* @since 5.4
* @deprecated Use {@link #setCookieCustomizer(Consumer)} instead.
*/
@Deprecated(since = "6.1")
public void setSecure(Boolean secure) {
this.secure = secure;
}
/**
* @since 5.5
* @deprecated Use {@link #setCookieCustomizer(Consumer)} instead.
*/
@Deprecated(since = "6.1")
public void setCookieMaxAge(int cookieMaxAge) {
Assert.isTrue(cookieMaxAge != 0, "cookieMaxAge cannot be zero");
this.cookieMaxAge = cookieMaxAge;
}
}
| 7,617 | 31.417021 | 106 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/CsrfAuthenticationStrategy.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.csrf;
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.Authentication;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.util.Assert;
/**
* {@link CsrfAuthenticationStrategy} is in charge of removing the {@link CsrfToken} upon
* authenticating. A new {@link CsrfToken} will then be generated by the framework upon
* the next request.
*
* @author Rob Winch
* @author Steve Riesenberg
* @since 3.2
*/
public final class CsrfAuthenticationStrategy implements SessionAuthenticationStrategy {
private final Log logger = LogFactory.getLog(getClass());
private final CsrfTokenRepository tokenRepository;
private CsrfTokenRequestHandler requestHandler = new XorCsrfTokenRequestAttributeHandler();
/**
* Creates a new instance
* @param tokenRepository the {@link CsrfTokenRepository} to use
*/
public CsrfAuthenticationStrategy(CsrfTokenRepository tokenRepository) {
Assert.notNull(tokenRepository, "tokenRepository cannot be null");
this.tokenRepository = tokenRepository;
}
/**
* Specify a {@link CsrfTokenRequestHandler} to use for making the {@code CsrfToken}
* available as a request attribute.
* @param requestHandler the {@link CsrfTokenRequestHandler} to use
*/
public void setRequestHandler(CsrfTokenRequestHandler requestHandler) {
Assert.notNull(requestHandler, "requestHandler cannot be null");
this.requestHandler = requestHandler;
}
@Override
public void onAuthentication(Authentication authentication, HttpServletRequest request,
HttpServletResponse response) throws SessionAuthenticationException {
boolean containsToken = this.tokenRepository.loadToken(request) != null;
if (containsToken) {
this.tokenRepository.saveToken(null, request, response);
DeferredCsrfToken deferredCsrfToken = this.tokenRepository.loadDeferredToken(request, response);
this.requestHandler.handle(request, response, deferredCsrfToken::get);
this.logger.debug("Replaced CSRF Token");
}
}
}
| 2,950 | 36.833333 | 99 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/LazyCsrfTokenRepository.java | /*
* Copyright 2012-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.csrf;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.Assert;
/**
* A {@link CsrfTokenRepository} that delays saving new {@link CsrfToken} until the
* attributes of the {@link CsrfToken} that were generated are accessed.
*
* @author Rob Winch
* @since 4.1
* @deprecated Use
* {@link CsrfTokenRepository#loadDeferredToken(HttpServletRequest, HttpServletResponse)}
* which returns a {@link DeferredCsrfToken}
*/
@Deprecated
public final class LazyCsrfTokenRepository implements CsrfTokenRepository {
/**
* The {@link HttpServletRequest} attribute name that the {@link HttpServletResponse}
* must be on.
*/
private static final String HTTP_RESPONSE_ATTR = HttpServletResponse.class.getName();
private final CsrfTokenRepository delegate;
private boolean deferLoadToken;
/**
* Creates a new instance
* @param delegate the {@link CsrfTokenRepository} to use. Cannot be null
* @throws IllegalArgumentException if delegate is null.
*/
public LazyCsrfTokenRepository(CsrfTokenRepository delegate) {
Assert.notNull(delegate, "delegate cannot be null");
this.delegate = delegate;
}
/**
* Determines if {@link #loadToken(HttpServletRequest)} should be lazily loaded.
* @param deferLoadToken true if should lazily load
* {@link #loadToken(HttpServletRequest)}. Default false.
*/
public void setDeferLoadToken(boolean deferLoadToken) {
this.deferLoadToken = deferLoadToken;
}
/**
* Generates a new token
* @param request the {@link HttpServletRequest} to use. The
* {@link HttpServletRequest} must have the {@link HttpServletResponse} as an
* attribute with the name of <code>HttpServletResponse.class.getName()</code>
*/
@Override
public CsrfToken generateToken(HttpServletRequest request) {
return wrap(request, this.delegate.generateToken(request));
}
/**
* Does nothing if the {@link CsrfToken} is not null. Saving is done only when the
* {@link CsrfToken#getToken()} is accessed from
* {@link #generateToken(HttpServletRequest)}. If it is null, then the save is
* performed immediately.
*/
@Override
public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
if (token == null) {
this.delegate.saveToken(token, request, response);
}
}
/**
* Delegates to the injected {@link CsrfTokenRepository}
*/
@Override
public CsrfToken loadToken(HttpServletRequest request) {
if (this.deferLoadToken) {
return new LazyLoadCsrfToken(request, this.delegate);
}
return this.delegate.loadToken(request);
}
private CsrfToken wrap(HttpServletRequest request, CsrfToken token) {
HttpServletResponse response = getResponse(request);
return new SaveOnAccessCsrfToken(this.delegate, request, response, token);
}
private HttpServletResponse getResponse(HttpServletRequest request) {
HttpServletResponse response = (HttpServletResponse) request.getAttribute(HTTP_RESPONSE_ATTR);
Assert.notNull(response, () -> "The HttpServletRequest attribute must contain an HttpServletResponse "
+ "for the attribute " + HTTP_RESPONSE_ATTR);
return response;
}
private final class LazyLoadCsrfToken implements CsrfToken {
private final HttpServletRequest request;
private final CsrfTokenRepository tokenRepository;
private CsrfToken token;
private LazyLoadCsrfToken(HttpServletRequest request, CsrfTokenRepository tokenRepository) {
this.request = request;
this.tokenRepository = tokenRepository;
}
private CsrfToken getDelegate() {
if (this.token != null) {
return this.token;
}
// load from the delegate repository
this.token = LazyCsrfTokenRepository.this.delegate.loadToken(this.request);
if (this.token == null) {
// return a generated token that is lazily saved since
// LazyCsrfTokenRepository#loadToken always returns a value
this.token = generateToken(this.request);
}
return this.token;
}
@Override
public String getHeaderName() {
return getDelegate().getHeaderName();
}
@Override
public String getParameterName() {
return getDelegate().getParameterName();
}
@Override
public String getToken() {
return getDelegate().getToken();
}
@Override
public String toString() {
return "LazyLoadCsrfToken{" + "token=" + this.token + '}';
}
}
private static final class SaveOnAccessCsrfToken implements CsrfToken {
private transient CsrfTokenRepository tokenRepository;
private transient HttpServletRequest request;
private transient HttpServletResponse response;
private final CsrfToken delegate;
SaveOnAccessCsrfToken(CsrfTokenRepository tokenRepository, HttpServletRequest request,
HttpServletResponse response, CsrfToken delegate) {
this.tokenRepository = tokenRepository;
this.request = request;
this.response = response;
this.delegate = delegate;
}
@Override
public String getHeaderName() {
return this.delegate.getHeaderName();
}
@Override
public String getParameterName() {
return this.delegate.getParameterName();
}
@Override
public String getToken() {
saveTokenIfNecessary();
return this.delegate.getToken();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
SaveOnAccessCsrfToken other = (SaveOnAccessCsrfToken) obj;
if (this.delegate == null) {
if (other.delegate != null) {
return false;
}
}
else if (!this.delegate.equals(other.delegate)) {
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.delegate == null) ? 0 : this.delegate.hashCode());
return result;
}
@Override
public String toString() {
return "SaveOnAccessCsrfToken [delegate=" + this.delegate + "]";
}
private void saveTokenIfNecessary() {
if (this.tokenRepository == null) {
return;
}
synchronized (this) {
if (this.tokenRepository != null) {
this.tokenRepository.saveToken(this.delegate, this.request, this.response);
this.tokenRepository = null;
this.request = null;
this.response = null;
}
}
}
}
}
| 6,948 | 27.247967 | 104 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/DefaultCsrfToken.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.csrf;
import org.springframework.util.Assert;
/**
* A CSRF token that is used to protect against CSRF attacks.
*
* @author Rob Winch
* @since 3.2
*/
@SuppressWarnings("serial")
public final class DefaultCsrfToken implements CsrfToken {
private final String token;
private final String parameterName;
private final String headerName;
/**
* Creates a new instance
* @param headerName the HTTP header name to use
* @param parameterName the HTTP parameter name to use
* @param token the value of the token (i.e. expected value of the HTTP parameter of
* parametername).
*/
public DefaultCsrfToken(String headerName, String parameterName, String token) {
Assert.hasLength(headerName, "headerName cannot be null or empty");
Assert.hasLength(parameterName, "parameterName cannot be null or empty");
Assert.hasLength(token, "token cannot be null or empty");
this.headerName = headerName;
this.parameterName = parameterName;
this.token = token;
}
@Override
public String getHeaderName() {
return this.headerName;
}
@Override
public String getParameterName() {
return this.parameterName;
}
@Override
public String getToken() {
return this.token;
}
}
| 1,864 | 26.426471 | 85 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/CsrfLogoutHandler.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.csrf;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.Assert;
/**
* {@link CsrfLogoutHandler} is in charge of removing the {@link CsrfToken} upon logout. A
* new {@link CsrfToken} will then be generated by the framework upon the next request.
*
* @author Rob Winch
* @since 3.2
*/
public final class CsrfLogoutHandler implements LogoutHandler {
private final CsrfTokenRepository csrfTokenRepository;
/**
* Creates a new instance
* @param csrfTokenRepository the {@link CsrfTokenRepository} to use
*/
public CsrfLogoutHandler(CsrfTokenRepository csrfTokenRepository) {
Assert.notNull(csrfTokenRepository, "csrfTokenRepository cannot be null");
this.csrfTokenRepository = csrfTokenRepository;
}
/**
* Clears the {@link CsrfToken}
*
* @see org.springframework.security.web.authentication.logout.LogoutHandler#logout(jakarta.servlet.http.HttpServletRequest,
* jakarta.servlet.http.HttpServletResponse,
* org.springframework.security.core.Authentication)
*/
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
this.csrfTokenRepository.saveToken(null, request, response);
}
}
| 2,062 | 33.966102 | 125 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/RepositoryDeferredCsrfToken.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.csrf;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author Rob Winch
* @author Steve Riesenberg
* @since 5.8
*/
final class RepositoryDeferredCsrfToken implements DeferredCsrfToken {
private final CsrfTokenRepository csrfTokenRepository;
private final HttpServletRequest request;
private final HttpServletResponse response;
private CsrfToken csrfToken;
private boolean missingToken;
RepositoryDeferredCsrfToken(CsrfTokenRepository csrfTokenRepository, HttpServletRequest request,
HttpServletResponse response) {
this.csrfTokenRepository = csrfTokenRepository;
this.request = request;
this.response = response;
}
@Override
public CsrfToken get() {
init();
return this.csrfToken;
}
@Override
public boolean isGenerated() {
init();
return this.missingToken;
}
private void init() {
if (this.csrfToken != null) {
return;
}
this.csrfToken = this.csrfTokenRepository.loadToken(this.request);
this.missingToken = (this.csrfToken == null);
if (this.missingToken) {
this.csrfToken = this.csrfTokenRepository.generateToken(this.request);
this.csrfTokenRepository.saveToken(this.csrfToken, this.request, this.response);
}
}
}
| 1,907 | 25.5 | 97 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/CsrfFilter.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.csrf;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashSet;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
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.access.AccessDeniedException;
import org.springframework.security.crypto.codec.Utf8;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* <p>
* Applies
* <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)" >CSRF</a>
* protection using a synchronizer token pattern. Developers are required to ensure that
* {@link CsrfFilter} is invoked for any request that allows state to change. Typically
* this just means that they should ensure their web application follows proper REST
* semantics (i.e. do not change state with the HTTP methods GET, HEAD, TRACE, OPTIONS).
* </p>
*
* <p>
* Typically the {@link CsrfTokenRepository} implementation chooses to store the
* {@link CsrfToken} in {@link HttpSession} with {@link HttpSessionCsrfTokenRepository}.
* This is preferred to storing the token in a cookie which can be modified by a client
* application.
* </p>
*
* @author Rob Winch
* @author Steve Riesenberg
* @since 3.2
*/
public final class CsrfFilter extends OncePerRequestFilter {
/**
* The default {@link RequestMatcher} that indicates if CSRF protection is required or
* not. The default is to ignore GET, HEAD, TRACE, OPTIONS and process all other
* requests.
*/
public static final RequestMatcher DEFAULT_CSRF_MATCHER = new DefaultRequiresCsrfMatcher();
/**
* The attribute name to use when marking a given request as one that should not be
* filtered.
* <p>
* To use, set the attribute on your {@link HttpServletRequest}: <pre>
* CsrfFilter.skipRequest(request);
* </pre>
*/
private static final String SHOULD_NOT_FILTER = "SHOULD_NOT_FILTER" + CsrfFilter.class.getName();
private final Log logger = LogFactory.getLog(getClass());
private final CsrfTokenRepository tokenRepository;
private RequestMatcher requireCsrfProtectionMatcher = DEFAULT_CSRF_MATCHER;
private AccessDeniedHandler accessDeniedHandler = new AccessDeniedHandlerImpl();
private CsrfTokenRequestHandler requestHandler = new XorCsrfTokenRequestAttributeHandler();
/**
* Creates a new instance.
* @param tokenRepository the {@link CsrfTokenRepository} to use
*/
public CsrfFilter(CsrfTokenRepository tokenRepository) {
Assert.notNull(tokenRepository, "tokenRepository cannot be null");
this.tokenRepository = tokenRepository;
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
return Boolean.TRUE.equals(request.getAttribute(SHOULD_NOT_FILTER));
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
DeferredCsrfToken deferredCsrfToken = this.tokenRepository.loadDeferredToken(request, response);
request.setAttribute(DeferredCsrfToken.class.getName(), deferredCsrfToken);
this.requestHandler.handle(request, response, deferredCsrfToken::get);
if (!this.requireCsrfProtectionMatcher.matches(request)) {
if (this.logger.isTraceEnabled()) {
this.logger.trace("Did not protect against CSRF since request did not match "
+ this.requireCsrfProtectionMatcher);
}
filterChain.doFilter(request, response);
return;
}
CsrfToken csrfToken = deferredCsrfToken.get();
String actualToken = this.requestHandler.resolveCsrfTokenValue(request, csrfToken);
if (!equalsConstantTime(csrfToken.getToken(), actualToken)) {
boolean missingToken = deferredCsrfToken.isGenerated();
this.logger.debug(
LogMessage.of(() -> "Invalid CSRF token found for " + UrlUtils.buildFullRequestUrl(request)));
AccessDeniedException exception = (!missingToken) ? new InvalidCsrfTokenException(csrfToken, actualToken)
: new MissingCsrfTokenException(actualToken);
this.accessDeniedHandler.handle(request, response, exception);
return;
}
filterChain.doFilter(request, response);
}
public static void skipRequest(HttpServletRequest request) {
request.setAttribute(SHOULD_NOT_FILTER, Boolean.TRUE);
}
/**
* Specifies a {@link RequestMatcher} that is used to determine if CSRF protection
* should be applied. If the {@link RequestMatcher} returns true for a given request,
* then CSRF protection is applied.
*
* <p>
* The default is to apply CSRF protection for any HTTP method other than GET, HEAD,
* TRACE, OPTIONS.
* </p>
* @param requireCsrfProtectionMatcher the {@link RequestMatcher} used to determine if
* CSRF protection should be applied.
*/
public void setRequireCsrfProtectionMatcher(RequestMatcher requireCsrfProtectionMatcher) {
Assert.notNull(requireCsrfProtectionMatcher, "requireCsrfProtectionMatcher cannot be null");
this.requireCsrfProtectionMatcher = requireCsrfProtectionMatcher;
}
/**
* Specifies a {@link AccessDeniedHandler} that should be used when CSRF protection
* fails.
*
* <p>
* The default is to use AccessDeniedHandlerImpl with no arguments.
* </p>
* @param accessDeniedHandler the {@link AccessDeniedHandler} to use
*/
public void setAccessDeniedHandler(AccessDeniedHandler accessDeniedHandler) {
Assert.notNull(accessDeniedHandler, "accessDeniedHandler cannot be null");
this.accessDeniedHandler = accessDeniedHandler;
}
/**
* Specifies a {@link CsrfTokenRequestHandler} that is used to make the
* {@link CsrfToken} available as a request attribute.
*
* <p>
* The default is {@link XorCsrfTokenRequestAttributeHandler}.
* </p>
* @param requestHandler the {@link CsrfTokenRequestHandler} to use
* @since 5.8
*/
public void setRequestHandler(CsrfTokenRequestHandler requestHandler) {
Assert.notNull(requestHandler, "requestHandler cannot be null");
this.requestHandler = requestHandler;
}
/**
* Constant time comparison to prevent against timing attacks.
* @param expected
* @param actual
* @return
*/
private static boolean equalsConstantTime(String expected, String actual) {
if (expected == actual) {
return true;
}
if (expected == null || actual == null) {
return false;
}
// Encode after ensure that the string is not null
byte[] expectedBytes = Utf8.encode(expected);
byte[] actualBytes = Utf8.encode(actual);
return MessageDigest.isEqual(expectedBytes, actualBytes);
}
private static final class DefaultRequiresCsrfMatcher implements RequestMatcher {
private final HashSet<String> allowedMethods = new HashSet<>(Arrays.asList("GET", "HEAD", "TRACE", "OPTIONS"));
@Override
public boolean matches(HttpServletRequest request) {
return !this.allowedMethods.contains(request.getMethod());
}
@Override
public String toString() {
return "CsrfNotRequired " + this.allowedMethods;
}
}
}
| 8,121 | 35.918182 | 115 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/CsrfTokenRepository.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.csrf;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
/**
* An API to allow changing the method in which the expected {@link CsrfToken} is
* associated to the {@link HttpServletRequest}. For example, it may be stored in
* {@link HttpSession}.
*
* @author Rob Winch
* @author Steve Riesenberg
* @since 3.2
* @see HttpSessionCsrfTokenRepository
*/
public interface CsrfTokenRepository {
/**
* Generates a {@link CsrfToken}
* @param request the {@link HttpServletRequest} to use
* @return the {@link CsrfToken} that was generated. Cannot be null.
*/
CsrfToken generateToken(HttpServletRequest request);
/**
* Saves the {@link CsrfToken} using the {@link HttpServletRequest} and
* {@link HttpServletResponse}. If the {@link CsrfToken} is null, it is the same as
* deleting it.
* @param token the {@link CsrfToken} to save or null to delete
* @param request the {@link HttpServletRequest} to use
* @param response the {@link HttpServletResponse} to use
*/
void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response);
/**
* Loads the expected {@link CsrfToken} from the {@link HttpServletRequest}
* @param request the {@link HttpServletRequest} to use
* @return the {@link CsrfToken} or null if none exists
*/
CsrfToken loadToken(HttpServletRequest request);
/**
* Defers loading the {@link CsrfToken} using the {@link HttpServletRequest} and
* {@link HttpServletResponse} until it is needed by the application.
* <p>
* The returned {@link DeferredCsrfToken} is cached to allow subsequent calls to
* {@link DeferredCsrfToken#get()} to return the same {@link CsrfToken} without the
* cost of loading or generating the token again.
* @param request the {@link HttpServletRequest} to use
* @param response the {@link HttpServletResponse} to use
* @return a {@link DeferredCsrfToken} that will load the {@link CsrfToken}
* @since 5.8
*/
default DeferredCsrfToken loadDeferredToken(HttpServletRequest request, HttpServletResponse response) {
return new RepositoryDeferredCsrfToken(this, request, response);
}
}
| 2,863 | 36.684211 | 104 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/CsrfTokenRequestAttributeHandler.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.csrf;
import java.util.function.Supplier;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.Assert;
/**
* An implementation of the {@link CsrfTokenRequestHandler} interface that is capable of
* making the {@link CsrfToken} available as a request attribute and resolving the token
* value as either a header or parameter value of the request.
*
* @author Steve Riesenberg
* @since 5.8
*/
public class CsrfTokenRequestAttributeHandler implements CsrfTokenRequestHandler {
private String csrfRequestAttributeName = "_csrf";
/**
* The {@link CsrfToken} is available as a request attribute named
* {@code CsrfToken.class.getName()}. By default, an additional request attribute that
* is the same as {@link CsrfToken#getParameterName()} is set. This attribute allows
* overriding the additional attribute.
* @param csrfRequestAttributeName the name of an additional request attribute with
* the value of the CsrfToken. Default is {@link CsrfToken#getParameterName()}
*/
public final void setCsrfRequestAttributeName(String csrfRequestAttributeName) {
this.csrfRequestAttributeName = csrfRequestAttributeName;
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
Supplier<CsrfToken> deferredCsrfToken) {
Assert.notNull(request, "request cannot be null");
Assert.notNull(response, "response cannot be null");
Assert.notNull(deferredCsrfToken, "deferredCsrfToken cannot be null");
request.setAttribute(HttpServletResponse.class.getName(), response);
CsrfToken csrfToken = new SupplierCsrfToken(deferredCsrfToken);
request.setAttribute(CsrfToken.class.getName(), csrfToken);
String csrfAttrName = (this.csrfRequestAttributeName != null) ? this.csrfRequestAttributeName
: csrfToken.getParameterName();
request.setAttribute(csrfAttrName, csrfToken);
}
private static final class SupplierCsrfToken implements CsrfToken {
private final Supplier<CsrfToken> csrfTokenSupplier;
private SupplierCsrfToken(Supplier<CsrfToken> csrfTokenSupplier) {
this.csrfTokenSupplier = csrfTokenSupplier;
}
@Override
public String getHeaderName() {
return getDelegate().getHeaderName();
}
@Override
public String getParameterName() {
return getDelegate().getParameterName();
}
@Override
public String getToken() {
return getDelegate().getToken();
}
private CsrfToken getDelegate() {
CsrfToken delegate = this.csrfTokenSupplier.get();
if (delegate == null) {
throw new IllegalStateException("csrfTokenSupplier returned null delegate");
}
return delegate;
}
}
}
| 3,334 | 32.686869 | 95 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/MissingCsrfTokenException.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.csrf;
/**
* Thrown when no expected {@link CsrfToken} is found but is required.
*
* @author Rob Winch
* @since 3.2
*/
@SuppressWarnings("serial")
public class MissingCsrfTokenException extends CsrfException {
public MissingCsrfTokenException(String actualToken) {
super("Could not verify the provided CSRF token because no token was found to compare.");
}
}
| 1,034 | 30.363636 | 91 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/CsrfTokenRequestResolver.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.csrf;
import jakarta.servlet.http.HttpServletRequest;
/**
* Implementations of this interface are capable of resolving the token value of a
* {@link CsrfToken} from the provided {@code HttpServletRequest}. Used by the
* {@link CsrfFilter}.
*
* @author Steve Riesenberg
* @since 5.8
* @see CsrfTokenRequestAttributeHandler
*/
@FunctionalInterface
public interface CsrfTokenRequestResolver {
/**
* Returns the token value resolved from the provided {@code HttpServletRequest} and
* {@link CsrfToken} or {@code null} if not available.
* @param request the {@code HttpServletRequest} being processed
* @param csrfToken the {@link CsrfToken} created by the {@link CsrfTokenRepository}
* @return the token value resolved from the request
*/
String resolveCsrfTokenValue(HttpServletRequest request, CsrfToken csrfToken);
}
| 1,506 | 34.046512 | 85 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/CsrfException.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.csrf;
import org.springframework.security.access.AccessDeniedException;
/**
* Thrown when an invalid or missing {@link CsrfToken} is found in the HttpServletRequest
*
* @author Rob Winch
* @since 3.2
*/
@SuppressWarnings("serial")
public class CsrfException extends AccessDeniedException {
public CsrfException(String message) {
super(message);
}
}
| 1,026 | 28.342857 | 89 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/InvalidCsrfTokenException.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.csrf;
import jakarta.servlet.http.HttpServletRequest;
/**
* Thrown when an expected {@link CsrfToken} exists, but it does not match the value
* present on the {@link HttpServletRequest}
*
* @author Rob Winch
* @since 3.2
*/
@SuppressWarnings("serial")
public class InvalidCsrfTokenException extends CsrfException {
/**
* @param expectedAccessToken
* @param actualAccessToken
*/
public InvalidCsrfTokenException(CsrfToken expectedAccessToken, String actualAccessToken) {
super("Invalid CSRF Token '" + actualAccessToken + "' was found on the request parameter '"
+ expectedAccessToken.getParameterName() + "' or header '" + expectedAccessToken.getHeaderName()
+ "'.");
}
}
| 1,365 | 31.52381 | 100 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/DeferredCsrfToken.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.csrf;
/**
* An interface that allows delayed access to a {@link CsrfToken} that may be generated.
*
* @author Rob Winch
* @author Steve Riesenberg
* @since 5.8
*/
public interface DeferredCsrfToken {
/**
* Gets the {@link CsrfToken}
* @return a non-null {@link CsrfToken}
*/
CsrfToken get();
/**
* Returns true if {@link #get()} refers to a generated {@link CsrfToken} or false if
* it already existed.
* @return true if {@link #get()} refers to a generated {@link CsrfToken} or false if
* it already existed.
*/
boolean isGenerated();
}
| 1,232 | 27.674419 | 88 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/CsrfToken.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.csrf;
import java.io.Serializable;
/**
* Provides the information about an expected CSRF token.
*
* @author Rob Winch
* @since 3.2
* @see DefaultCsrfToken
*/
public interface CsrfToken extends Serializable {
/**
* Gets the HTTP header that the CSRF is populated on the response and can be placed
* on requests instead of the parameter. Cannot be null.
* @return the HTTP header that the CSRF is populated on the response and can be
* placed on requests instead of the parameter
*/
String getHeaderName();
/**
* Gets the HTTP parameter name that should contain the token. Cannot be null.
* @return the HTTP parameter name that should contain the token.
*/
String getParameterName();
/**
* Gets the token value. Cannot be null.
* @return the token value
*/
String getToken();
}
| 1,480 | 28.039216 | 85 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/HttpSessionCsrfTokenRepository.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.csrf;
import java.util.UUID;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.util.Assert;
/**
* A {@link CsrfTokenRepository} that stores the {@link CsrfToken} in the
* {@link HttpSession}.
*
* @author Rob Winch
* @since 3.2
*/
public final class HttpSessionCsrfTokenRepository implements CsrfTokenRepository {
private static final String DEFAULT_CSRF_PARAMETER_NAME = "_csrf";
private static final String DEFAULT_CSRF_HEADER_NAME = "X-CSRF-TOKEN";
private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = HttpSessionCsrfTokenRepository.class.getName()
.concat(".CSRF_TOKEN");
private String parameterName = DEFAULT_CSRF_PARAMETER_NAME;
private String headerName = DEFAULT_CSRF_HEADER_NAME;
private String sessionAttributeName = DEFAULT_CSRF_TOKEN_ATTR_NAME;
@Override
public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
if (token == null) {
HttpSession session = request.getSession(false);
if (session != null) {
session.removeAttribute(this.sessionAttributeName);
}
}
else {
HttpSession session = request.getSession();
session.setAttribute(this.sessionAttributeName, token);
}
}
@Override
public CsrfToken loadToken(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return null;
}
return (CsrfToken) session.getAttribute(this.sessionAttributeName);
}
@Override
public CsrfToken generateToken(HttpServletRequest request) {
return new DefaultCsrfToken(this.headerName, this.parameterName, createNewToken());
}
/**
* Sets the {@link HttpServletRequest} parameter name that the {@link CsrfToken} is
* expected to appear on
* @param parameterName the new parameter name to use
*/
public void setParameterName(String parameterName) {
Assert.hasLength(parameterName, "parameterName cannot be null or empty");
this.parameterName = parameterName;
}
/**
* Sets the header name that the {@link CsrfToken} is expected to appear on and the
* header that the response will contain the {@link CsrfToken}.
* @param headerName the new header name to use
*/
public void setHeaderName(String headerName) {
Assert.hasLength(headerName, "headerName cannot be null or empty");
this.headerName = headerName;
}
/**
* Sets the {@link HttpSession} attribute name that the {@link CsrfToken} is stored in
* @param sessionAttributeName the new attribute name to use
*/
public void setSessionAttributeName(String sessionAttributeName) {
Assert.hasLength(sessionAttributeName, "sessionAttributename cannot be null or empty");
this.sessionAttributeName = sessionAttributeName;
}
private String createNewToken() {
return UUID.randomUUID().toString();
}
}
| 3,535 | 30.855856 | 106 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/csrf/XorCsrfTokenRequestAttributeHandler.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.csrf;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.function.Supplier;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.crypto.codec.Utf8;
import org.springframework.util.Assert;
/**
* An implementation of the {@link CsrfTokenRequestHandler} interface that is capable of
* masking the value of the {@link CsrfToken} on each request and resolving the raw token
* value from the masked value as either a header or parameter value of the request.
*
* @author Steve Riesenberg
* @since 5.8
*/
public final class XorCsrfTokenRequestAttributeHandler extends CsrfTokenRequestAttributeHandler {
private SecureRandom secureRandom = new SecureRandom();
/**
* Specifies the {@code SecureRandom} used to generate random bytes that are used to
* mask the value of the {@link CsrfToken} on each request.
* @param secureRandom the {@code SecureRandom} to use to generate random bytes
*/
public void setSecureRandom(SecureRandom secureRandom) {
Assert.notNull(secureRandom, "secureRandom cannot be null");
this.secureRandom = secureRandom;
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
Supplier<CsrfToken> deferredCsrfToken) {
Assert.notNull(request, "request cannot be null");
Assert.notNull(response, "response cannot be null");
Assert.notNull(deferredCsrfToken, "deferredCsrfToken cannot be null");
Supplier<CsrfToken> updatedCsrfToken = deferCsrfTokenUpdate(deferredCsrfToken);
super.handle(request, response, updatedCsrfToken);
}
private Supplier<CsrfToken> deferCsrfTokenUpdate(Supplier<CsrfToken> csrfTokenSupplier) {
return new CachedCsrfTokenSupplier(() -> {
CsrfToken csrfToken = csrfTokenSupplier.get();
Assert.state(csrfToken != null, "csrfToken supplier returned null");
String updatedToken = createXoredCsrfToken(this.secureRandom, csrfToken.getToken());
return new DefaultCsrfToken(csrfToken.getHeaderName(), csrfToken.getParameterName(), updatedToken);
});
}
@Override
public String resolveCsrfTokenValue(HttpServletRequest request, CsrfToken csrfToken) {
String actualToken = super.resolveCsrfTokenValue(request, csrfToken);
return getTokenValue(actualToken, csrfToken.getToken());
}
private static String getTokenValue(String actualToken, String token) {
byte[] actualBytes;
try {
actualBytes = Base64.getUrlDecoder().decode(actualToken);
}
catch (Exception ex) {
return null;
}
byte[] tokenBytes = Utf8.encode(token);
int tokenSize = tokenBytes.length;
if (actualBytes.length < tokenSize) {
return null;
}
// extract token and random bytes
int randomBytesSize = actualBytes.length - tokenSize;
byte[] xoredCsrf = new byte[tokenSize];
byte[] randomBytes = new byte[randomBytesSize];
System.arraycopy(actualBytes, 0, randomBytes, 0, randomBytesSize);
System.arraycopy(actualBytes, randomBytesSize, xoredCsrf, 0, tokenSize);
byte[] csrfBytes = xorCsrf(randomBytes, xoredCsrf);
return Utf8.decode(csrfBytes);
}
private static String createXoredCsrfToken(SecureRandom secureRandom, String token) {
byte[] tokenBytes = Utf8.encode(token);
byte[] randomBytes = new byte[tokenBytes.length];
secureRandom.nextBytes(randomBytes);
byte[] xoredBytes = xorCsrf(randomBytes, tokenBytes);
byte[] combinedBytes = new byte[tokenBytes.length + randomBytes.length];
System.arraycopy(randomBytes, 0, combinedBytes, 0, randomBytes.length);
System.arraycopy(xoredBytes, 0, combinedBytes, randomBytes.length, xoredBytes.length);
return Base64.getUrlEncoder().encodeToString(combinedBytes);
}
private static byte[] xorCsrf(byte[] randomBytes, byte[] csrfBytes) {
int len = Math.min(randomBytes.length, csrfBytes.length);
byte[] xoredCsrf = new byte[len];
System.arraycopy(csrfBytes, 0, xoredCsrf, 0, csrfBytes.length);
for (int i = 0; i < len; i++) {
xoredCsrf[i] ^= randomBytes[i];
}
return xoredCsrf;
}
private static final class CachedCsrfTokenSupplier implements Supplier<CsrfToken> {
private final Supplier<CsrfToken> delegate;
private CsrfToken csrfToken;
private CachedCsrfTokenSupplier(Supplier<CsrfToken> delegate) {
this.delegate = delegate;
}
@Override
public CsrfToken get() {
if (this.csrfToken == null) {
this.csrfToken = this.delegate.get();
}
return this.csrfToken;
}
}
}
| 5,090 | 33.632653 | 102 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/context/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.
*/
/**
* Classes which are responsible for maintaining the security context between HTTP
* requests.
*/
package org.springframework.security.web.context;
| 777 | 34.363636 | 82 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/context/HttpSessionSecurityContextRepository.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.context;
import java.util.function.Supplier;
import jakarta.servlet.AsyncContext;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
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.annotation.AnnotationUtils;
import org.springframework.core.log.LogMessage;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.Transient;
import org.springframework.security.core.context.DeferredSecurityContext;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.util.Assert;
import org.springframework.web.util.WebUtils;
/**
* A {@code SecurityContextRepository} implementation which stores the security context in
* the {@code HttpSession} between requests.
* <p>
* The {@code HttpSession} will be queried to retrieve the {@code SecurityContext} in the
* <tt>loadContext</tt> method (using the key {@link #SPRING_SECURITY_CONTEXT_KEY} by
* default). If a valid {@code SecurityContext} cannot be obtained from the
* {@code HttpSession} for whatever reason, a fresh {@code SecurityContext} will be
* created by calling by {@link SecurityContextHolder#createEmptyContext()} and this
* instance will be returned instead.
* <p>
* When <tt>saveContext</tt> is called, the context will be stored under the same key,
* provided
* <ol>
* <li>The value has changed</li>
* <li>The configured <tt>AuthenticationTrustResolver</tt> does not report that the
* contents represent an anonymous user</li>
* </ol>
* <p>
* With the standard configuration, no {@code HttpSession} will be created during
* <tt>loadContext</tt> if one does not already exist. When <tt>saveContext</tt> is called
* at the end of the web request, and no session exists, a new {@code HttpSession} will
* <b>only</b> be created if the supplied {@code SecurityContext} is not equal to an empty
* {@code SecurityContext} instance. This avoids needless <code>HttpSession</code>
* creation, but automates the storage of changes made to the context during the request.
* Note that if {@link SecurityContextPersistenceFilter} is configured to eagerly create
* sessions, then the session-minimisation logic applied here will not make any
* difference. If you are using eager session creation, then you should ensure that the
* <tt>allowSessionCreation</tt> property of this class is set to <tt>true</tt> (the
* default).
* <p>
* If for whatever reason no {@code HttpSession} should <b>ever</b> be created (for
* example, if Basic authentication is being used or similar clients that will never
* present the same {@code jsessionid}), then {@link #setAllowSessionCreation(boolean)
* allowSessionCreation} should be set to <code>false</code>. Only do this if you really
* need to conserve server memory and ensure all classes using the
* {@code SecurityContextHolder} are designed to have no persistence of the
* {@code SecurityContext} between web requests.
*
* @author Luke Taylor
* @since 3.0
*/
public class HttpSessionSecurityContextRepository implements SecurityContextRepository {
/**
* The default key under which the security context will be stored in the session.
*/
public static final String SPRING_SECURITY_CONTEXT_KEY = "SPRING_SECURITY_CONTEXT";
protected final Log logger = LogFactory.getLog(this.getClass());
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
/**
* SecurityContext instance used to check for equality with default (unauthenticated)
* content
*/
private Object contextObject = this.securityContextHolderStrategy.createEmptyContext();
private boolean allowSessionCreation = true;
private boolean disableUrlRewriting = false;
private String springSecurityContextKey = SPRING_SECURITY_CONTEXT_KEY;
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
/**
* Gets the security context for the current request (if available) and returns it.
* <p>
* If the session is null, the context object is null or the context object stored in
* the session is not an instance of {@code SecurityContext}, a new context object
* will be generated and returned.
*/
@Override
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
HttpServletRequest request = requestResponseHolder.getRequest();
HttpServletResponse response = requestResponseHolder.getResponse();
HttpSession httpSession = request.getSession(false);
SecurityContext context = readSecurityContextFromSession(httpSession);
if (context == null) {
context = generateNewContext();
if (this.logger.isTraceEnabled()) {
this.logger.trace(LogMessage.format("Created %s", context));
}
}
if (response != null) {
SaveToSessionResponseWrapper wrappedResponse = new SaveToSessionResponseWrapper(response, request,
httpSession != null, context);
wrappedResponse.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);
requestResponseHolder.setResponse(wrappedResponse);
requestResponseHolder.setRequest(new SaveToSessionRequestWrapper(request, wrappedResponse));
}
return context;
}
@Override
public DeferredSecurityContext loadDeferredContext(HttpServletRequest request) {
Supplier<SecurityContext> supplier = () -> readSecurityContextFromSession(request.getSession(false));
return new SupplierDeferredSecurityContext(supplier, this.securityContextHolderStrategy);
}
@Override
public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {
SaveContextOnUpdateOrErrorResponseWrapper responseWrapper = WebUtils.getNativeResponse(response,
SaveContextOnUpdateOrErrorResponseWrapper.class);
if (responseWrapper == null) {
saveContextInHttpSession(context, request);
return;
}
responseWrapper.saveContext(context);
}
private void saveContextInHttpSession(SecurityContext context, HttpServletRequest request) {
if (isTransient(context) || isTransient(context.getAuthentication())) {
return;
}
SecurityContext emptyContext = generateNewContext();
if (emptyContext.equals(context)) {
HttpSession session = request.getSession(false);
removeContextFromSession(context, session);
}
else {
boolean createSession = this.allowSessionCreation;
HttpSession session = request.getSession(createSession);
setContextInSession(context, session);
}
}
private void setContextInSession(SecurityContext context, HttpSession session) {
if (session != null) {
session.setAttribute(this.springSecurityContextKey, context);
if (this.logger.isDebugEnabled()) {
this.logger.debug(LogMessage.format("Stored %s to HttpSession [%s]", context, session));
}
}
}
private void removeContextFromSession(SecurityContext context, HttpSession session) {
if (session != null) {
session.removeAttribute(this.springSecurityContextKey);
if (this.logger.isDebugEnabled()) {
this.logger.debug(LogMessage.format("Removed %s from HttpSession [%s]", context, session));
}
}
}
@Override
public boolean containsContext(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return false;
}
return session.getAttribute(this.springSecurityContextKey) != null;
}
/**
* @param httpSession the session obtained from the request.
*/
private SecurityContext readSecurityContextFromSession(HttpSession httpSession) {
if (httpSession == null) {
this.logger.trace("No HttpSession currently exists");
return null;
}
// Session exists, so try to obtain a context from it.
Object contextFromSession = httpSession.getAttribute(this.springSecurityContextKey);
if (contextFromSession == null) {
if (this.logger.isTraceEnabled()) {
this.logger.trace(LogMessage.format("Did not find SecurityContext in HttpSession %s "
+ "using the SPRING_SECURITY_CONTEXT session attribute", httpSession.getId()));
}
return null;
}
// We now have the security context object from the session.
if (!(contextFromSession instanceof SecurityContext)) {
this.logger.warn(LogMessage.format(
"%s did not contain a SecurityContext but contained: '%s'; are you improperly "
+ "modifying the HttpSession directly (you should always use SecurityContextHolder) "
+ "or using the HttpSession attribute reserved for this class?",
this.springSecurityContextKey, contextFromSession));
return null;
}
if (this.logger.isTraceEnabled()) {
this.logger.trace(
LogMessage.format("Retrieved %s from %s", contextFromSession, this.springSecurityContextKey));
}
else if (this.logger.isDebugEnabled()) {
this.logger.debug(LogMessage.format("Retrieved %s", contextFromSession));
}
// Everything OK. The only non-null return from this method.
return (SecurityContext) contextFromSession;
}
/**
* By default, calls {@link SecurityContextHolder#createEmptyContext()} to obtain a
* new context (there should be no context present in the holder when this method is
* called). Using this approach the context creation strategy is decided by the
* {@link SecurityContextHolderStrategy} in use. The default implementations will
* return a new <tt>SecurityContextImpl</tt>.
* @return a new SecurityContext instance. Never null.
*/
protected SecurityContext generateNewContext() {
return this.securityContextHolderStrategy.createEmptyContext();
}
/**
* If set to true (the default), a session will be created (if required) to store the
* security context if it is determined that its contents are different from the
* default empty context value.
* <p>
* Note that setting this flag to false does not prevent this class from storing the
* security context. If your application (or another filter) creates a session, then
* the security context will still be stored for an authenticated user.
* @param allowSessionCreation
*/
public void setAllowSessionCreation(boolean allowSessionCreation) {
this.allowSessionCreation = allowSessionCreation;
}
/**
* Allows the use of session identifiers in URLs to be disabled. Off by default.
* @param disableUrlRewriting set to <tt>true</tt> to disable URL encoding methods in
* the response wrapper and prevent the use of <tt>jsessionid</tt> parameters.
*/
public void setDisableUrlRewriting(boolean disableUrlRewriting) {
this.disableUrlRewriting = disableUrlRewriting;
}
/**
* Allows the session attribute name to be customized for this repository instance.
* @param springSecurityContextKey the key under which the security context will be
* stored. Defaults to {@link #SPRING_SECURITY_CONTEXT_KEY}.
*/
public void setSpringSecurityContextKey(String springSecurityContextKey) {
Assert.hasText(springSecurityContextKey, "springSecurityContextKey cannot be empty");
this.springSecurityContextKey = springSecurityContextKey;
}
/**
* 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 strategy) {
this.securityContextHolderStrategy = strategy;
this.contextObject = this.securityContextHolderStrategy.createEmptyContext();
}
private boolean isTransient(Object object) {
if (object == null) {
return false;
}
return AnnotationUtils.getAnnotation(object.getClass(), Transient.class) != null;
}
/**
* Sets the {@link AuthenticationTrustResolver} to be used. The default is
* {@link AuthenticationTrustResolverImpl}.
* @param trustResolver the {@link AuthenticationTrustResolver} to use. Cannot be
* null.
*/
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
Assert.notNull(trustResolver, "trustResolver cannot be null");
this.trustResolver = trustResolver;
}
private static class SaveToSessionRequestWrapper extends HttpServletRequestWrapper {
private final SaveContextOnUpdateOrErrorResponseWrapper response;
SaveToSessionRequestWrapper(HttpServletRequest request, SaveContextOnUpdateOrErrorResponseWrapper response) {
super(request);
this.response = response;
}
@Override
public AsyncContext startAsync() {
this.response.disableSaveOnResponseCommitted();
return super.startAsync();
}
@Override
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse)
throws IllegalStateException {
this.response.disableSaveOnResponseCommitted();
return super.startAsync(servletRequest, servletResponse);
}
}
/**
* Wrapper that is applied to every request/response to update the
* <code>HttpSession</code> with the <code>SecurityContext</code> when a
* <code>sendError()</code> or <code>sendRedirect</code> happens. See SEC-398.
* <p>
* Stores the necessary state from the start of the request in order to make a
* decision about whether the security context has changed before saving it.
*/
final class SaveToSessionResponseWrapper extends SaveContextOnUpdateOrErrorResponseWrapper {
private final Log logger = HttpSessionSecurityContextRepository.this.logger;
private final HttpServletRequest request;
private final boolean httpSessionExistedAtStartOfRequest;
private final SecurityContext contextBeforeExecution;
private final Authentication authBeforeExecution;
private boolean isSaveContextInvoked;
/**
* Takes the parameters required to call <code>saveContext()</code> successfully
* in addition to the request and the response object we are wrapping.
* @param request the request object (used to obtain the session, if one exists).
* @param httpSessionExistedAtStartOfRequest indicates whether there was a session
* in place before the filter chain executed. If this is true, and the session is
* found to be null, this indicates that it was invalidated during the request and
* a new session will now be created.
* @param context the context before the filter chain executed. The context will
* only be stored if it or its contents changed during the request.
*/
SaveToSessionResponseWrapper(HttpServletResponse response, HttpServletRequest request,
boolean httpSessionExistedAtStartOfRequest, SecurityContext context) {
super(response, HttpSessionSecurityContextRepository.this.disableUrlRewriting);
this.request = request;
this.httpSessionExistedAtStartOfRequest = httpSessionExistedAtStartOfRequest;
this.contextBeforeExecution = context;
this.authBeforeExecution = context.getAuthentication();
}
/**
* Stores the supplied security context in the session (if available) and if it
* has changed since it was set at the start of the request. If the
* AuthenticationTrustResolver identifies the current user as anonymous, then the
* context will not be stored.
* @param context the context object obtained from the SecurityContextHolder after
* the request has been processed by the filter chain.
* SecurityContextHolder.getContext() cannot be used to obtain the context as it
* has already been cleared by the time this method is called.
*
*/
@Override
protected void saveContext(SecurityContext context) {
if (isTransient(context)) {
return;
}
final Authentication authentication = context.getAuthentication();
if (isTransient(authentication)) {
return;
}
HttpSession httpSession = this.request.getSession(false);
String springSecurityContextKey = HttpSessionSecurityContextRepository.this.springSecurityContextKey;
// See SEC-776
if (authentication == null
|| HttpSessionSecurityContextRepository.this.trustResolver.isAnonymous(authentication)) {
if (httpSession != null && this.authBeforeExecution != null) {
// SEC-1587 A non-anonymous context may still be in the session
// SEC-1735 remove if the contextBeforeExecution was not anonymous
httpSession.removeAttribute(springSecurityContextKey);
this.isSaveContextInvoked = true;
}
if (this.logger.isDebugEnabled()) {
if (authentication == null) {
this.logger.debug("Did not store empty SecurityContext");
}
else {
this.logger.debug("Did not store anonymous SecurityContext");
}
}
return;
}
httpSession = (httpSession != null) ? httpSession : createNewSessionIfAllowed(context);
// If HttpSession exists, store current SecurityContext but only if it has
// actually changed in this thread (see SEC-37, SEC-1307, SEC-1528)
if (httpSession != null) {
// We may have a new session, so check also whether the context attribute
// is set SEC-1561
if (contextChanged(context) || httpSession.getAttribute(springSecurityContextKey) == null) {
HttpSessionSecurityContextRepository.this.saveContextInHttpSession(context, this.request);
this.isSaveContextInvoked = true;
}
}
}
private boolean contextChanged(SecurityContext context) {
return this.isSaveContextInvoked || context != this.contextBeforeExecution
|| context.getAuthentication() != this.authBeforeExecution;
}
private HttpSession createNewSessionIfAllowed(SecurityContext context) {
if (this.httpSessionExistedAtStartOfRequest) {
this.logger.debug("HttpSession is now null, but was not null at start of request; "
+ "session was invalidated, so do not create a new session");
return null;
}
if (!HttpSessionSecurityContextRepository.this.allowSessionCreation) {
this.logger.debug("The HttpSession is currently null, and the "
+ HttpSessionSecurityContextRepository.class.getSimpleName()
+ " is prohibited from creating an HttpSession "
+ "(because the allowSessionCreation property is false) - SecurityContext thus not "
+ "stored for next request");
return null;
}
// Generate a HttpSession only if we need to
if (HttpSessionSecurityContextRepository.this.contextObject.equals(context)) {
this.logger.debug(LogMessage.format(
"HttpSession is null, but SecurityContext has not changed from "
+ "default empty context %s so not creating HttpSession or storing SecurityContext",
context));
return null;
}
try {
HttpSession session = this.request.getSession(true);
this.logger.debug("Created HttpSession as SecurityContext is non-default");
return session;
}
catch (IllegalStateException ex) {
// Response must already be committed, therefore can't create a new
// session
this.logger.warn("Failed to create a session, as response has been committed. "
+ "Unable to store SecurityContext.");
}
return null;
}
}
}
| 19,972 | 40.784519 | 111 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/context/SupplierDeferredSecurityContext.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.context;
import java.util.function.Supplier;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogMessage;
import org.springframework.security.core.context.DeferredSecurityContext;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
/**
* @author Steve Riesenberg
* @since 5.8
*/
final class SupplierDeferredSecurityContext implements DeferredSecurityContext {
private static final Log logger = LogFactory.getLog(SupplierDeferredSecurityContext.class);
private final Supplier<SecurityContext> supplier;
private final SecurityContextHolderStrategy strategy;
private SecurityContext securityContext;
private boolean missingContext;
SupplierDeferredSecurityContext(Supplier<SecurityContext> supplier, SecurityContextHolderStrategy strategy) {
this.supplier = supplier;
this.strategy = strategy;
}
@Override
public SecurityContext get() {
init();
return this.securityContext;
}
@Override
public boolean isGenerated() {
init();
return this.missingContext;
}
private void init() {
if (this.securityContext != null) {
return;
}
this.securityContext = this.supplier.get();
this.missingContext = (this.securityContext == null);
if (this.missingContext) {
this.securityContext = this.strategy.createEmptyContext();
if (logger.isTraceEnabled()) {
logger.trace(LogMessage.format("Created %s", this.securityContext));
}
}
}
}
| 2,215 | 27.410256 | 110 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/context/HttpRequestResponseHolder.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.context;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Used to pass the incoming request to
* {@link SecurityContextRepository#loadContext(HttpRequestResponseHolder)}, allowing the
* method to swap the request for a wrapped version, as well as returning the
* <tt>SecurityContext</tt> value.
*
* @author Luke Taylor
* @since 3.0
* @deprecated Use
* {@link SecurityContextRepository#loadDeferredContext(HttpServletRequest)}
*/
@Deprecated
public final class HttpRequestResponseHolder {
private HttpServletRequest request;
private HttpServletResponse response;
public HttpRequestResponseHolder(HttpServletRequest request, HttpServletResponse response) {
this.request = request;
this.response = response;
}
public HttpServletRequest getRequest() {
return this.request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletResponse getResponse() {
return this.response;
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
}
| 1,765 | 27.483871 | 93 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/context/RequestAttributeSecurityContextRepository.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.context;
import java.util.function.Supplier;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.context.DeferredSecurityContext;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.util.Assert;
/**
* Stores the {@link SecurityContext} on a
* {@link jakarta.servlet.ServletRequest#setAttribute(String, Object)} so that it can be
* restored when different dispatch types occur. It will not be available on subsequent
* requests.
*
* Unlike {@link HttpSessionSecurityContextRepository} this filter has no need to persist
* the {@link SecurityContext} on the response being committed because the
* {@link SecurityContext} will not be available for subsequent requests for
* {@link RequestAttributeSecurityContextRepository}.
*
* @author Rob Winch
* @since 5.7
*/
public final class RequestAttributeSecurityContextRepository implements SecurityContextRepository {
/**
* The default request attribute name to use.
*/
public static final String DEFAULT_REQUEST_ATTR_NAME = RequestAttributeSecurityContextRepository.class.getName()
.concat(".SPRING_SECURITY_CONTEXT");
private final String requestAttributeName;
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
/**
* Creates a new instance using {@link #DEFAULT_REQUEST_ATTR_NAME}.
*/
public RequestAttributeSecurityContextRepository() {
this(DEFAULT_REQUEST_ATTR_NAME);
}
/**
* Creates a new instance with the specified request attribute name.
* @param requestAttributeName the request attribute name to set to the
* {@link SecurityContext}.
*/
public RequestAttributeSecurityContextRepository(String requestAttributeName) {
this.requestAttributeName = requestAttributeName;
}
@Override
public boolean containsContext(HttpServletRequest request) {
return getContext(request) != null;
}
@Override
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
return loadDeferredContext(requestResponseHolder.getRequest()).get();
}
@Override
public DeferredSecurityContext loadDeferredContext(HttpServletRequest request) {
Supplier<SecurityContext> supplier = () -> getContext(request);
return new SupplierDeferredSecurityContext(supplier, this.securityContextHolderStrategy);
}
private SecurityContext getContext(HttpServletRequest request) {
return (SecurityContext) request.getAttribute(this.requestAttributeName);
}
@Override
public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {
request.setAttribute(this.requestAttributeName, context);
}
/**
* 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;
}
}
| 4,052 | 36.183486 | 113 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/context/SaveContextOnUpdateOrErrorResponseWrapper.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.context;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
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.util.OnCommittedResponseWrapper;
import org.springframework.util.Assert;
/**
* Base class for response wrappers which encapsulate the logic for storing a security
* context and which store the <code>SecurityContext</code> when a
* <code>sendError()</code>, <code>sendRedirect</code>,
* <code>getOutputStream().close()</code>, <code>getOutputStream().flush()</code>,
* <code>getWriter().close()</code>, or <code>getWriter().flush()</code> happens on the
* same thread that this {@link SaveContextOnUpdateOrErrorResponseWrapper} was created.
* See issue SEC-398 and SEC-2005.
* <p>
* Sub-classes should implement the {@link #saveContext(SecurityContext context)} method.
* <p>
* Support is also provided for disabling URL rewriting
*
* @author Luke Taylor
* @author Marten Algesten
* @author Rob Winch
* @since 3.0
* @deprecated Use
* {@link SecurityContextRepository#loadDeferredContext(HttpServletRequest)} instead.
*/
@Deprecated
public abstract class SaveContextOnUpdateOrErrorResponseWrapper extends OnCommittedResponseWrapper {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private boolean contextSaved = false;
// See SEC-1052
private final boolean disableUrlRewriting;
/**
* @param response the response to be wrapped
* @param disableUrlRewriting turns the URL encoding methods into null operations,
* preventing the use of URL rewriting to add the session identifier as a URL
* parameter.
*/
public SaveContextOnUpdateOrErrorResponseWrapper(HttpServletResponse response, boolean disableUrlRewriting) {
super(response);
this.disableUrlRewriting = disableUrlRewriting;
}
/**
* 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;
}
/**
* Invoke this method to disable automatic saving of the {@link SecurityContext} when
* the {@link HttpServletResponse} is committed. This can be useful in the event that
* Async Web Requests are made which may no longer contain the {@link SecurityContext}
* on it.
*/
public void disableSaveOnResponseCommitted() {
disableOnResponseCommitted();
}
/**
* Implements the logic for storing the security context.
* @param context the <tt>SecurityContext</tt> instance to store
*/
protected abstract void saveContext(SecurityContext context);
/**
* Calls <code>saveContext()</code> with the current contents of the
* <tt>SecurityContextHolder</tt> as long as {@link #disableSaveOnResponseCommitted()
* ()} was not invoked.
*/
@Override
protected void onResponseCommitted() {
saveContext(this.securityContextHolderStrategy.getContext());
this.contextSaved = true;
}
@Override
public final String encodeRedirectURL(String url) {
if (this.disableUrlRewriting) {
return url;
}
return super.encodeRedirectURL(url);
}
@Override
public final String encodeURL(String url) {
if (this.disableUrlRewriting) {
return url;
}
return super.encodeURL(url);
}
/**
* Tells if the response wrapper has called <code>saveContext()</code> because of this
* wrapper.
*/
public final boolean isContextSaved() {
return this.contextSaved;
}
}
| 4,609 | 33.661654 | 110 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/context/DelegatingSecurityContextRepository.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.context;
import java.util.Arrays;
import java.util.List;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.context.DeferredSecurityContext;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.util.Assert;
/**
* @author Steve Riesenberg
* @author Josh Cummings
* @since 5.8
*/
public final class DelegatingSecurityContextRepository implements SecurityContextRepository {
private final List<SecurityContextRepository> delegates;
public DelegatingSecurityContextRepository(SecurityContextRepository... delegates) {
this(Arrays.asList(delegates));
}
public DelegatingSecurityContextRepository(List<SecurityContextRepository> delegates) {
Assert.notEmpty(delegates, "delegates cannot be empty");
this.delegates = delegates;
}
@Override
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
SecurityContext result = null;
for (SecurityContextRepository delegate : this.delegates) {
SecurityContext delegateResult = delegate.loadContext(requestResponseHolder);
if (result == null || delegate.containsContext(requestResponseHolder.getRequest())) {
result = delegateResult;
}
}
return result;
}
@Override
public DeferredSecurityContext loadDeferredContext(HttpServletRequest request) {
DeferredSecurityContext deferredSecurityContext = null;
for (SecurityContextRepository delegate : this.delegates) {
if (deferredSecurityContext == null) {
deferredSecurityContext = delegate.loadDeferredContext(request);
}
else {
DeferredSecurityContext next = delegate.loadDeferredContext(request);
deferredSecurityContext = new DelegatingDeferredSecurityContext(deferredSecurityContext, next);
}
}
return deferredSecurityContext;
}
@Override
public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {
for (SecurityContextRepository delegate : this.delegates) {
delegate.saveContext(context, request, response);
}
}
@Override
public boolean containsContext(HttpServletRequest request) {
for (SecurityContextRepository delegate : this.delegates) {
if (delegate.containsContext(request)) {
return true;
}
}
return false;
}
static final class DelegatingDeferredSecurityContext implements DeferredSecurityContext {
private final DeferredSecurityContext previous;
private final DeferredSecurityContext next;
DelegatingDeferredSecurityContext(DeferredSecurityContext previous, DeferredSecurityContext next) {
this.previous = previous;
this.next = next;
}
@Override
public SecurityContext get() {
SecurityContext securityContext = this.previous.get();
if (!this.previous.isGenerated()) {
return securityContext;
}
return this.next.get();
}
@Override
public boolean isGenerated() {
return this.previous.isGenerated() && this.next.isGenerated();
}
}
}
| 3,664 | 29.798319 | 109 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/context/SecurityContextHolderFilter.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.context;
import java.io.IOException;
import java.util.function.Supplier;
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.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.util.Assert;
import org.springframework.web.filter.GenericFilterBean;
/**
* A {@link jakarta.servlet.Filter} that uses the {@link SecurityContextRepository} to
* obtain the {@link SecurityContext} and set it on the {@link SecurityContextHolder}.
* This is similar to {@link SecurityContextPersistenceFilter} except that the
* {@link SecurityContextRepository#saveContext(SecurityContext, HttpServletRequest, HttpServletResponse)}
* must be explicitly invoked to save the {@link SecurityContext}. This improves the
* efficiency and provides better flexibility by allowing different authentication
* mechanisms to choose individually if authentication should be persisted.
*
* @author Rob Winch
* @author Marcus da Coregio
* @since 5.7
*/
public class SecurityContextHolderFilter extends GenericFilterBean {
private static final String FILTER_APPLIED = SecurityContextHolderFilter.class.getName() + ".APPLIED";
private final SecurityContextRepository securityContextRepository;
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
/**
* Creates a new instance.
* @param securityContextRepository the repository to use. Cannot be null.
*/
public SecurityContextHolderFilter(SecurityContextRepository securityContextRepository) {
Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
this.securityContextRepository = securityContextRepository;
}
@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 ServletException, IOException {
if (request.getAttribute(FILTER_APPLIED) != null) {
chain.doFilter(request, response);
return;
}
request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
Supplier<SecurityContext> deferredContext = this.securityContextRepository.loadDeferredContext(request);
try {
this.securityContextHolderStrategy.setDeferredContext(deferredContext);
chain.doFilter(request, response);
}
finally {
this.securityContextHolderStrategy.clearContext();
request.removeAttribute(FILTER_APPLIED);
}
}
/**
* 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;
}
}
| 4,086 | 39.068627 | 108 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/context/SecurityContextRepository.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.context;
import java.util.function.Supplier;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.context.DeferredSecurityContext;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.function.SingletonSupplier;
/**
* Strategy used for persisting a {@link SecurityContext} between requests.
* <p>
* Used by {@link SecurityContextPersistenceFilter} to obtain the context which should be
* used for the current thread of execution and to store the context once it has been
* removed from thread-local storage and the request has completed.
* <p>
* The persistence mechanism used will depend on the implementation, but most commonly the
* <tt>HttpSession</tt> will be used to store the context.
*
* @author Luke Taylor
* @since 3.0
* @see SecurityContextPersistenceFilter
* @see HttpSessionSecurityContextRepository
* @see SaveContextOnUpdateOrErrorResponseWrapper
*/
public interface SecurityContextRepository {
/**
* Obtains the security context for the supplied request. For an unauthenticated user,
* an empty context implementation should be returned. This method should not return
* null.
* <p>
* The use of the <tt>HttpRequestResponseHolder</tt> parameter allows implementations
* to return wrapped versions of the request or response (or both), allowing them to
* access implementation-specific state for the request. The values obtained from the
* holder will be passed on to the filter chain and also to the <tt>saveContext</tt>
* method when it is finally called to allow implicit saves of the
* <tt>SecurityContext</tt>. Implementations may wish to return a subclass of
* {@link SaveContextOnUpdateOrErrorResponseWrapper} as the response object, which
* guarantees that the context is persisted when an error or redirect occurs.
* Implementations may allow passing in the original request response to allow
* explicit saves.
* @param requestResponseHolder holder for the current request and response for which
* the context should be loaded.
* @return The security context which should be used for the current request, never
* null.
* @deprecated Use {@link #loadDeferredContext(HttpServletRequest)} instead.
*/
@Deprecated
SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder);
/**
* Defers loading the {@link SecurityContext} using the {@link HttpServletRequest}
* until it is needed by the application.
* @param request the {@link HttpServletRequest} to load the {@link SecurityContext}
* from
* @return a {@link DeferredSecurityContext} that returns the {@link SecurityContext}
* which cannot be null
* @since 5.8
*/
default DeferredSecurityContext loadDeferredContext(HttpServletRequest request) {
Supplier<SecurityContext> supplier = () -> loadContext(new HttpRequestResponseHolder(request, null));
return new SupplierDeferredSecurityContext(SingletonSupplier.of(supplier),
SecurityContextHolder.getContextHolderStrategy());
}
/**
* Stores the security context on completion of a request.
* @param context the non-null context which was obtained from the holder.
* @param request
* @param response
*/
void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response);
/**
* Allows the repository to be queried as to whether it contains a security context
* for the current request.
* @param request the current request
* @return true if a context is found for the request, false otherwise
*/
boolean containsContext(HttpServletRequest request);
}
| 4,403 | 41.757282 | 103 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/context/NullSecurityContextRepository.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.context;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.util.Assert;
/**
* @author Luke Taylor
* @since 3.1
*/
public final class NullSecurityContextRepository implements SecurityContextRepository {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
@Override
public boolean containsContext(HttpServletRequest request) {
return false;
}
@Override
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
return this.securityContextHolderStrategy.createEmptyContext();
}
@Override
public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {
}
/**
* 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;
}
}
| 2,163 | 33.903226 | 109 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializer.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.context;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Set;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterRegistration.Dynamic;
import jakarta.servlet.ServletContext;
import jakarta.servlet.SessionTrackingMode;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Conventions;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.util.Assert;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.AbstractContextLoaderInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;
/**
* Registers the {@link DelegatingFilterProxy} to use the springSecurityFilterChain before
* any other registered {@link Filter}. When used with
* {@link #AbstractSecurityWebApplicationInitializer(Class...)}, it will also register a
* {@link ContextLoaderListener}. When used with
* {@link #AbstractSecurityWebApplicationInitializer()}, this class is typically used in
* addition to a subclass of {@link AbstractContextLoaderInitializer}.
*
* <p>
* By default the {@link DelegatingFilterProxy} is registered without support, but can be
* enabled by overriding {@link #isAsyncSecuritySupported()} and
* {@link #getSecurityDispatcherTypes()}.
* </p>
*
* <p>
* Additional configuration before and after the springSecurityFilterChain can be added by
* overriding {@link #afterSpringSecurityFilterChain(ServletContext)}.
* </p>
*
*
* <h2>Caveats</h2>
* <p>
* Subclasses of AbstractDispatcherServletInitializer will register their filters before
* any other {@link Filter}. This means that you will typically want to ensure subclasses
* of AbstractDispatcherServletInitializer are invoked first. This can be done by ensuring
* the {@link Order} or {@link Ordered} of AbstractDispatcherServletInitializer are sooner
* than subclasses of {@link AbstractSecurityWebApplicationInitializer}.
* </p>
*
* @author Rob Winch
* @author Keesun Baik
*/
public abstract class AbstractSecurityWebApplicationInitializer implements WebApplicationInitializer {
private static final String SERVLET_CONTEXT_PREFIX = "org.springframework.web.servlet.FrameworkServlet.CONTEXT.";
public static final String DEFAULT_FILTER_NAME = "springSecurityFilterChain";
private final Class<?>[] configurationClasses;
/**
* Creates a new instance that assumes the Spring Security configuration is loaded by
* some other means than this class. For example, a user might create a
* {@link ContextLoaderListener} using a subclass of
* {@link AbstractContextLoaderInitializer}.
*
* @see ContextLoaderListener
*/
protected AbstractSecurityWebApplicationInitializer() {
this.configurationClasses = null;
}
/**
* Creates a new instance that will instantiate the {@link ContextLoaderListener} with
* the specified classes.
* @param configurationClasses
*/
protected AbstractSecurityWebApplicationInitializer(Class<?>... configurationClasses) {
this.configurationClasses = configurationClasses;
}
@Override
public final void onStartup(ServletContext servletContext) {
beforeSpringSecurityFilterChain(servletContext);
if (this.configurationClasses != null) {
AnnotationConfigWebApplicationContext rootAppContext = new AnnotationConfigWebApplicationContext();
rootAppContext.register(this.configurationClasses);
servletContext.addListener(new ContextLoaderListener(rootAppContext));
}
if (enableHttpSessionEventPublisher()) {
servletContext.addListener("org.springframework.security.web.session.HttpSessionEventPublisher");
}
servletContext.setSessionTrackingModes(getSessionTrackingModes());
insertSpringSecurityFilterChain(servletContext);
afterSpringSecurityFilterChain(servletContext);
}
/**
* Override this if {@link HttpSessionEventPublisher} should be added as a listener.
* This should be true, if session management has specified a maximum number of
* sessions.
* @return true to add {@link HttpSessionEventPublisher}, else false
*/
protected boolean enableHttpSessionEventPublisher() {
return false;
}
/**
* Registers the springSecurityFilterChain
* @param servletContext the {@link ServletContext}
*/
private void insertSpringSecurityFilterChain(ServletContext servletContext) {
String filterName = DEFAULT_FILTER_NAME;
DelegatingFilterProxy springSecurityFilterChain = new DelegatingFilterProxy(filterName);
String contextAttribute = getWebApplicationContextAttribute();
if (contextAttribute != null) {
springSecurityFilterChain.setContextAttribute(contextAttribute);
}
registerFilter(servletContext, true, filterName, springSecurityFilterChain);
}
/**
* Inserts the provided {@link Filter}s before existing {@link Filter}s using default
* generated names, {@link #getSecurityDispatcherTypes()}, and
* {@link #isAsyncSecuritySupported()}.
* @param servletContext the {@link ServletContext} to use
* @param filters the {@link Filter}s to register
*/
protected final void insertFilters(ServletContext servletContext, Filter... filters) {
registerFilters(servletContext, true, filters);
}
/**
* Inserts the provided {@link Filter}s after existing {@link Filter}s using default
* generated names, {@link #getSecurityDispatcherTypes()}, and
* {@link #isAsyncSecuritySupported()}.
* @param servletContext the {@link ServletContext} to use
* @param filters the {@link Filter}s to register
*/
protected final void appendFilters(ServletContext servletContext, Filter... filters) {
registerFilters(servletContext, false, filters);
}
/**
* Registers the provided {@link Filter}s using default generated names,
* {@link #getSecurityDispatcherTypes()}, and {@link #isAsyncSecuritySupported()}.
* @param servletContext the {@link ServletContext} to use
* @param insertBeforeOtherFilters if true, will insert the provided {@link Filter}s
* before other {@link Filter}s. Otherwise, will insert the {@link Filter}s after
* other {@link Filter}s.
* @param filters the {@link Filter}s to register
*/
private void registerFilters(ServletContext servletContext, boolean insertBeforeOtherFilters, Filter... filters) {
Assert.notEmpty(filters, "filters cannot be null or empty");
for (Filter filter : filters) {
Assert.notNull(filter, () -> "filters cannot contain null values. Got " + Arrays.asList(filters));
String filterName = Conventions.getVariableName(filter);
registerFilter(servletContext, insertBeforeOtherFilters, filterName, filter);
}
}
/**
* Registers the provided filter using the {@link #isAsyncSecuritySupported()} and
* {@link #getSecurityDispatcherTypes()}.
* @param servletContext
* @param insertBeforeOtherFilters should this Filter be inserted before or after
* other {@link Filter}
* @param filterName
* @param filter
*/
private void registerFilter(ServletContext servletContext, boolean insertBeforeOtherFilters, String filterName,
Filter filter) {
Dynamic registration = servletContext.addFilter(filterName, filter);
Assert.state(registration != null, () -> "Duplicate Filter registration for '" + filterName
+ "'. Check to ensure the Filter is only configured once.");
registration.setAsyncSupported(isAsyncSecuritySupported());
EnumSet<DispatcherType> dispatcherTypes = getSecurityDispatcherTypes();
registration.addMappingForUrlPatterns(dispatcherTypes, !insertBeforeOtherFilters, "/*");
}
/**
* Returns the {@link DelegatingFilterProxy#getContextAttribute()} or null if the
* parent {@link ApplicationContext} should be used. The default behavior is to use
* the parent {@link ApplicationContext}.
*
* <p>
* If {@link #getDispatcherWebApplicationContextSuffix()} is non-null the
* {@link WebApplicationContext} for the Dispatcher will be used. This means the child
* {@link ApplicationContext} is used to look up the springSecurityFilterChain bean.
* </p>
* @return the {@link DelegatingFilterProxy#getContextAttribute()} or null if the
* parent {@link ApplicationContext} should be used
*/
private String getWebApplicationContextAttribute() {
String dispatcherServletName = getDispatcherWebApplicationContextSuffix();
if (dispatcherServletName == null) {
return null;
}
return SERVLET_CONTEXT_PREFIX + dispatcherServletName;
}
/**
* Determines how a session should be tracked. By default,
* {@link SessionTrackingMode#COOKIE} is used.
*
* <p>
* Note that {@link SessionTrackingMode#URL} is intentionally omitted to help
* protected against <a href="https://en.wikipedia.org/wiki/Session_fixation">session
* fixation attacks</a>. {@link SessionTrackingMode#SSL} is omitted because SSL
* configuration is required for this to work.
* </p>
*
* <p>
* Subclasses can override this method to make customizations.
* </p>
* @return
*/
protected Set<SessionTrackingMode> getSessionTrackingModes() {
return EnumSet.of(SessionTrackingMode.COOKIE);
}
/**
* Return the <servlet-name> to use the DispatcherServlet's
* {@link WebApplicationContext} to find the {@link DelegatingFilterProxy} or null to
* use the parent {@link ApplicationContext}.
*
* <p>
* For example, if you are using AbstractDispatcherServletInitializer or
* AbstractAnnotationConfigDispatcherServletInitializer and using the provided Servlet
* name, you can return "dispatcher" from this method to use the DispatcherServlet's
* {@link WebApplicationContext}.
* </p>
* @return the <servlet-name> of the DispatcherServlet to use its
* {@link WebApplicationContext} or null (default) to use the parent
* {@link ApplicationContext}.
*/
protected String getDispatcherWebApplicationContextSuffix() {
return null;
}
/**
* Invoked before the springSecurityFilterChain is added.
* @param servletContext the {@link ServletContext}
*/
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
}
/**
* Invoked after the springSecurityFilterChain is added.
* @param servletContext the {@link ServletContext}
*/
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
}
/**
* Get the {@link DispatcherType} for the springSecurityFilterChain.
* @return
*/
protected EnumSet<DispatcherType> getSecurityDispatcherTypes() {
return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC, DispatcherType.FORWARD,
DispatcherType.INCLUDE);
}
/**
* Determine if the springSecurityFilterChain should be marked as supporting asynch.
* Default is true.
* @return true if springSecurityFilterChain should be marked as supporting asynch
*/
protected boolean isAsyncSecuritySupported() {
return true;
}
}
| 11,758 | 38.592593 | 115 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/context/SecurityContextPersistenceFilter.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.context;
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.core.log.LogMessage;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.util.Assert;
import org.springframework.web.filter.GenericFilterBean;
/**
* Populates the {@link SecurityContextHolder} with information obtained from the
* configured {@link SecurityContextRepository} prior to the request and stores it back in
* the repository once the request has completed and clearing the context holder. By
* default it uses an {@link HttpSessionSecurityContextRepository}. See this class for
* information <tt>HttpSession</tt> related configuration options.
* <p>
* This filter will only execute once per request, to resolve servlet container
* (specifically Weblogic) incompatibilities.
* <p>
* This filter MUST be executed BEFORE any authentication processing mechanisms.
* Authentication processing mechanisms (e.g. BASIC, CAS processing filters etc) expect
* the <code>SecurityContextHolder</code> to contain a valid <code>SecurityContext</code>
* by the time they execute.
* <p>
* This is essentially a refactoring of the old
* <tt>HttpSessionContextIntegrationFilter</tt> to delegate the storage issues to a
* separate strategy, allowing for more customization in the way the security context is
* maintained between requests.
* <p>
* The <tt>forceEagerSessionCreation</tt> property can be used to ensure that a session is
* always available before the filter chain executes (the default is <code>false</code>,
* as this is resource intensive and not recommended).
*
* @author Luke Taylor
* @since 3.0
* @deprecated Use {@link SecurityContextHolderFilter}
*/
@Deprecated
public class SecurityContextPersistenceFilter extends GenericFilterBean {
static final String FILTER_APPLIED = "__spring_security_scpf_applied";
private SecurityContextRepository repo;
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private boolean forceEagerSessionCreation = false;
public SecurityContextPersistenceFilter() {
this(new HttpSessionSecurityContextRepository());
}
public SecurityContextPersistenceFilter(SecurityContextRepository repo) {
this.repo = repo;
}
@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 {
// ensure that filter is only applied once per request
if (request.getAttribute(FILTER_APPLIED) != null) {
chain.doFilter(request, response);
return;
}
request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
if (this.forceEagerSessionCreation) {
HttpSession session = request.getSession();
if (this.logger.isDebugEnabled() && session.isNew()) {
this.logger.debug(LogMessage.format("Created session %s eagerly", session.getId()));
}
}
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext contextBeforeChainExecution = this.repo.loadContext(holder);
try {
this.securityContextHolderStrategy.setContext(contextBeforeChainExecution);
if (contextBeforeChainExecution.getAuthentication() == null) {
logger.debug("Set SecurityContextHolder to empty SecurityContext");
}
else {
if (this.logger.isDebugEnabled()) {
this.logger
.debug(LogMessage.format("Set SecurityContextHolder to %s", contextBeforeChainExecution));
}
}
chain.doFilter(holder.getRequest(), holder.getResponse());
}
finally {
SecurityContext contextAfterChainExecution = this.securityContextHolderStrategy.getContext();
// Crucial removal of SecurityContextHolder contents before anything else.
this.securityContextHolderStrategy.clearContext();
this.repo.saveContext(contextAfterChainExecution, holder.getRequest(), holder.getResponse());
request.removeAttribute(FILTER_APPLIED);
this.logger.debug("Cleared SecurityContextHolder to complete request");
}
}
public void setForceEagerSessionCreation(boolean forceEagerSessionCreation) {
this.forceEagerSessionCreation = forceEagerSessionCreation;
}
/**
* 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;
}
}
| 5,954 | 40.068966 | 108 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/context/request/async/SecurityContextCallableProcessingInterceptor.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.context.request.async;
import java.util.concurrent.Callable;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.util.Assert;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.async.CallableProcessingInterceptor;
/**
* <p>
* Allows for integration with Spring MVC's {@link Callable} support.
* </p>
* <p>
* A {@link CallableProcessingInterceptor} that establishes the injected
* {@link SecurityContext} on the {@link SecurityContextHolder} when
* {@link #preProcess(NativeWebRequest, Callable)} is invoked. It also clear out the
* {@link SecurityContextHolder} by invoking {@link SecurityContextHolder#clearContext()}
* in the {@link #postProcess(NativeWebRequest, Callable, Object)} method.
* </p>
*
* @author Rob Winch
* @since 3.2
*/
public final class SecurityContextCallableProcessingInterceptor implements CallableProcessingInterceptor {
private volatile SecurityContext securityContext;
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
/**
* Create a new {@link SecurityContextCallableProcessingInterceptor} that uses the
* {@link SecurityContext} from the {@link SecurityContextHolder} at the time
* {@link #beforeConcurrentHandling(NativeWebRequest, Callable)} is invoked.
*/
public SecurityContextCallableProcessingInterceptor() {
}
/**
* Creates a new {@link SecurityContextCallableProcessingInterceptor} with the
* specified {@link SecurityContext}.
* @param securityContext the {@link SecurityContext} to set on the
* {@link SecurityContextHolder} in {@link #preProcess(NativeWebRequest, Callable)}.
* Cannot be null.
* @throws IllegalArgumentException if {@link SecurityContext} is null.
*/
public SecurityContextCallableProcessingInterceptor(SecurityContext securityContext) {
Assert.notNull(securityContext, "securityContext cannot be null");
setSecurityContext(securityContext);
}
@Override
public <T> void beforeConcurrentHandling(NativeWebRequest request, Callable<T> task) {
if (this.securityContext == null) {
setSecurityContext(this.securityContextHolderStrategy.getContext());
}
}
@Override
public <T> void preProcess(NativeWebRequest request, Callable<T> task) {
this.securityContextHolderStrategy.setContext(this.securityContext);
}
@Override
public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) {
this.securityContextHolderStrategy.clearContext();
}
/**
* 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 void setSecurityContext(SecurityContext securityContext) {
this.securityContext = securityContext;
}
}
| 3,993 | 37.403846 | 108 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/context/request/async/WebAsyncManagerIntegrationFilter.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.context.request.async;
import java.io.IOException;
import java.util.concurrent.Callable;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.util.Assert;
import org.springframework.web.context.request.async.WebAsyncManager;
import org.springframework.web.context.request.async.WebAsyncUtils;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* Provides integration between the {@link SecurityContext} and Spring Web's
* {@link WebAsyncManager} by using the
* {@link SecurityContextCallableProcessingInterceptor#beforeConcurrentHandling(org.springframework.web.context.request.NativeWebRequest, Callable)}
* to populate the {@link SecurityContext} on the {@link Callable}.
*
* @author Rob Winch
* @see SecurityContextCallableProcessingInterceptor
*/
public final class WebAsyncManagerIntegrationFilter extends OncePerRequestFilter {
private static final Object CALLABLE_INTERCEPTOR_KEY = new Object();
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
SecurityContextCallableProcessingInterceptor securityProcessingInterceptor = (SecurityContextCallableProcessingInterceptor) asyncManager
.getCallableInterceptor(CALLABLE_INTERCEPTOR_KEY);
if (securityProcessingInterceptor == null) {
SecurityContextCallableProcessingInterceptor interceptor = new SecurityContextCallableProcessingInterceptor();
interceptor.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);
asyncManager.registerCallableInterceptor(CALLABLE_INTERCEPTOR_KEY, interceptor);
}
filterChain.doFilter(request, response);
}
/**
* 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;
}
}
| 3,390 | 43.038961 | 148 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/context/support/SecurityWebApplicationContextUtils.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.context.support;
import jakarta.servlet.ServletContext;
import org.springframework.util.Assert;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
/**
* Spring Security extension to Spring's {@link WebApplicationContextUtils}.
*
* @author Rob Winch
*/
public abstract class SecurityWebApplicationContextUtils extends WebApplicationContextUtils {
/**
* Find a unique {@code WebApplicationContext} for this web app: either the root web
* app context (preferred) or a unique {@code WebApplicationContext} among the
* registered {@code ServletContext} attributes (typically coming from a single
* {@code DispatcherServlet} in the current web application).
* <p>
* Note that {@code DispatcherServlet}'s exposure of its context can be controlled
* through its {@code publishContext} property, which is {@code true} by default but
* can be selectively switched to only publish a single context despite multiple
* {@code DispatcherServlet} registrations in the web app.
* @param servletContext ServletContext to find the web application context for
* @return the desired WebApplicationContext for this web app
* @throws IllegalStateException if no WebApplicationContext can be found
* @see #getWebApplicationContext(ServletContext)
* @see ServletContext#getAttributeNames()
*/
public static WebApplicationContext findRequiredWebApplicationContext(ServletContext servletContext) {
WebApplicationContext webApplicationContext = findWebApplicationContext(servletContext);
Assert.state(webApplicationContext != null,
"No WebApplicationContext found: no ContextLoaderListener registered?");
return webApplicationContext;
}
}
| 2,414 | 42.125 | 103 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/aot/hint/WebMvcSecurityRuntimeHints.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.aot.hint;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.security.web.access.expression.WebSecurityExpressionRoot;
/**
* {@link RuntimeHintsRegistrar} for WebMVC classes
*
* @author Marcus Da Coregio
* @since 6.0
*/
class WebMvcSecurityRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.reflection().registerType(WebSecurityExpressionRoot.class, (builder) -> builder
.withMembers(MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS));
}
}
| 1,367 | 34.076923 | 90 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/method/annotation/CsrfTokenArgumentResolver.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.method.annotation;
import org.springframework.core.MethodParameter;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
* Allows resolving the current {@link CsrfToken}. For example, the following
* {@link RestController} will resolve the current {@link CsrfToken}:
*
* <pre>
* <code>
* @RestController
* public class MyController {
* @MessageMapping("/im")
* public CsrfToken csrf(CsrfToken token) {
* return token;
* }
* }
* </code> </pre>
*
* @author Rob Winch
* @since 4.0
*/
public final class CsrfTokenArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return CsrfToken.class.equals(parameter.getParameterType());
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
CsrfToken token = (CsrfToken) webRequest.getAttribute(CsrfToken.class.getName(),
RequestAttributes.SCOPE_REQUEST);
return token;
}
}
| 2,155 | 33.774194 | 93 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/method/annotation/AuthenticationPrincipalArgumentResolver.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.method.annotation;
import java.lang.annotation.Annotation;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.expression.BeanResolver;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
* Allows resolving the {@link Authentication#getPrincipal()} using the
* {@link AuthenticationPrincipal} annotation. For example, the following
* {@link Controller}:
*
* <pre>
* @Controller
* public class MyController {
* @MessageMapping("/im")
* public void im(@AuthenticationPrincipal CustomUser customUser) {
* // do something with CustomUser
* }
* }
* </pre>
*
* <p>
* Will resolve the CustomUser argument using {@link Authentication#getPrincipal()} from
* the {@link SecurityContextHolder}. If the {@link Authentication} or
* {@link Authentication#getPrincipal()} is null, it will return null. If the types do not
* match, null will be returned unless
* {@link AuthenticationPrincipal#errorOnInvalidType()} is true in which case a
* {@link ClassCastException} will be thrown.
*
* <p>
* Alternatively, users can create a custom meta annotation as shown below:
*
* <pre>
* @Target({ ElementType.PARAMETER })
* @Retention(RetentionPolicy.RUNTIME)
* @AuthenticationPrincipal
* public @interface CurrentUser {
* }
* </pre>
*
* <p>
* The custom annotation can then be used instead. For example:
*
* <pre>
* @Controller
* public class MyController {
* @MessageMapping("/im")
* public void im(@CurrentUser CustomUser customUser) {
* // do something with CustomUser
* }
* }
* </pre>
*
* @author Rob Winch
* @since 4.0
*/
public final class AuthenticationPrincipalArgumentResolver implements HandlerMethodArgumentResolver {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private ExpressionParser parser = new SpelExpressionParser();
private BeanResolver beanResolver;
@Override
public boolean supportsParameter(MethodParameter parameter) {
return findMethodAnnotation(AuthenticationPrincipal.class, parameter) != null;
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication();
if (authentication == null) {
return null;
}
Object principal = authentication.getPrincipal();
AuthenticationPrincipal annotation = findMethodAnnotation(AuthenticationPrincipal.class, parameter);
String expressionToParse = annotation.expression();
if (StringUtils.hasLength(expressionToParse)) {
StandardEvaluationContext context = new StandardEvaluationContext();
context.setRootObject(principal);
context.setVariable("this", principal);
context.setBeanResolver(this.beanResolver);
Expression expression = this.parser.parseExpression(expressionToParse);
principal = expression.getValue(context);
}
if (principal != null && !ClassUtils.isAssignable(parameter.getParameterType(), principal.getClass())) {
if (annotation.errorOnInvalidType()) {
throw new ClassCastException(principal + " is not assignable to " + parameter.getParameterType());
}
return null;
}
return principal;
}
/**
* Sets the {@link BeanResolver} to be used on the expressions
* @param beanResolver the {@link BeanResolver} to use
*/
public void setBeanResolver(BeanResolver beanResolver) {
this.beanResolver = beanResolver;
}
/**
* 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;
}
/**
* Obtains the specified {@link Annotation} on the specified {@link MethodParameter}.
* @param annotationClass the class of the {@link Annotation} to find on the
* {@link MethodParameter}
* @param parameter the {@link MethodParameter} to search for an {@link Annotation}
* @return the {@link Annotation} that was found or null.
*/
private <T extends Annotation> T findMethodAnnotation(Class<T> annotationClass, MethodParameter parameter) {
T annotation = parameter.getParameterAnnotation(annotationClass);
if (annotation != null) {
return annotation;
}
Annotation[] annotationsToSearch = parameter.getParameterAnnotations();
for (Annotation toSearch : annotationsToSearch) {
annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), annotationClass);
if (annotation != null) {
return annotation;
}
}
return null;
}
}
| 6,621 | 37.057471 | 109 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/method/annotation/CurrentSecurityContextArgumentResolver.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.method.annotation;
import java.lang.annotation.Annotation;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.expression.BeanResolver;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.security.core.annotation.CurrentSecurityContext;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
* Allows resolving the {@link SecurityContext} using the {@link CurrentSecurityContext}
* annotation. For example, the following {@link Controller}:
*
* <pre>
* @Controller
* public class MyController {
* @RequestMapping("/im")
* public void security(@CurrentSecurityContext SecurityContext context) {
* // do something with context
* }
* }
* </pre>
*
* it can also support the spring SPEL expression to get the value from SecurityContext
* <pre>
* @Controller
* public class MyController {
* @RequestMapping("/im")
* public void security(@CurrentSecurityContext(expression="authentication") Authentication authentication) {
* // do something with context
* }
* }
* </pre>
*
* <p>
* Will resolve the {@link SecurityContext} argument using
* {@link SecurityContextHolder#getContext()} from the {@link SecurityContextHolder}. If
* the {@link SecurityContext} is {@code null}, it will return {@code null}. If the types
* do not match, {@code null} will be returned unless
* {@link CurrentSecurityContext#errorOnInvalidType()} is {@code true} in which case a
* {@link ClassCastException} will be thrown.
* </p>
*
* @author Dan Zheng
* @since 5.2
*/
public final class CurrentSecurityContextArgumentResolver implements HandlerMethodArgumentResolver {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private ExpressionParser parser = new SpelExpressionParser();
private BeanResolver beanResolver;
@Override
public boolean supportsParameter(MethodParameter parameter) {
return findMethodAnnotation(CurrentSecurityContext.class, parameter) != null;
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
SecurityContext securityContext = this.securityContextHolderStrategy.getContext();
if (securityContext == null) {
return null;
}
Object securityContextResult = securityContext;
CurrentSecurityContext annotation = findMethodAnnotation(CurrentSecurityContext.class, parameter);
String expressionToParse = annotation.expression();
if (StringUtils.hasLength(expressionToParse)) {
StandardEvaluationContext context = new StandardEvaluationContext();
context.setRootObject(securityContext);
context.setVariable("this", securityContext);
context.setBeanResolver(this.beanResolver);
Expression expression = this.parser.parseExpression(expressionToParse);
securityContextResult = expression.getValue(context);
}
if (securityContextResult != null
&& !parameter.getParameterType().isAssignableFrom(securityContextResult.getClass())) {
if (annotation.errorOnInvalidType()) {
throw new ClassCastException(
securityContextResult + " is not assignable to " + parameter.getParameterType());
}
return null;
}
return securityContextResult;
}
/**
* 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;
}
/**
* Set the {@link BeanResolver} to be used on the expressions
* @param beanResolver the {@link BeanResolver} to use
*/
public void setBeanResolver(BeanResolver beanResolver) {
Assert.notNull(beanResolver, "beanResolver cannot be null");
this.beanResolver = beanResolver;
}
/**
* Obtain the specified {@link Annotation} on the specified {@link MethodParameter}.
* @param annotationClass the class of the {@link Annotation} to find on the
* {@link MethodParameter}
* @param parameter the {@link MethodParameter} to search for an {@link Annotation}
* @return the {@link Annotation} that was found or null.
*/
private <T extends Annotation> T findMethodAnnotation(Class<T> annotationClass, MethodParameter parameter) {
T annotation = parameter.getParameterAnnotation(annotationClass);
if (annotation != null) {
return annotation;
}
Annotation[] annotationsToSearch = parameter.getParameterAnnotations();
for (Annotation toSearch : annotationsToSearch) {
annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), annotationClass);
if (annotation != null) {
return annotation;
}
}
return null;
}
}
| 6,498 | 38.871166 | 113 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/jackson2/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.
*/
/**
* Mix-in classes to provide Jackson serialization support.
*
* @author Jitendra Singh
* @since 4.2
*/
package org.springframework.security.web.jackson2;
| 785 | 31.75 | 75 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/jackson2/CookieMixin.java | /*
* Copyright 2015-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.jackson2;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
/**
* Mixin class to serialize/deserialize {@link jakarta.servlet.http.Cookie}
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new WebServletJackson2Module());
* </pre>
*
* @author Jitendra Singh
* @since 4.2
* @see WebServletJackson2Module
* @see org.springframework.security.jackson2.SecurityJackson2Modules
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonDeserialize(using = CookieDeserializer.class)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
abstract class CookieMixin {
}
| 1,495 | 34.619048 | 117 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/jackson2/WebServletJackson2Module.java | /*
* Copyright 2015-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.jackson2;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.module.SimpleModule;
import jakarta.servlet.http.Cookie;
import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;
import org.springframework.security.web.savedrequest.SavedCookie;
/**
* Jackson module for spring-security-web related to servlet. This module register
* {@link CookieMixin}, {@link SavedCookieMixin}, {@link DefaultSavedRequestMixin} and
* {@link WebAuthenticationDetailsMixin}. If no default typing enabled by default then
* it'll enable it because typing info is needed to properly serialize/deserialize
* objects. In order to use this module just add this module into your ObjectMapper
* configuration.
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new WebServletJackson2Module());
* </pre> <b>Note: use {@link SecurityJackson2Modules#getModules(ClassLoader)} to get list
* of all security modules.</b>
*
* @author Boris Finkelshteyn
* @since 5.1
* @see SecurityJackson2Modules
*/
public class WebServletJackson2Module extends SimpleModule {
public WebServletJackson2Module() {
super(WebServletJackson2Module.class.getName(), new Version(1, 0, 0, null, null, null));
}
@Override
public void setupModule(SetupContext context) {
SecurityJackson2Modules.enableDefaultTyping(context.getOwner());
context.setMixInAnnotations(Cookie.class, CookieMixin.class);
context.setMixInAnnotations(SavedCookie.class, SavedCookieMixin.class);
context.setMixInAnnotations(DefaultSavedRequest.class, DefaultSavedRequestMixin.class);
context.setMixInAnnotations(WebAuthenticationDetails.class, WebAuthenticationDetailsMixin.class);
}
}
| 2,536 | 39.919355 | 99 | java |
null | spring-security-main/web/src/main/java/org/springframework/security/web/jackson2/CookieDeserializer.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.jackson2;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.MissingNode;
import com.fasterxml.jackson.databind.node.NullNode;
import jakarta.servlet.http.Cookie;
/**
* Jackson deserializer for {@link Cookie}. This is needed because in most cases we don't
* set {@link Cookie#getDomain()} property. So when jackson deserialize that json
* {@link Cookie#setDomain(String)} throws {@link NullPointerException}. This is
* registered with {@link CookieMixin} but you can also use it with your own mixin.
*
* @author Jitendra Singh
* @since 4.2
* @see CookieMixin
*/
class CookieDeserializer extends JsonDeserializer<Cookie> {
@Override
public Cookie deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectMapper mapper = (ObjectMapper) jp.getCodec();
JsonNode jsonNode = mapper.readTree(jp);
Cookie cookie = new Cookie(readJsonNode(jsonNode, "name").asText(), readJsonNode(jsonNode, "value").asText());
cookie.setComment(readJsonNode(jsonNode, "comment").asText());
cookie.setDomain(readJsonNode(jsonNode, "domain").asText());
cookie.setMaxAge(readJsonNode(jsonNode, "maxAge").asInt(-1));
cookie.setSecure(readJsonNode(jsonNode, "secure").asBoolean());
cookie.setVersion(readJsonNode(jsonNode, "version").asInt());
cookie.setPath(readJsonNode(jsonNode, "path").asText());
JsonNode attributes = readJsonNode(jsonNode, "attributes");
cookie.setHttpOnly(readJsonNode(attributes, "HttpOnly").asBoolean());
return cookie;
}
private JsonNode readJsonNode(JsonNode jsonNode, String field) {
return hasNonNullField(jsonNode, field) ? jsonNode.get(field) : MissingNode.getInstance();
}
private boolean hasNonNullField(JsonNode jsonNode, String field) {
return jsonNode.has(field) && !(jsonNode.get(field) instanceof NullNode);
}
}
| 2,829 | 40.617647 | 116 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.