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 变量来保存 身份验证 对象。跨线程边界的任何路由(如 sedajms )都将丢失 Authentication 对象。其次,Spring Security 系统似乎已验证了 身份验证 对象,并且具有角色(请参阅 Technical Overview 部分 5.3.1 了解更多信息)。

camel-spring-security 的默认行为是在 Exchange.AUTHENTICATION 标头中查找对象。此对象必须至少包含一个主体,它必须是 org.springframework.security.core.Authentication 的子类。您可以通过提供 org.apache.camel.component.spring.security. Authentication Adapter to your < authorizationPolicy > bean 来自定义 Subject to Authentication 对象的映射。如果您使用不使用 Spring Security 的组件,但确实提供 Subject,这很有用。目前,只有 CXF 组件会填充 Exchange.AUTHENTICATION 标头。