Spring security with Oauth2 or Http-Basic authentication for the same resource

前端 未结 8 1151
南方客
南方客 2021-01-30 09:07

I\'m attempting to implement an API with resources that are protected by either Oauth2 OR Http-Basic authentication.

When I load the WebSecurityConfigurerAdapter which a

8条回答
  •  抹茶落季
    2021-01-30 09:35

    This may be close to what you were looking for:

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(new OAuthRequestedMatcher())
        .authorizeRequests()
            .anyRequest().authenticated();
    }
    
    private static class OAuthRequestedMatcher implements RequestMatcher {
        @Override
        public boolean matches(HttpServletRequest request) {
            String auth = request.getHeader("Authorization");
            // Determine if the client request contained an OAuth Authorization
            return (auth != null) && auth.startsWith("Bearer");
        }
    }
    

    The only thing this doesn't provide is a way to "fall back" if the authentication isn't successful.

    To me, this approach makes sense. If a User is directly providing authentication to the request via Basic auth, then OAuth is not necessary. If the Client is the one acting, then we need this filter to step in and make sure the request is properly authenticated.

提交回复
热议问题