【发布时间】:2021-12-12 06:48:12
【问题描述】:
我正在尝试熟悉 Spring Security,特别是从 Spring Security OAuth 迁移到 Soring Security(如以下示例/指南 https://github.com/spring-projects/spring-security/wiki/OAuth-2.0-Migration-Guide 中所示)。
但是,我似乎只收到 403 Forbidden 错误。我正在从 Postman 访问,并且正在使用我公司现有的 OAuth 服务器。我能够从身份验证服务器获取令牌,因此我知道我的凭据正确,并且我已经验证了 OAuth 用户的角色。
我正在使用以下依赖项:
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
implementation 'org.springframework.boot:spring-boot-starter-web'
这是我尝试访问的简单端点:
@RestController
public class AppController
{
@GetMapping("/hello")
public String hello()
{
return "hello";
}
}
这是我的 application.yml 文件:
spring:
security:
oauth2:
resourceserver:
jwt:
jwk-set-uri: <<company-website-here>>/uaa/oauth/token_keys
这是我的安全配置类:
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/hello").hasRole("MY_ROLE")
.anyRequest().authenticated()
.and()
.oauth2ResourceServer().jwt();
}
}
我似乎无法弄清楚为什么我似乎只收到 403 错误。我也尝试将@EnableWebSecurity 添加到安全配置类,但这并没有什么不同。将身份验证服务器 URL 显式添加到服务器和/或手动创建 JwtDecoder 也没有成功;似乎 url 是根据其属性名称自动从 yml 文件中提取的。
我正在尝试放弃使用 org.springframework.security.oauth.boot 依赖项和 ResourceServerConfigurerAdapter。
我必须像这样添加自己的转换器:
private static class JwtAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken>
{
private final Converter<Jwt, Collection<GrantedAuthority>> jwtGrantedAuthoritiesConverter;
public JwtAuthenticationConverter()
{
this.jwtGrantedAuthoritiesConverter = jwt -> jwt
.getClaimAsStringList("authorities")
.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
}
@Override
public final AbstractAuthenticationToken convert(@NonNull Jwt jwt)
{
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
return new JwtAuthenticationToken(jwt, authorities, jwt.getClaimAsString("client_id"));
}
}
然后必须将其添加到主安全配置中:
.jwtAuthenticationConverter(new JwtAuthenticationConverter());
【问题讨论】:
标签: java spring-boot spring-security