簡體   English   中英

Apache CXF身份驗證+ Spring安全性

[英]Apache CXF authentication + spring security

我想在基於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 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/**")
          .permitAll()
        ;
    }
}

如果我在配置中使用allowAll(),那么所有請求都會通過,但是注釋不起作用。 如果我使用authenticated(),那么在我的驗證程序運行之前,我會收到“訪問被拒絕”的信息。

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

您可以嘗試使用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();
  }    

}    

您可以在我的倉庫中找到完整的工作項目: 倉庫

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM