在我的Spring Boot应用程序中,我有RESTful API和MVC Web仪表板用于管理 .
是否可以在一个应用程序中为Spring MVC Web仪表板同时提供RESTful API的Spring Security OAuth2身份验证/授权(基于令牌,无状态)和FormLogin(有状态)?
如何使用Spring Boot正确配置它?
您需要为基于表单的登录和资源服务器安全性表单REST endpoints 配置Web安全性
以下是使用单点登录和单独部署的授权服务器的工作配置 .
@Configuration @EnableOAuth2Sso @EnableWebSecurity protected static class ResourceConfiguration extends WebSecurityConfigurerAdapter { @Value("${sso.url}") private String ssoUrl; @Autowired private RedisConnectionFactory redisConnectionFactory; @Bean protected TokenStore tokenStore() { return new RedisTokenStore(redisConnectionFactory); } @Bean @Primary protected ResourceServerTokenServices tokenServices() { DefaultTokenServices defaultTokenServices = new DefaultTokenServices(); defaultTokenServices.setTokenStore(tokenStore()); defaultTokenServices.setSupportRefreshToken(true); return defaultTokenServices; } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { OAuth2AuthenticationManager authenticationManager = new OAuth2AuthenticationManager(); authenticationManager.setTokenServices(tokenServices()); return authenticationManager; } @Override protected void configure(HttpSecurity http) throws Exception { http.requestMatchers() .and().authorizeRequests() .antMatchers("/").permitAll() .antMatchers(HttpMethod.GET, "/static/**").permitAll() .antMatchers(HttpMethod.GET, "/profile/**").permitAll() .antMatchers(HttpMethod.GET, "/services/**").permitAll() .anyRequest().authenticated() .and().logout() .invalidateHttpSession(true) .logoutSuccessUrl(ssoUrl+"/logout") .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .deleteCookies("JSESSIONID").invalidateHttpSession(true) .permitAll(); } } @Configuration @EnableResourceServer @Order(1) protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId("resource-id"); } @Override public void configure(HttpSecurity http) throws Exception { http.requestMatcher(new OAuthRequestedMatcher()) .authorizeRequests().anyRequest().fullyAuthenticated(); } } private static class OAuthRequestedMatcher implements RequestMatcher { public boolean matches(HttpServletRequest request) { String auth = request.getHeader("Authorization"); boolean haveOauth2Token = (auth != null) && auth.startsWith("Bearer"); boolean haveAccessToken = request.getParameter("access_token")!=null; return haveOauth2Token || haveAccessToken; } }
1 回答
您需要为基于表单的登录和资源服务器安全性表单REST endpoints 配置Web安全性
以下是使用单点登录和单独部署的授权服务器的工作配置 .