Apache CXF身份验证+弹簧安全性

问题描述 投票:0回答:1

我想在基于Apache-CXF的SOAP应用程序中使用@RolesAllowed(或类似)注释。但我不明白如何为此配置Spring Security。

我想从SOAP消息中的XML头进行身份验证。

端点安全配置:

Map<String, Object> props = new HashMap<>();
props.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
props.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
endpoint.getInInterceptors().add(new WSS4JInInterceptor(props));

endpoint.getProperties().put("ws-security.validate.token", false);
endpoint.getProperties().put("ws-security.ut.no-callbacks", true);
endpoint.getProperties().put("ws-security.ut.validator", 
                             CredentialValidator.class.getName());

还尝试使用CallbackHandler。结果相同。

验证器:

public class CredentialValidator extends UsernameTokenValidator {
    @Override
    public Credential validate(Credential credential, RequestData data)
                  throws WSSecurityException {
        String userName = credential.getUsernametoken().getName();
        String password = credential.getUsernametoken().getPassword();

        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(Role.USER_ROLE));

        PreAuthenticatedAuthenticationToken token = new 
           PreAuthenticatedAuthenticationToken(
               userName, 
               password, 
               authorities);
        SecurityContextHolder.getContext().setAuthentication(token);
    }   
}

Spring安全配置:

@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
          .antMatchers(HttpMethod.POST, "/services/**")
          .permitAll()
        ;
    }
}

如果我在配置中使用permitAll(),则所有请求都会通过,但注释不起作用。如果我使用authenticated()然后在验证器工作之前得到“访问被拒绝”。

我在@WebService接口中使用@AllowedRoles注释。

java spring soap spring-security cxf
1个回答
0
投票

您可以尝试使用TokenFilter,而不是使用CredentialValidator。您的Spring Security配置应如下所示:

@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .antMatchers(HttpMethod.POST, "/services/**")
      .authenticated()
      .addFilterBefore(tokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
  }

@Bean
public TokenFilter tokenFilterBean() {
    return new TokenFilter();
  }    

}    

你可以在我的回购中找到完整的工作项目:repo

© www.soinside.com 2019 - 2024. All rights reserved.