or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication-filters.mdauthorization.mdcsrf-protection.mdfilter-chain.mdfirewall.mdindex.mdlogout.mdreactive-security.mdrequest-matching.mdsaved-requests.mdsecurity-context.mdsecurity-headers.mdservlet-integration.mdsession-management.md
tile.json

servlet-integration.mddocs/

Servlet API Integration

Servlet API integration provides wrappers and utilities that integrate Spring Security with the Jakarta Servlet API and related frameworks.

Servlet API Wrappers

HttpServlet3RequestFactory

Factory for creating Servlet 3 request wrappers with Spring Security integration.

package org.springframework.security.web.servletapi;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.security.authentication.AuthenticationTrustResolver;

public class HttpServlet3RequestFactory {
    /**
     * Creates a factory with the given role prefix.
     *
     * @param rolePrefix the role prefix (e.g., "ROLE_")
     */
    public HttpServlet3RequestFactory(String rolePrefix);

    /**
     * Creates a factory with role prefix and trust resolver.
     *
     * @param rolePrefix the role prefix
     * @param trustResolver the authentication trust resolver
     */
    public HttpServlet3RequestFactory(String rolePrefix, AuthenticationTrustResolver trustResolver);

    /**
     * Creates a SecurityContextHolderAwareRequestWrapper for the given request.
     *
     * @param request the HTTP request
     * @return the wrapped request
     */
    public SecurityContextHolderAwareRequestWrapper create(HttpServletRequest request);
}

SecurityContextHolderAwareRequestWrapper

Wraps HttpServletRequest to integrate Spring Security with Servlet API methods.

package org.springframework.security.web.servletapi;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import java.security.Principal;

import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.core.Authentication;

public class SecurityContextHolderAwareRequestWrapper extends HttpServletRequestWrapper {
    /**
     * Creates a wrapper for the given request.
     *
     * @param request the HTTP request
     * @param rolePrefix the prefix for role checking (e.g., "ROLE_")
     */
    public SecurityContextHolderAwareRequestWrapper(HttpServletRequest request, String rolePrefix);

    /**
     * Creates a wrapper for the given request with a custom trust resolver.
     *
     * @param request the HTTP request
     * @param trustResolver the authentication trust resolver
     * @param rolePrefix the prefix for role checking (e.g., "ROLE_")
     */
    public SecurityContextHolderAwareRequestWrapper(HttpServletRequest request,
            AuthenticationTrustResolver trustResolver, String rolePrefix);

    /**
     * Returns the remote user from Spring Security context.
     */
    @Override
    public String getRemoteUser();
    
    /**
     * Returns the user principal from Spring Security context.
     */
    @Override
    public Principal getUserPrincipal();
    
    /**
     * Checks if user has the specified role using Spring Security.
     *
     * @param role the role to check (without prefix)
     */
    @Override
    public boolean isUserInRole(String role);
    
    /**
     * Returns the Authentication from Spring Security context.
     */
    public Authentication getAuthentication();
    
    /**
     * Performs login using Spring Security.
     */
    @Override
    public void login(String username, String password) throws ServletException;
    
    /**
     * Performs logout using Spring Security.
     */
    @Override
    public void logout() throws ServletException;
}

SecurityContextHolderAwareRequestFilter

Filter that wraps requests with SecurityContextHolderAwareRequestWrapper.

package org.springframework.security.web.servletapi;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import java.io.IOException;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.web.filter.GenericFilterBean;

public class SecurityContextHolderAwareRequestFilter extends GenericFilterBean {
    public SecurityContextHolderAwareRequestFilter();
    
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws ServletException, IOException;
    
    /**
     * Sets the role prefix (default: "ROLE_").
     */
    public void setRolePrefix(String rolePrefix);
    
    /**
     * Sets the authentication manager for login operations.
     */
    public void setAuthenticationManager(AuthenticationManager authenticationManager);
    
    /**
     * Sets the authentication trust resolver.
     */
    public void setTrustResolver(AuthenticationTrustResolver trustResolver);
    
    /**
     * Sets the SecurityContextHolderStrategy.
     */
    public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy);
    
    /**
     * Sets the logout handlers.
     */
    public void setLogoutHandlers(List<LogoutHandler> logoutHandlers);
}

Annotation Support

AuthenticationPrincipalArgumentResolver

Resolves @AuthenticationPrincipal annotated method arguments.

package org.springframework.security.web.method.annotation;

import org.springframework.core.MethodParameter;
import org.springframework.security.core.Authentication;
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;

public class AuthenticationPrincipalArgumentResolver implements HandlerMethodArgumentResolver {
    public AuthenticationPrincipalArgumentResolver();
    
    public boolean supportsParameter(MethodParameter parameter);
    
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                   NativeWebRequest webRequest, WebDataBinderFactory binderFactory);
}

AuthenticationPrincipal

Annotation to bind authentication principal to method parameter.

package org.springframework.security.core.annotation;

import java.lang.annotation.*;

@Target({ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AuthenticationPrincipal {
    /**
     * Whether to return null when authentication is null (default: false).
     */
    boolean errorOnInvalidType() default false;
    
    /**
     * SpEL expression to extract a property from the principal.
     */
    String expression() default "";
}

CurrentSecurityContext

Annotation to bind SecurityContext to method parameter.

package org.springframework.security.core.annotation;

import java.lang.annotation.*;

@Target({ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CurrentSecurityContext {
    /**
     * Whether to return null when SecurityContext is empty (default: false).
     */
    boolean errorOnInvalidType() default false;
    
    /**
     * SpEL expression to extract a property from SecurityContext.
     */
    String expression() default "";
}

Spring MVC Integration

CsrfRequestDataValueProcessor

RequestDataValueProcessor that automatically adds CSRF tokens to forms.

package org.springframework.security.web.servlet.support.csrf;

import java.util.Map;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.web.servlet.support.RequestDataValueProcessor;

public final class CsrfRequestDataValueProcessor implements RequestDataValueProcessor {
    /**
     * Creates a CSRF request data value processor.
     */
    public CsrfRequestDataValueProcessor();

    /**
     * Processes action URLs.
     *
     * @param request the HTTP request
     * @param action the form action URL
     * @param httpMethod the HTTP method
     * @return the processed action URL
     */
    public String processAction(HttpServletRequest request, String action, String httpMethod);

    /**
     * Processes form field values.
     *
     * @param request the HTTP request
     * @param name the field name
     * @param value the field value
     * @param type the input type
     * @return the processed value
     */
    public String processFormFieldValue(HttpServletRequest request, String name, String value, String type);

    /**
     * Returns extra hidden fields (CSRF token).
     *
     * @param request the HTTP request
     * @return map of hidden field names to values
     */
    public Map<String, String> getExtraHiddenFields(HttpServletRequest request);

    /**
     * Processes URLs.
     *
     * @param request the HTTP request
     * @param url the URL
     * @return the processed URL
     */
    public String processUrl(HttpServletRequest request, String url);
}

Jackson Integration

SecurityJackson2Modules

Provides Jackson modules for serializing Spring Security objects.

DEPRECATED: As of Spring Security 7.0, this class is deprecated for removal. Use org.springframework.security.jackson.SecurityJacksonModules (Jackson 3-based) instead.

package org.springframework.security.jackson2;

import com.fasterxml.jackson.databind.Module;
import java.util.List;

/**
 * @deprecated as of 7.0, use org.springframework.security.jackson.SecurityJacksonModules instead (Jackson 3-based)
 */
@Deprecated(forRemoval = true)
public class SecurityJackson2Modules {
    /**
     * Returns all security Jackson modules.
     *
     * @param loader the class loader
     * @return list of Jackson modules
     */
    public static List<Module> getModules(ClassLoader loader);
}

WebServletJackson2Module

Jackson module for web servlet security objects.

package org.springframework.security.web.jackson2;

import com.fasterxml.jackson.databind.module.SimpleModule;

public class WebServletJackson2Module extends SimpleModule {
    public WebServletJackson2Module();
}

UI Filters

DefaultLoginPageGeneratingFilter

Generates a default login page when none is configured.

package org.springframework.security.web.authentication.ui;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.function.Function;

import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.web.filter.OncePerRequestFilter;

public class DefaultLoginPageGeneratingFilter extends OncePerRequestFilter {
    public static final String DEFAULT_LOGIN_PAGE_URL = "/login";
    public static final String ERROR_PARAMETER_NAME = "error";
    
    public DefaultLoginPageGeneratingFilter();
    
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException;
    
    /**
     * Sets the SecurityContextHolderStrategy.
     */
    public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy);
    
    /**
     * Sets a function to resolve hidden inputs (e.g., CSRF token).
     */
    public void setResolveHiddenInputs(Function<HttpServletRequest, Map<String, String>> resolveHiddenInputs);
    
    /**
     * Sets a function to resolve custom headers.
     */
    public void setResolveHeaders(Function<HttpServletRequest, Map<String, String>> resolveHeaders);
    
    /**
     * Returns whether this filter is enabled.
     */
    public boolean isEnabled();
    
    public void setLogoutSuccessUrl(String logoutSuccessUrl);
    
    public void setLoginPageUrl(String loginPageUrl);
    
    public void setFailureUrl(String failureUrl);
    
    public void setFormLoginEnabled(boolean formLoginEnabled);
    
    public void setOauth2LoginEnabled(boolean oauth2LoginEnabled);
    
    public void setSaml2LoginEnabled(boolean saml2LoginEnabled);
}

DefaultLogoutPageGeneratingFilter

Generates a default logout page.

package org.springframework.security.web.authentication.ui;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.function.Function;

import org.springframework.web.filter.OncePerRequestFilter;

public class DefaultLogoutPageGeneratingFilter extends OncePerRequestFilter {
    public DefaultLogoutPageGeneratingFilter();
    
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException;
    
    /**
     * Sets a function to resolve hidden inputs (e.g., CSRF token).
     */
    public void setResolveHiddenInputs(Function<HttpServletRequest, Map<String, String>> resolveHiddenInputs);
}

Usage Examples

Using @AuthenticationPrincipal

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    
    @GetMapping("/api/user/profile")
    public UserProfile getProfile(@AuthenticationPrincipal UserDetails user) {
        return userService.getProfile(user.getUsername());
    }
    
    @GetMapping("/api/user/email")
    public String getEmail(@AuthenticationPrincipal(expression = "email") String email) {
        return email;
    }
    
    @GetMapping("/api/user/custom")
    public CustomUser getCustomUser(@AuthenticationPrincipal CustomUserDetails customUser) {
        return customUser.toCustomUser();
    }
}

Using @CurrentSecurityContext

import org.springframework.security.core.annotation.CurrentSecurityContext;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SecurityController {
    
    @GetMapping("/api/security/context")
    public Map<String, Object> getSecurityInfo(
            @CurrentSecurityContext SecurityContext securityContext) {
        
        Authentication auth = securityContext.getAuthentication();
        
        return Map.of(
            "username", auth.getName(),
            "authorities", auth.getAuthorities(),
            "authenticated", auth.isAuthenticated()
        );
    }
    
    @GetMapping("/api/security/username")
    public String getUsername(
            @CurrentSecurityContext(expression = "authentication.name") String username) {
        return username;
    }
}

Servlet API Integration

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ServletIntegrationController {
    
    @GetMapping("/api/servlet/info")
    public Map<String, Object> getServletInfo(HttpServletRequest request) {
        // Using standard Servlet API methods with Spring Security integration
        return Map.of(
            "remoteUser", request.getRemoteUser(),
            "userPrincipal", request.getUserPrincipal().getName(),
            "isAdmin", request.isUserInRole("ADMIN"),
            "isUser", request.isUserInRole("USER"),
            "authType", request.getAuthType()
        );
    }
}

Custom Argument Resolver

import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new AuthenticationPrincipalArgumentResolver());
        resolvers.add(new CurrentSecurityContextArgumentResolver());
    }
}