ale*_*oid 4 spring spring-security spring-boot spring-security-oauth2
在我的 Spring Boot 应用程序中,我有 RESTful API 和 MVC Web 仪表板用于管理。
是否可以在一个应用程序中同时拥有用于 RESTful API 的 Spring Security OAuth2 身份验证/授权(基于令牌,无状态)和用于 Spring MVC Web 仪表板的 FormLogin(有状态)?
如何使用 Spring Boot 正确配置它?
小智 10
您需要为基于表单的登录和资源服务器安全表单 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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5203 次 |
| 最近记录: |