我正在使用 oauth2,并且我有一个授权服务器和一个(单独的)资源服务器。客户端从授权服务器获取令牌,然后使用该令牌向资源服务器发出请求。当资源服务器从授权服务器获取 SecurityContext 时,我想添加其他信息。目前它获取用户的用户名,我也想添加用户 ID。在授权服务器中,我有以下设置:
public org.springframework.security.core.userdetails.UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//... more logic in here
return new CurrentUser(user.getId(), user.getUsername(), user.getPassword(), true, true, true, true, grantedAuthorities);
}
其中 CurrentUser 定义如下:
public class CurrentUser extends org.springframework.security.core.userdetails.User {
private Long userId;
public CurrentUser(Long userId, String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
this.userId = userId;
}
}
在资源服务器中,我试图将主体转换为 CurrentUser,但主体只是一个字符串。好像没有发送。你知道我错过了什么吗?
Authentication a = SecurityContextHolder.getContext().getAuthentication();
CurrentUser user = (CurrentUser)a.getPrincipal(); //throws exception
资源服务器(一个单独的应用程序)配置如下:
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfiguration extends
ResourceServerConfigurerAdapter
{
private static final String RESOURCE_ID = "my_id";
@Override
public void configure(ResourceServerSecurityConfigurer resources)
{
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("...").access("...")
.and()
.exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}
在资源服务器的属性文件中,我有验证令牌的必要信息:
security.oauth2.resource.token-info-uri=http://localhost:8000/auth-service/oauth/check_token
security.oauth2.client.client-id = my-client
security.oauth2.client.client-secret = password