在我的应用程序中,我只想为某些特定的API调用提供OAuth2安全性。我的问题是我可以基于path变量提供HttpBasic或Oauth2身份验证吗?
以下是我将要考虑的两种情况。
1)假设用户(在路径变量中提供了其名称)xyz,如果xyz不具有OAuth功能,我想使用httpBasic对其进行身份验证
2)如果另一个用户abc具有OAuth功能,我想使用Oauth/OpenId connect对其进行身份验证。
我有一个为用户分配功能的表,下面是该表的概览。
名称,特征
xyz,HttpBasic
abc,Oauth
最佳答案
好吧,我自己进行了一些研究,并找到了解决方案。这就是我所做的
-使用WebSecurityConfigurerAdapter创建了一个httpbasic配置,现在在任何拦截器开始执行任务之前,我已经创建了一个请求匹配器,它将检查授权 header 是Basic还是Bearer。
//By default this filter order is 100 and OAuth has filter order 3
@Order(2)
public class MicroserviceSecurityConfigurationHttpBasic extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().exceptionHandling()
.authenticationEntryPoint(customAccessDeniedHandler())
.and().headers().frameOptions().disable()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.requestMatcher(new BasicRequestMatcher())
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.and().httpBasic();
}
private class BasicRequestMatcher implements RequestMatcher {
@Override
public boolean matches(HttpServletRequest httpRequest) {
String auth = httpRequest.getHeader("Authorization");
String requestUri = httpRequest.getRequestURI();
//Fetching Identifier to provide OAuth Security to only specific urls
String identifier= requestUri.substring(requestUri.lastIndexOf("/") + 1, requestUri.length());
//Lets say for identifier ABC only, I want to secure it using OAuth2.0
if (auth != null && auth.startsWith("Basic") && identifier.equalsIgnoreCase("ABC")) {
auth=null;
}
//For ABC identifier this method will return null so then the authentication will be redirected to OAuth2.0 config.
return (auth != null && auth.startsWith("Basic"));
}
}
}
-在此之后,我使用ResourceServerConfigurerAdapter创建了OAuth2.0配置,下面是它的简要介绍。
//Default filter order=3 so this will be executed after WebSecurityConfigurerAdapter
public class MicroserviceSecurityConfiguration extends ResourceServerConfigurerAdapter {
...
//Here I am intercepting the same url but the config will look for bearer token only
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().exceptionHandling()
.and().headers().frameOptions().disable()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests()
.antMatchers("/api/**").authenticated();
}
}
引用:https://github.com/spring-projects/spring-security-oauth/issues/1024
Spring security with Oauth2 or Http-Basic authentication for the same resource