java - Apache CXF 认证+spring 安全
问题描述
我想在基于 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);
}
}
弹簧安全配置:
@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 注释。
解决方案
您可以尝试使用 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 中找到完整的工作项目: repo
推荐阅读
- c# - 不使用 IUserType 查询数据库时如何防止 NHibernate SqlDateTime 溢出?
- html - 背景图像渐变淡出
- amazon-web-services - 使 Cloudfront 分发的缓存失效的问题
- angular - 从对象列表中删除重复项
- javascript - 复制一个文件,并重新计算新的状态
- reactjs - 在material-ui Tab容器中实现react hooks useState不起作用
- angular - 使用Angular动态添加和删除
- python - 使用 pytorch 对大图像进行补丁分类
- angular - 不可见的primeng日历
- html - 我无法对齐我的
右侧的 div 和 ; 我似乎也无法控制 twitter 嵌入的高度