遗留Java Servlet/JSP应用OIDC认证拦截及非Spring Boot示例求助
I get it—you’re working with a legacy Java Servlet/JSP app and want to add OIDC authentication using Spring Security, but without Spring Boot (since most examples are Boot-focused). Let’s walk through a practical, XML-configured solution that mirrors the SAML approach you’re familiar with, wrapping your existing servlets with an authentication filter.
Step 1: Add Required Dependencies
First, include these Spring Security OIDC dependencies in your pom.xml (if using Maven):
<dependencies> <!-- Spring Security Web --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.8.1</version> <!-- Use latest compatible version --> </dependency> <!-- Spring Security Config --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.8.1</version> </dependency> <!-- Spring Security OAuth2 Client --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-oauth2-client</artifactId> <version>5.8.1</version> </dependency> <!-- Spring Security OAuth2 JOSE (for JWT handling) --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-oauth2-jose</artifactId> <version>5.8.1</version> </dependency> </dependencies>
Step 2: Configure web.xml to Wrap Your Existing Servlets
Just like with SAML, register the springSecurityFilterChain to intercept all incoming requests. This ensures every request goes through OIDC authentication before reaching your legacy servlets/JSPs.
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!-- Spring Security Filter Chain --> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Load Spring Security Configuration --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-security.xml</param-value> </context-param> <!-- Your existing servlet mappings go here --> <servlet> <servlet-name>YourLegacyServlet</servlet-name> <servlet-class>com.yourcompany.YourLegacyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>YourLegacyServlet</servlet-name> <url-pattern>/legacy/*</url-pattern> </servlet-mapping> </web-app>
Step 3: Spring Security OIDC Configuration (spring-security.xml)
This is where you’ll set up the OIDC client registration and security rules. We’ll use the OIDC provider’s issuer URI to auto-discover endpoints (authorization, token, user info) instead of hardcoding them.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <security:http auto-config="true"> <!-- Require authentication for all requests --> <security:intercept-url pattern="/**" access="authenticated"/> <!-- Enable OIDC Login --> <security:oauth2-login client-registration-id="your-oidc-client" login-page="/oauth2/authorization/your-oidc-client"/> <!-- Configure OIDC Logout (redirects to provider and back to your app) --> <security:logout logout-success-url="/" invalidate-session="true"/> </security:http> <!-- OIDC Client Registration --> <security:oauth2-client> <security:client-registrations> <security:registration id="your-oidc-client" client-id="YOUR_CLIENT_ID" client-secret="YOUR_CLIENT_SECRET" issuer-uri="https://your-oidc-provider.com/issuer" redirect-uri="{baseUrl}/login/oauth2/code/your-oidc-client" scope="openid,profile,email"/> </security:client-registrations> </security:oauth2-client> </beans>
Replace YOUR_CLIENT_ID, YOUR_CLIENT_SECRET, and https://your-oidc-provider.com/issuer with your actual OIDC provider details. Make sure the redirect-uri is registered in your provider’s console.
Step 4: Access Authenticated User Info in Your Legacy Servlet
Once authenticated, you can pull the user’s details from the Spring Security SecurityContext in any servlet/JSP:
package com.yourcompany; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.core.oidc.user.OidcUser; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/legacy/secure") public class YourLegacyServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); // Get authenticated OIDC user Authentication auth = SecurityContextHolder.getContext().getAuthentication(); OidcUser oidcUser = (OidcUser) auth.getPrincipal(); out.println("<h1>Welcome, " + oidcUser.getFullName() + "</h1>"); out.println("<p>Email: " + oidcUser.getEmail() + "</p>"); out.println("<p>Subject ID: " + oidcUser.getSubject() + "</p>"); // Access other claims as needed: oidcUser.getClaims().get("claim-name") } }
Key Notes
- OIDC Provider Setup: Double-check that your client ID/secret are correctly created in your provider (e.g., Okta, Auth0, Keycloak) and the redirect URI matches your config.
- Public Paths: If you have unprotected pages, add an
<security:intercept-url>withaccess="permitAll"(e.g.,<security:intercept-url pattern="/public/**" access="permitAll"/>). - Session Management: Spring Security handles session creation post-authentication, so your legacy app can use
HttpSessionas usual if needed.
内容的提问来源于stack exchange,提问作者wrschneider

