gpt4 book ai didi

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

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

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

是否可以在一个应用程序中同时拥有用于 RESTful API 的 Spring Security OAuth2 身份验证/授权(基于 token ,无状态)和用于 Spring MVC Web 仪表板的 FormLogin(有状态)?

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

最佳答案

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

这是一个工作配置,它使用单点登录和单独部署的授权服务器。

@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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32153226/

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