【发布时间】:2019-01-08 18:54:23
【问题描述】:
我的应用程序卡住了。这听起来很简单:我在我的 OAuth AuthorizationServer 上注册了两个客户端和两个用户。用户 alpha 可以访问这两个应用程序(“androidapp”和“angularapp”),但用户 beta 只能访问其中一个应用程序(仅“angularapp”)。如何区分用户并阻止“androidapp”应用的测试版?
这是我的 AuthServer 的代码:
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter{
@Autowired private DataSource dataSource;
@Autowired private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()")
;
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("angularapp")
.secret(passwordEncoder.encode("12345"))
.scopes("read", "write")
.authorizedGrantTypes("password", "refresh_token")
.accessTokenValiditySeconds(20000)
.refreshTokenValiditySeconds(20000)
.and()
.withClient("androidapp")
.secret(passwordEncoder.encode("67890"))
.scopes("read", "write")
.authorizedGrantTypes("password", "refresh_token")
.accessTokenValiditySeconds(20000)
.refreshTokenValiditySeconds(20000);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.authenticationManager(authenticationManager)
.tokenStore(tokenStore())
.accessTokenConverter(accessTokenConverter())
;
}
@Bean
public JwtTokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter jwt = new JwtAccessTokenConverter();
jwt.setSigningKey(JwtConfig.RSA_PRIVATE_KEY);
jwt.setVerifierKey(JwtConfig.RSA_PUBLIC_KEY);
return jwt;
}
}
提前感谢您的回答。
【问题讨论】:
-
一种选择是编写自己的
ClientDetailsService实现,例如,向loadClientByClientId()添加一些自定义授权逻辑。 -
这可以工作,但在那个级别我没有用户名来知道用户是否与该应用程序相关联......
-
您可以从安全上下文中获取用户名。
-
是的!你的想法有效,但反过来。执行
loadClientByClientId方法时,SecurityContext中存储的Principal对象尚不存在,但执行loadUserByUsername方法时确实存在,稍加观察:此时Principal对象包含client_id,而不是username,导致自定义UserDetailsService对象而不是ClientsDetailsService。然后,通过关系实体 (JPA),我加入了client_id和username,给出了预期的结果 -
嗯,当调用加载客户端方法时,主体还不存在,我觉得很奇怪。您是否保护了
/oauth/authorize端点?
标签: spring spring-boot spring-oauth2