我具有带有一个自定义端点的oauth2授权服务器(以admin手动注销特定用户) 我希望使用其他客户端凭据(客户端ID和Secret作为基本编码的标头值)来保护此端点,类似于/ oauth / check_token。
只能从具有特定范围的资源服务器调用此端点。
我找不到用于使用Spring机制进行客户端身份验证检查的任何文档或方法。
编辑1
我使用Java配置而不是xml
答案 0 :(得分:0)
@PreAuthorize("#oauth2.hasScope('TEST_SCOPE')")
在控制器方法上应该足够。如果客户端未通过身份验证,则没有作用域可用,并且作用域检查将失败。
如果需要,可以使用Spring Security表达式@PreAuthorize("isAuthenticated()")
来检查客户端是否已通过身份验证:https://docs.spring.io/spring-security/site/docs/5.0.0.RELEASE/reference/htmlsingle/#el-common-built-in
您还可以配置HttpSecurity
而不是使用@PreAuthorize
答案 1 :(得分:0)
所以我得到了以下解决方案
身份验证管理器
.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.context.request.async.AsyncRequestTimeoutException]
过滤器声明
public class ClientAuthenticationManager implements AuthenticationManager {
private ClientDetailsService clientDetailsService;
private PasswordEncoder passwordEncoder;
public HGClientAuthenticationManager(ClientDetailsService clientDetailsService, PasswordEncoder passwordEncoder) {
Assert.notNull(clientDetailsService, "Given clientDetailsService must not be null!");
Assert.notNull(passwordEncoder, "Given passwordEncoder must not be null!");
this.clientDetailsService = clientDetailsService;
this.passwordEncoder = passwordEncoder;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
ClientDetails clientDetails = null;
try {
clientDetails = this.clientDetailsService.loadClientByClientId(authentication.getPrincipal().toString());
} catch (ClientRegistrationException e) {
throw new BadCredentialsException("Invalid client id or password");
}
if (!passwordEncoder.matches(authentication.getCredentials().toString(), clientDetails.getClientSecret())) {
throw new BadCredentialsException("Invalid client id or password");
}
return new OAuth2Authentication(
new OAuth2Request(null, clientDetails.getClientId(), clientDetails.getAuthorities(), true,
clientDetails.getScope(), clientDetails.getResourceIds(), null, null, null),
null);
}
}
过滤器注册
private BasicAuthenticationFilter basicAuthenticationFilter() {
ClientDetailsUserDetailsService clientDetailsUserDetailsService = new ClientDetailsUserDetailsService(
this.clientDetailsService);
clientDetailsUserDetailsService.setPasswordEncoder(this.passwordEncoder);
return new BasicAuthenticationFilter(
new ClientAuthenticationManager(this.clientDetailsService, this.passwordEncoder));
}
警告!!!
这将阻止任何其他类型的身份验证(oauth2等)。
仅 httpSecurity.addFilterBefore(this.basicAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
身份验证被接受,并且已注册客户端仅。