我们可以将 httpbasic 和 OAuth2 都用于 API 吗,具体取决于路径变量?



在我的应用程序中,我只想为某些特定的API调用提供OAuth2安全性。我的问题是我可以根据路径变量提供 HttpBasic 或 Oauth2 身份验证吗?

以下是我将考虑的两种情况。

1(假设对于用户(其名称在路径变量中提供(xyz,如果xyz没有OAuth的功能,我想使用httpBasic对其进行身份验证

2(如果另一个用户abc具有OAuth功能,我想使用Oauth/OpenId connect对其进行身份验证。

我有一个为用户分配功能的表格,下面是表格的一瞥。

名称、功能

xyz, HttpBasic

ABC, 奥特

好的,我自己做了一些研究,能够找到解决方案。这是我所做的,

- 使用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

具有相同资源的 Oauth2 或 Http-Basic 身份验证的 Spring 安全性

最新更新