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

前端 未结 8 1188
南方客
南方客 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:36

    And why not doing this the other way round? Just bypass resource server if there is no token attached, then fallback to normal security filter chain. This is by the way what resource server filter is stopping on.

    @Configuration
    @EnableResourceServer
    class ResourceServerConfig : ResourceServerConfigurerAdapter() {
    
    
        @Throws(Exception::class)
        override fun configure(resources: ResourceServerSecurityConfigurer) {
            resources.resourceId("aaa")
        }
    
        /**
         * Resources exposed via oauth. As we are providing also local user interface they are also accessible from within.
         */
        @Throws(Exception::class)
        override fun configure(http: HttpSecurity) {
            http.requestMatcher(BearerAuthorizationHeaderMatcher())
                    .authorizeRequests()
                    .anyRequest()
                    .authenticated()
        }
    
        private class BearerAuthorizationHeaderMatcher : RequestMatcher {
            override fun matches(request: HttpServletRequest): Boolean {
                val auth = request.getHeader("Authorization")
                return auth != null && auth.startsWith("Bearer")
            }
        }
    
    }
    

提交回复
热议问题