I have 春季启动(1.2.1.RELEASE) 服务的应用程序OAuth2(2.0.6.RELEASE) 授权和资源服务器位于一个应用程序实例中。它使用自定义UserDetailsService
实现利用MongoTemplate
在 MongoDB 中搜索用户。身份验证用grant_type=password
on /oauth/token
就像魅力一样,以及授权Authorization: Bearer {token}
调用特定资源时的标头。
现在我想向服务器添加简单的 OAuth 确认对话框,以便我可以进行身份验证和授权,例如Swagger UI 在 api 文档中调用受保护的资源。这是我到目前为止所做的:
@Configuration
@SessionAttributes("authorizationRequest")
class OAuth2ServerConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.addViewController("/oauth/confirm_access").setViewName("authorize");
}
@Configuration
@Order(2)
protected static class LoginConfig extends WebSecurityConfigurerAdapter implements ApplicationEventPublisherAware {
@Autowired
UserDetailsService userDetailsService
@Autowired
PasswordEncoder passwordEncoder
ApplicationEventPublisher applicationEventPublisher
@Bean
DaoAuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider()
provider.passwordEncoder = passwordEncoder
provider.userDetailsService = userDetailsService
return provider
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.parentAuthenticationManager(authenticationManagerBean())
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder())
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
//return super.authenticationManagerBean()
ProviderManager providerManager = new ProviderManager([daoAuthenticationProvider()], super.authenticationManagerBean())
providerManager.setAuthenticationEventPublisher(new DefaultAuthenticationEventPublisher(applicationEventPublisher))
return providerManager
}
@Bean
public PasswordEncoder passwordEncoder() {
new BCryptPasswordEncoder(5)
}
}
@Configuration
@EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter {
@Value('${oauth.resourceId}')
private String resourceId
@Autowired
@Qualifier('authenticationManagerBean')
private AuthenticationManager authenticationManager
@Override
public void configure(HttpSecurity http) throws Exception {
http.setSharedObject(AuthenticationManager.class, authenticationManager)
http.csrf().disable()
http.httpBasic().disable()
http.formLogin().loginPage("/login").permitAll()
//http.authenticationProvider(daoAuthenticationProvider())
http.anonymous().and()
.authorizeRequests()
.antMatchers('/login/**').permitAll()
.antMatchers('/uaa/register/**').permitAll()
.antMatchers('/uaa/activate/**').permitAll()
.antMatchers('/uaa/password/**').permitAll()
.antMatchers('/uaa/account/**').hasAuthority('ADMIN')
.antMatchers('/api-docs/**').permitAll()
.antMatchers('/admin/**').hasAuthority('SUPERADMIN')
.anyRequest().authenticated()
//http.sessionManagement().sessionCreationPolicy(STATELESS)
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(resourceId)
resources.authenticationManager(authenticationManager)
}
}
@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Value('${oauth.clientId}')
private String clientId
@Value('${oauth.secret:}')
private String secret
@Value('${oauth.resourceId}')
private String resourceId
@Autowired
@Qualifier('authenticationManagerBean')
private AuthenticationManager authenticationManager
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
return new JwtAccessTokenConverter();
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.checkTokenAccess("permitAll()")
oauthServer.allowFormAuthenticationForClients()
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)
.accessTokenConverter(accessTokenConverter())
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient(clientId)
.secret(secret)
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
.authorities("USER", "ADMIN")
.scopes("read", "write", "trust")
.resourceIds(resourceId)
}
}
}
主要问题是我无法同时运行两者(Web 登录表单和标头中的 OAuth2 授权令牌)。如果ResourceServer
获得更高的优先级,然后 OAuth2 令牌授权有效,但我无法使用 Web 表单登录。另一方面,如果我将更高的优先级设置为LoginConfig
类,然后 OAuth2 令牌授权停止工作。
案例研究:登录表单有效,OAuth2 令牌授权无效
我发现在这种情况下问题是由未注册引起的OAuth2AuthenticationProcessingFilter
。我尝试手动注册它ResourceServer.configure(HttpSecurity http)
方法,但它不起作用 - 我可以在 FilterChain 列表上看到过滤器,但它没有被触发。这不是修复它的好方法,因为在 ResourceServer 初始化期间完成了很多其他魔法,所以我转向第二种情况。
案例研究:登录表单不起作用,OAuth2 令牌授权起作用
在这种情况下,主要问题是默认情况下UsernamePasswordAuthenticationFilter
找不到正确配置的AuthenticationProvider
实例(在ProviderManager
)。当我尝试通过以下方式手动添加它时:
http.authenticationProvide(daoAuthenticationProvider())
它得到一个,但在这种情况下没有AuthenticationEventPublisher
已定义且成功的身份验证无法发布到其他组件。事实上,在下一次迭代中,它被替换为AnonymousAuthenticationToken
。这就是为什么我尝试手动定义AuthenticationManager
实例与DaoAuthenticationProvider
inside:
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
//return super.authenticationManagerBean()
ProviderManager providerManager = new ProviderManager([daoAuthenticationProvider()], super.authenticationManagerBean())
providerManager.setAuthenticationEventPublisher(new DefaultAuthenticationEventPublisher(applicationEventPublisher))
return providerManager
}
我认为它会起作用,但是提供不同的问题AuthenticationManager
注册过滤器的实例。事实证明,每个过滤器都有authenticationManager
使用手动注入sharedObjects
成分:
authFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
这里的问题是你不能保证有一个正确的实例集,因为有一个简单的 HashMap (在 GitHub 上查看)用于存储特定的共享对象,并且可以随时更改。我尝试将其设置为:
http.setSharedObject(AuthenticationManager.class, authenticationManager)
但在我到达正在读取它的地方之前,它已经被默认实现替换了。我用调试器检查了它,看起来每个新过滤器都有一个新的身份验证管理器实例。
我的问题是:我做得正确吗?如何设置授权服务器,将资源服务器集成在一个应用程序中,并且登录表单(OAuth2 对话框)可以正常工作?也许可以用一种不同的、更简单的方式来完成。我将不胜感激任何帮助。