我試圖讓自己熟悉 Spring Security,特別是從 Spring Security OAuth 遷移到 Soring Security(如下例/指南https://github.com/spring-projects/spring-security/wiki/OAuth-2.0-遷移指南)。
但是,我似乎只收到 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());
uj5u.com熱心網友回復:
可能會發生一些事情。
當您遷移到 Spring Security 5 時,您可能需要手動提取您的權限。檢查這個帖子,它是正確的答案。
您正在使用hasRole函式,這將在您的權限/角色之前附加“ROLE_”。因此,如果您的 JWT 令牌上的角色不是 ROLE_JWT_ROLE,您應該使用 hasTransaction。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/339655.html
上一篇:允許根據用戶的角色訪問控制器。所有這些都出現403錯誤
下一篇:如何將LocalDateTimeyyyy-MM-ddHH:mm格式化為dd-MM-yyyyHH:mm作為字串,以獲取不僅包含日期屬性的物件的整個串列?
