java – 我们可以根据路径变量使用httpbasic和OAuth2作为API吗?
作者:互联网
在我的应用程序中,我想仅为某些特定的API调用提供OAuth2安全性.我的问题是我可以根据路径变量提供HttpBasic或Oauth2身份验证吗?
以下是我将考虑的两种情况.
1)让我们说用户(其名称在路径变量中提供)xyz,如果xyz没有OAuth的功能,我想使用httpBasic进行身份验证
2)如果另一个用户abc具有OAuth功能,我想使用Oauth / OpenId connect对其进行身份验证.
我有一个表为用户分配功能,下面是表的一瞥.
名称,功能
xyz,HttpBasic
abc,Oauth
解决方法:
好吧,我自己做了一些研究,能够找到解决方案.这就是我做的,
– 使用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
标签:jhipster,java,spring-boot,spring-security,oauth-2-0 来源: https://codeday.me/bug/20190910/1799953.html