如何有单独的身份验证源? (一个用于 Oauth2,一个用于基于表单的登录)
Posted
技术标签:
【中文标题】如何有单独的身份验证源? (一个用于 Oauth2,一个用于基于表单的登录)【英文标题】:How to have separate authentication sources? (one for Oauth2 and one for form-based login) 【发布时间】:2016-03-13 15:36:26 【问题描述】:我正在编写一个具有链接到数据库的身份验证的小型应用程序,此身份验证将由 Oauth2 方面(由@EnableAuthorizationServer 和@EnableResourceServer 注释的类)管理。在同一个应用程序中还有另一个用于管理页面的身份验证,该页面将链接到另一个不同的数据库并使用正常的基于表单的身份验证。
我为此特定目的编写了以下网络安全配置类:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig
@Configuration
@Order(5)
public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter
@Override
protected void configure(HttpSecurity http) throws Exception
http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/admin_logout"))
.invalidateHttpSession(true).logoutSuccessUrl("/admin/login.html");
http.authorizeRequests()
.antMatchers("/admin/login.html").permitAll().antMatchers("/admin/protected.html")
.hasRole("ADMIN")
.and().formLogin().loginPage("/admin/login.html")
.loginProcessingUrl("/admin_login").defaultSuccessUrl("/admin/protected.html");
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception
//Data source for form based auth
auth.inMemoryAuthentication().withUser("adminuser").password("adminpassword").roles("ADMIN");
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
//Data source for Oauth
auth.inMemoryAuthentication().withUser("myuser").password("mypassword").roles("USER").and().withUser("test")
.password("testpassword").roles("USER");
其他相关组件有:
授权服务器配置:
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter
@Autowired
AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception
endpoints.authenticationManager(authenticationManager).tokenEnhancer(tokenEnhancer())
.tokenStore(tokenStore());
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception
clients
.inMemory()
.withClient("client")
.secret("secret")
.authorizedGrantTypes("password", "refresh_token")
.scopes("read", "write")
.resourceIds("resource").accessTokenValiditySeconds(60);
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception
oauthServer.checkTokenAccess("isAuthenticated()");
@Bean
public TokenEnhancer tokenEnhancer()
return new CustomTokenEnhancer();
@Bean
public TokenStore tokenStore()
return new InMemoryTokenStore();
资源服务器配置:
@Configuration
@EnableResourceServer
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER-1)
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter
@Autowired
TokenStore tokenStore;
@Override
public void configure(ResourceServerSecurityConfigurer resources)
resources.resourceId("resource").tokenStore(tokenStore);
@Override
public void configure(final HttpSecurity http) throws Exception
http.authorizeRequests().antMatchers("/api/**").authenticated();
您也可以在这里查看代码:https://github.com/cenobyte321/spring-oauth2-tokenenhancer-test/tree/webspeciallogin(分支:webspeciallogin)
问题是 AdminSecurityConfig 类中的所有内容都被忽略了,我可以在不登录的情况下进入 protected.html 页面,并且没有创建指定的登录和注销处理 url。
另一方面,基于 Oauth2 的登录可以正常工作。我还没有弄清楚如何在 Oauth2 中指定一个 AuthenticationManagerBuilder,大多数在线资源都建议使用 Oauth 适当读取的 configureGlobal 注入方法,这就是为什么它在上面的代码中设置的原因。
如何在一个启用 Oauth2 的应用程序中配置两个相互独立的身份验证源?
问候。
【问题讨论】:
【参考方案1】:你需要两件事:
-
确保您的
AdminSecurityConfig
的优先级高于您的ResourceServerConfiguration
。虽然 @EnableResourceServer
注释的文档说它将注册一个带有硬编码顺序 3 的 WebSecurityConfigurerAdapter
,但它实际上在 ResourceServerOrderProcessor
中被覆盖,顺序为 -10。因此,请确保您的 AdminSecurityConfig
的订单低于 -10。
确保使用请求匹配器将AdminSecurityConfig
中的HttpSecurity
配置限制为与管理服务器关联的URL,如下所示:
http.requestMatchers().antMatchers("/admin/**", "/admin_login", "/admin_logout")
.and()
.authorizeRequests()
.antMatchers("/admin/protected.html").hasRole("ADMIN")
.antMatchers("/admin/login.html").permitAll()
.and()
.formLogin().loginPage("/admin/login.html")
.loginProcessingUrl("/admin_login")
.defaultSuccessUrl("/admin/protected.html")
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/admin_logout"))
.invalidateHttpSession(true).logoutSuccessUrl("/admin/login.html")
;
注意嵌入代码的第一行带有http.requestMatchers().antMatchers("/admin/**", "/admin_login", "/admin_logout")
。
有关类似问题,请参阅 Dave Syer(Spring Security 的作者之一)answer 以供参考。
我在 github 上为您的示例项目创建了一个 pull request 并进行了上述修复。
【讨论】:
非常感谢,我也觉得资源服务器顺序是3。虽然你的pull request中现在确实保护了受保护的页面,但是我有一个奇怪的问题“ /admin_login" url 在提交表单后返回“出现意外错误 (type=Method Not Allowed, status=405). Request method 'POST' not supported”,即使此特定示例禁用了 CSRF 保护。 你是对的。我将HttpSecurity
的配置限制在AdminSecurityConfig
中,不包括用于登录处理的URL 模式/admin_login
。我已经更新了我的答案。再试一次,似乎成功了。
知道了,现在可以使用了。鉴于您应该限制这个单独的应用程序组件的所有路由,包括处理 url,因此也应该在此处添加“admin_logout”路由。非常感谢您的帮助!【参考方案2】:
您能否通过使用基于角色的授权以不同的方式解决问题?例如:
@Override
protected void configure(HttpSecurity http) throws Exception
http
.authorizeRequests()
....
.antMatchers("/user/manage/**").access("hasRole('SYS_ADMIN_ROLE')")
.antMatchers("/audit/**").access("hasRole('SYS_ADMIN_ROLE')")
.antMatchers("/upload**").access("hasRole('SYS_ADMIN_ROLE')")
另一种方法是自定义用户详细信息服务,它知道如何在适当的数据库中查找用户 ID:
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
LimitLoginAuthenticationProvider provider = (LimitLoginAuthenticationProvider)authenticationProvider;
provider.setPasswordEncoder(passwordEncoder);
auth.userDetailsService(customUserDetailsService()).passwordEncoder(passwordEncoder);
auth.authenticationProvider(authenticationProvider);
【讨论】:
以上是关于如何有单独的身份验证源? (一个用于 Oauth2,一个用于基于表单的登录)的主要内容,如果未能解决你的问题,请参考以下文章
Spring Security OAuth2:如何为两类用户提供两个单独的登录链接?
如何使用 oauth2 通过 REST Web 服务进行身份验证