一个应用程序中的Spring Security OAuth2和FormLogin

在我的Spring Boot应用程序中,我具有用于管理的RESTful API和MVC Web仪表板。

是否可以在一个应用程序中同时具有RESTful API的Spring Security OAuth2身份验证/授权(基于令牌,无状态)和Spring MVC

Web仪表板的FormLogin(有状态)?

如何使用Spring Boot正确配置它?

回答:

您需要为基于表单的登录和“资源服务器安全性”表单REST端点配置Web安全性

这是一个工作配置,该配置使用单点登录并单独部署了Authorization Server。

@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;

}

}

以上是 一个应用程序中的Spring Security OAuth2和FormLogin 的全部内容, 来源链接: utcz.com/qa/434654.html

回到顶部