结合使用OAuth2和http基本身份验证Spring Security

时间:2019-09-24 08:58:31

标签: spring spring-boot spring-security oauth-2.0 spring-security-oauth2

我已经使用Spring Boot和Spring Security实现了OAuth2。现在,我有一组可用的API,我想为其使用不同的身份验证方法。例如,我想为/users/** API使用OAuth2,为/admin/** API使用Http Basic身份验证。

但是,OAuth2不适用于/admin/**,而HTTP basic不适用于/users/** API。

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

在Spring Security中,您可以具有多个处理不同请求的过滤器链。 因此,您可以使用一个处理对/ users / ** uri的请求,该请求将具有“基本身份验证”过滤器,而处理一个对/ admin / ** uri的请求的请求将具有Oauth2过滤器。要进行设置,您需要2个WebSecurityConfigurerAdapter实例

一个用于Oauth2

@Configuration
@Order(1)
public static class Oauth2ConfigurationAdapter extends WebSecurityConfigurerAdapter {

    protected void configure(HttpSecurity http) throws Exception {
       http.mvcMatcher("/user/**")
       ...... 

另外一个针对Basic:

@Configuration
@Order(2)
public static class BasicConfigurationAdapter extends WebSecurityConfigurerAdapter {

    protected void configure(HttpSecurity http) throws Exception {
       http.mvcMatcher("/admin/**")
       ...... 

本文对此进行了详细说明:https://www.baeldung.com/spring-security-multiple-entry-points

此代码还与/ admin的Digest auth和其他所有代码的Basic做了类似的事情。 https://github.com/wlesniak/spring-security-authn-authz-course/tree/master/module_2/mod2_crypto_portfolio_digest