- 角色由
JwtGrantedAuthoritiesConverter
类中的 convert
方法提供,方法如下
public Collection<GrantedAuthority> convert(Jwt jwt) {
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
for (String authority : getAuthorities(jwt)) {
grantedAuthorities.add(new SimpleGrantedAuthority(this.authorityPrefix + authority));
}
return grantedAuthorities;
}
- 由于
convert()
方法提供的角色默认是以 SCOPE_
开头,但 hasRole()
是以 ROLE_
开头,因此导致访问时无权限问题 - 自定义
JwtAuthenticationConverter
解决
@Bean
JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
JwtGrantedAuthoritiesConverter authoritiesConverter = new JwtGrantedAuthoritiesConverter();
authoritiesConverter.setAuthorityPrefix("ROLE_");
converter.setJwtGrantedAuthoritiesConverter(authoritiesConverter);
return converter;
}
- 在
configure
中添加 JwtAuthenticationConverter
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/db/**").hasAnyRole("db")
.antMatchers("/admin/**").hasAnyRole("admin")
.antMatchers("/user/**").hasAnyRole("user")
.anyRequest().authenticated()
.and()
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(jwtAuthenticationConverter())
.jwkSetUri("http://localhost:8080/oauth2/keys");
}