TL; DR:如何根据用户的access_token在资源服务器端(即没有JWT)分配用户自定义角色/权限?
整个故事:我有一个正在运行的Auth服务器和一个客户端(即SPA),可以从Auth服务器获取access_token。借助该access_token,客户端可以在我的资源服务器(与Auth服务器分离)上请求数据。资源服务器可以使用access_token从Auth服务器获取用户名。
我可以通过将Authentication对象注入到这样的方法中来访问代码中的用户名:
@RequestMapping("/ping")
fun pingPong(auth: Authentication): String = "pong, " + auth.name
Run Code Online (Sandbox Code Playgroud)
我的问题是如何auth.authorities向该对象添加我的自定义角色或权限(-仅USER_ROLE),该对象将根据用户名在资源服务器上而不是Auth服务器上进行管理。
我尝试了几种方法来做,但是没有一个帮助。最有希望的是:
@Configuration
@EnableWebSecurity
@EnableResourceServer
class ResourceServerConfigurer(val userDetailsService: MyUserDetailsService) : ResourceServerConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http.userDetailsService(userDetailsService) // userDetailsService is autowired
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests()
.antMatchers("/", "/index.html").permitAll()
.anyRequest().authenticated()
}
}
Run Code Online (Sandbox Code Playgroud)
和我的自定义UserDetailsService:
@Service
class UserDetailsService : org.springframework.security.core.userdetails.UserDetailsService {
override fun loadUserByUsername(username: String): UserDetails {
return org.springframework.security.core.userdetails.User(username, "password", getAuthorities(username))
}
private fun getAuthorities(user: String): Set<GrantedAuthority> {
val authorities = HashSet<GrantedAuthority>()
authorities.addAll(listOf(
SimpleGrantedAuthority("ROLE_ONE"), //let's …Run Code Online (Sandbox Code Playgroud)