java - Spring Boot 。 HMAC 认证。如何添加自定义 AuthenticationProvider 和 Authentication 过滤器?

标签 java authentication spring-security spring-boot hmac

为了实现 HMAC 身份验证,我制作了自己的过滤器、提供程序和 token 。 休息安全过滤器:

public class RestSecurityFilter extends AbstractAuthenticationProcessingFilter {
private final Logger LOG = LoggerFactory.getLogger(RestSecurityFilter.class);

private AuthenticationManager authenticationManager;

public RestSecurityFilter(String defaultFilterProcessesUrl) {
    super(defaultFilterProcessesUrl);
}

public RestSecurityFilter(RequestMatcher requiresAuthenticationRequestMatcher) {
    super(requiresAuthenticationRequestMatcher);
}

@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    AuthenticationRequestWrapper request = new AuthenticationRequestWrapper(req);

    // Get authorization headers
    String signature = request.getHeader("Signature");
    String principal = request.getHeader("API-Key");
    String timestamp = request.getHeader("timestamp");
    if ((signature == null) || (principal == null) || (timestamp == null))
    unsuccessfulAuthentication(request, response, new BadHMACAuthRequestException("Authentication attempt failed! Request missing mandatory headers."));


    // a rest credential is composed by request data to sign and the signature
    RestCredentials credentials = new RestCredentials(HMACUtils.calculateContentToSign(request), signature);

    // Create an authentication token
    return new RestToken(principal, credentials, Long.parseLong(timestamp));
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    LOG.debug("Filter request: " + req.toString());
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    chain.doFilter(request, response);

    Authentication authResult;

    try {
        authResult = attemptAuthentication(request, response);
        if (authResult == null)
            unsuccessfulAuthentication(request, response, new BadHMACAuthRequestException("Authentication attempt failed !"));

    } catch (InternalAuthenticationServiceException failed) {
        LOG.error("An internal error occurred while trying to authenticate the user.", failed);
        unsuccessfulAuthentication(request, response, failed);
    } catch (AuthenticationException failed) {
        // Authentication failed
        unsuccessfulAuthentication(request, response, failed);
    }
}
}

身份验证提供者:

@Component
public class RestAuthenticationProvider implements AuthenticationProvider {
private final Logger LOG = LoggerFactory.getLogger(RestAuthenticationProvider.class);

private ApiKeysService apiKeysService;

@Autowired
public void setApiKeysService(ApiKeysService apiKeysService) {
    this.apiKeysService = apiKeysService;
}

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    RestToken restToken = (RestToken) authentication;

    // api key (aka username)
    String principal = restToken.getPrincipal();

    LOG.info("Authenticating api key: '" + principal + "'");

    // check request time, 60000 is one minute
    long interval = Clock.systemUTC().millis() - restToken.getTimestamp();
    if ((interval < 0) && (interval > 60000))
        throw new BadHMACAuthRequestException("Auth Failed: old request.");

    // hashed blob
    RestCredentials credentials = restToken.getCredentials();

    // get secret access key from api key
    ApiKey apiKey = apiKeysService.getKeyByName(principal).orElseThrow(() -> new NotFoundException("Key not found for: '" + principal + "'"));
    String secret = apiKey.getApiKey();

    // calculate the hmac of content with secret key
    String hmac = HMACUtils.calculateHMAC(secret, credentials.getRequestData());
    LOG.debug("Api Key '{}', calculated hmac '{}'");

    // check if signatures match
    if (!credentials.getSignature().equals(hmac)) {
        throw new BadHMACAuthRequestException("Auth Failed: invalid HMAC signature.");
    }

    return new RestToken(principal, credentials, restToken.getTimestamp(), apiKeysService.getPermissions(apiKey));
}

@Override
public boolean supports(Class<?> authentication) {
    return RestToken.class.equals(authentication);

}
}

我不知道如何配置 WebSecurityConfig 以使用我的过滤器和身份验证提供程序对每个请求进行身份验证。我假设我需要创建 @Bean 来初始化 RestSecurityFilterAbstractAuthenticationProcessingFilter 的 JavaDoc 也说我需要 authenticationManager 属性。我将不胜感激使用自定义过滤器、提供程序和 token 的工作解决方案。

最佳答案

我不熟悉 Spring Boot,但我看到了您对我的问题的评论 How To Inject AuthenticationManager using Java Configuration in a Custom Filter

在传统的 Spring Security XML 配置中,您将像这样指定自定义 RestSecurityFilter

<http use-expressions="true" create-session="stateless" authentication-manager-ref="authenticationManager" entry-point-ref="restAuthenticationEntryPoint">
       <custom-filter ref="restSecurityFilter" position="FORM_LOGIN_FILTER" />
</http>

更多信息 http://docs.spring.io/spring-security/site/docs/4.0.1.RELEASE/reference/htmlsingle/#ns-custom-filters

关于java - Spring Boot 。 HMAC 认证。如何添加自定义 AuthenticationProvider 和 Authentication 过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30502589/

相关文章:

java - 如何在具有许多字段的java中创建一个不可变的类?

java - 我可以根据枚举来限定注入(inject)吗?

java - 获取在 2D 平面上相互接触的对象的数量副本(Java 算法)

encryption - Ajax登录: Password Encryption

java - 如何在 Netbeans 中使用具有 SOAP 身份验证 header 的 .NET Web 服务

java - 如何在成功登录GWT Java后打开新页面

grails - 安装/卸载spring-security-eventlog-0.3

java - java中的迭代器 - 删除范围内的数字

grails - Grails安全插件

spring - 如何在 Spring Security 中编写自定义过滤器?