gpt4 book ai didi

spring-security - Spring Boot with Security OAuth2 - 如何使用带有 Web 登录表单的资源服务器?

转载 作者:行者123 更新时间:2023-12-03 23:31:59 25 4
gpt4 key购买 nike

我有 Spring Boot (1.2.1.RELEASE) 服务于 的应用程序OAuth2 (2.0.6.RELEASE) 授权和资源服务器在一个应用程序实例中。它使用自定义 UserDetailsService使用 MongoTemplate 的实现在 MongoDB 中搜索用户。使用 grant_type=password 进行身份验证在 /oauth/token像魅力一样工作,以及 Authorization: Bearer {token} 的授权请求特定资源时的 header 。
现在我想向服务器添加简单的 OAuth 确认对话框,这样我就可以进行身份​​验证和授权,例如Swagger UI 在 api-docs 中调用 protected 资源。这是我到目前为止所做的:

@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 登录表单和 header 中的 OAuth2 授权 token )。如果 ResourceServer获得更高的优先级,然后 OAuth2 token 授权工作,但我无法使用 Web 表单登录。另一方面,如果我将更高的优先级设置为 LoginConfig类,然后 OAuth2 token 授权停止工作。
案例研究:登录表单有效,OAuth2 token 授权无效
我发现在这种情况下,问题是由未注册的 OAuth2AuthenticationProcessingFilter 引起的。 .我尝试在 ResourceServer.configure(HttpSecurity http) 中手动注册它方法,但它不起作用 - 我可以在 FilterChain 列表中看到过滤器,但它没有被触发。这不是修复它的好方法,因为在 ResourceServer 初始化期间还做了很多其他的魔法,所以我转向了第二种情况。
案例研究:登录表单不起作用,OAuth2 token 授权起作用
在这种情况下,主要问题是默认情况下 UsernamePasswordAuthenticationFilter找不到正确配置的 AuthenticationProvider实例(在 ProviderManager 中)。当我尝试通过以下方式手动添加它时:
http.authenticationProvide(daoAuthenticationProvider())
它得到一个,但在这种情况下没有 AuthenticationEventPublisher已定义且成功的身份验证无法发布到其他组件。事实上,在下一次迭代中,它会被 AnonymousAuthenticationToken 取代。 .这就是为什么我尝试手动定义 AuthenticationManager DaoAuthenticationProvider 的实例里面:
@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 手动注入(inject)零件:
authFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
这里的问题是不能保证您拥有正确的实例集,因为有一个简单的 HashMap ( check it on GitHub) 用于存储特定的共享对象,并且可以随时更改。我试图将其设置为:
http.setSharedObject(AuthenticationManager.class, authenticationManager)
但在我到达正在阅读它的地方之前,它已经被默认实现所取代。我用调试器检查了它,看起来每个新过滤器都有一个新的身份验证管理器实例。
我的问题是:我做得对吗?如何在登录表单(OAuth2 对话框)工作的一个应用程序中集成资源服务器来设置授权服务器?也许它可以用一种不同的、更容易的方式来完成。如果有任何帮助,我将不胜感激。

最佳答案

这是问题的解决方案。看看这个示例Groovy类(class):

@Configuration
@EnableResourceServer
class ResourceServer extends ResourceServerConfigurerAdapter {

@Value('${oauth.resourceId}')
private String resourceId

@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
http.httpBasic().disable()

http.requestMatchers().antMatchers('/admin/**', '/uaa/**')
.and().authorizeRequests()
.antMatchers('/uaa/authenticated/**').authenticated()
.antMatchers('/uaa/register/**').permitAll()
.antMatchers('/uaa/activate/**').permitAll()
.antMatchers('/uaa/password/**').permitAll()
.antMatchers('/uaa/auth/**').permitAll()
.antMatchers('/uaa/account/**').hasAuthority('ADMIN')
.antMatchers('/admin/**').hasAuthority('ADMIN')
.anyRequest().authenticated()

http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
}

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(resourceId);
}
}

基本上,要与 Web 表单例份验证并行运行 OAuth2.0 身份验证,您必须将
http.requestMatchers().antMatchers('/path/1/**', '/path/2/**')

到配置类。我之前的配置错过了这个重要的部分,所以只有 OAuth2.0 参与了身份验证过程。

关于spring-security - Spring Boot with Security OAuth2 - 如何使用带有 Web 登录表单的资源服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28838530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com