我有一个配置了工作安全性的spring项目,我想做的是设置一条特定的路径,该路径仅使用基本的用户/密码身份验证即可接受REST调用,并且可以进行硬编码。
我知道这是一个奇怪的情况,但是我有一个非常具体的用例。
安全代码类似于:
service->readCharacteristic(dev.m_readCharacteristic);
qDebug()<<"Data read: "<<dev.m_readCharacteristic.value();
我不太了解spring是如何发挥所有魔力的,但是我希望它看起来像这样:
@Override
public void configure(HttpSecurity http) throws Exception {
http
...
.and()
.authorizeRequests()
.antMatchers("my-path/**").authenticated()
}
必须发生的两件事:
答案 0 :(得分:0)
好吧,所以我做了一些破解(受this answer的启发),但是它为我解决了这个问题。
首先,我创建了这个AuthenticationProvider
:
public class ClusterInternalAuthenticationProvider implements AuthenticationProvider {
public static final String USER = "...";
public static final String PASSWORD = "...";
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken)authentication;
Object principal = token.getPrincipal();
Object credentials = token.getCredentials();
if (principal.equals(USER) && credentials.equals(PASSWORD)) {
return new UsernamePasswordAuthenticationToken(
principal,
credentials,
Collections.singletonList(new SimpleGrantedAuthority("RELEVANT_AUTHORITY"))
);
}
throw new BadCredentialsException("Sorry mate, wrong credentials...");
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.isAssignableFrom(UsernamePasswordAuthenticationToken.class);
}
}
这将尝试user / pswd组合,如果为true,则返回具有访问特定路径所需的权限的凭据。
接下来,在SecurityConfiguration中,启用httpBasic
并添加我的AuthenticationProvider
:
@Override
public void configure(HttpSecurity http) throws Exception {
http
...
.and()
.authorizeRequests()
.antMatchers("my-path/**").hasAuthority("RELEVANT_AUTHORITY")
.and()
.httpBasic()
.and()
.authenticationProvider(new ClusterInternalAuthenticationProvider());
}
这似乎是足够的,但就我需要确保不要在其他地方使用此权限的意义而言,这不是一个“正确”的解决方案,并且对于如此小的需求似乎显得过分了-非常欢迎其他解决方案。 / p>