在我的应用程序中,我想仅为某些特定的API调用提供OAuth2安全性。我的问题是我可以根据路径变量提供HttpBasic或Oauth2身份验证吗?
以下是我将考虑的两种情况。
1)让我们说用户(其名称在路径变量中提供)xyz,如果xyz没有OAuth的功能,我想使用httpBasic验证它
2)如果另一个用户abc具有OAuth功能,我想使用Oauth / OpenId connect对其进行身份验证。
我有一个表格可以为用户分配功能,下面是表格的一瞥。
名称,功能
xyz,HttpBasic
abc,Oauth
答案 0 :(得分:2)
好的,我自己做了一些研究,并找到了解决方案。这就是我做的,
使用WebSecurityConfigurerAdapter处理一个httpbasic配置,现在在任何拦截器开始之前我创建了一个请求匹配器,它将检查授权头是基本还是承载。
//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