java - 基于 JWT 声明的 Spring Security 5 填充权限
问题描述
正如我所见,Spring Security OAuth2.x 项目已移至 Spring Security 5.2.x。我尝试以新的方式实现授权和资源服务器。@PreAuthorize
除了一件事 -注释之外,一切都正常工作。当我尝试将其与标准一起使用时,@PreAuthorize("hasRole('ROLE_USER')")
我总是被禁止。我看到的Principal
是类型的对象org.springframework.security.oauth2.jwt.Jwt
无法解析权限,我不知道为什么。
org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken@44915f5f: Principal: org.springframework.security.oauth2.jwt.Jwt@2cfdbd3; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffffa64e: RemoteIpAddress: 172.19.0.1; SessionId: null; Granted Authorities: SCOPE_read, SCOPE_write
并在将其投射到Jwt
{user_name=user, scope=["read","write"], exp=2019-12-18T13:19:29Z, iat=2019-12-18T13:19:28Z, authorities=["ROLE_USER","READ_ONLY"], client_id=sampleClientId}
安全服务器配置
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Autowired
private AuthenticationManager authenticationManager;
@Bean
public KeyPair keyPair() {
ClassPathResource ksFile = new ClassPathResource("mytest.jks");
KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(ksFile, "mypass".toCharArray());
return keyStoreKeyFactory.getKeyPair("mytest");
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setKeyPair(keyPair());
return converter;
}
@Bean
public JWKSet jwkSet() {
RSAKey key = new Builder((RSAPublicKey) keyPair().getPublic()).build();
return new JWKSet(key);
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.tokenStore(tokenStore())
.accessTokenConverter(accessTokenConverter())
.authenticationManager(authenticationManager);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
security.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
}
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private UserDetailsService userDetailsService;
public SecurityConfiguration(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.mvcMatchers("/.well-known/jwks.json")
.permitAll()
.anyRequest()
.authenticated();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
}
资源服务器配置
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResuorceServerConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.oauth2ResourceServer()
.jwt();
}
}
也许有人有类似的问题?
解决方案
默认情况下,资源服务器根据"scope"
声明填充权限。
如果Jwt
包含一个名为"scope"
or的声明"scp"
,则 Spring Security 将使用该声明中的值通过为每个值添加前缀来构造权限"SCOPE_"
。
在您的示例中,其中一项声明是scope=["read","write"]
.
这意味着权限列表将由"SCOPE_read"
和组成"SCOPE_write"
。
您可以通过在安全配置中提供自定义身份验证转换器来修改默认权限映射行为。
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(getJwtAuthenticationConverter());
然后在您的实现中getJwtAuthenticationConverter
,您可以配置Jwt
映射到权限列表的方式。
Converter<Jwt, AbstractAuthenticationToken> getJwtAuthenticationConverter() {
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(jwt -> {
// custom logic
});
return converter;
}
推荐阅读
- css - CSS | 背景样式 - 固定在移动设备中不起作用
- matplotlib - 仅使用 plt.colorbar() 设置颜色条边界
- android - 如何动态添加带有图像视图的多个线性布局?
- lodash - 如何将 lodash sortBy 与自定义顺序比较器一起使用
- powerbi - PowerBI 条件
- php - 添加一个复选框以在 Woocommerce 中显示/隐藏结帐字段
- c - 哪些整数值被分配给一系列没有标识符的枚举?
- java - 使用 dateParam 进行 JSTL 查询
- c# - 当我将统一应用程序构建为独立应用程序时,所有着色器都吓坏了?闪烁多色?
- r - 是否有一个 R 函数来过滤一个数据框,其中保留了所有匹配值的列?