99.3. 身份验证
获取用于授权的安全凭证的过程不由此组件指定。您可以根据自己的需要编写您自己的处理器或组件,从交换中获取身份验证信息。例如,您可以创建一个处理器,从来自 Jetty 组件的 HTTP 请求标头获取凭证。无论如何收集凭据,都需要将它们放置在 Inmessage
或 SecurityContextHolder
中,以便 Camel Spring Security 组件可以访问它们。
import javax.security.auth.Subject; import org.apache.camel.*; import org.apache.commons.codec.binary.Base64; import org.springframework.security.authentication.*; public class MyAuthService implements Processor { public void process(Exchange exchange) throws Exception { // get the username and password from the HTTP header // http://en.wikipedia.org/wiki/Basic_access_authentication String userpass = new String(Base64.decodeBase64(exchange.getIn().getHeader("Authorization", String.class))); String[] tokens = userpass.split(":"); // create an Authentication object UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(tokens[0], tokens[1]); // wrap it in a Subject Subject subject = new Subject(); subject.getPrincipals().add(authToken); // place the Subject in the In message exchange.getIn().setHeader(Exchange.AUTHENTICATION, subject); // you could also do this if useThreadSecurityContext is set to true // SecurityContextHolder.getContext().setAuthentication(authToken); } }
如有必要,SpringSecurityAuthorizationPolicy
会自动验证 Authentication
对象。
请注意,当您使用 SecurityContextHolder
而不是 或 除了 Exchange.AUTHENTICATION
标头外,请注意这两个问题:
-
上下文拥有者使用 thread-local 变量来保存
Authentication
对象。任何跨线程边界的路由(如 seda 或 jms )都会丢失Authentication
对象。 Spring Security 系统要求上下文中的
Authentication
对象已经进行身份验证,并具有角色。如需了解更多详细信息,请参阅 Spring 技术概述,第 5.3.1 节:"Spring Security 中的身份验证是什么?"。
camel-spring-security 的默认行为是在 Exchange.AUTHENTICATION
标头中查找 Subject
。此主题必须至少包含一个主体,它必须是 org.springframework.security.core.Authentication
的子类。
您可以通过向 < authorizationPolicy
& gt
; bean 提供 org.apache.camel.component.spring.security.AuthenticationAdapter
的实现来自定义 Subject
到 Authentication 对象的映射。
如果您正在使用不使用 Spring Security 的组件,但不提供 Subject
,则这很有用。
目前,只有 CXF 组件会填充 Exchange.AUTHENTICATION
标头。