324.3. 身份验证
获取用于授权的安全凭证的过程不由此组件指定。您可以根据自己的需要编写您自己的处理器或组件,从交换中获取身份验证信息。例如,您可以创建一个处理器,从源自 Jetty 组件的 HTTP 请求标头获取凭证。无论如何收集凭证,都需要将其放置在 In 消息或 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 对象已经被身份验证并具有角色(更多详情请参阅 Technical Overview 部分 5.3.1 )。
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 标头。