spring-projects / spring-security

Spring Security

Home Page:http://spring.io/projects/spring-security

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

authorizeHttpRequests requestMatchers should support both .authenticated and .access in the same config

abccbaandy opened this issue · comments

commented

Expected Behavior

        http.authorizeHttpRequests(matchers -> matchers
                .requestMatchers(
                        "/api/",
                        "/api/**"
                )
                .authenticated()
                .access(myAuthorizationManager)

Current Behavior
The code can not compile.
I can only choose on of the
.authenticated()
or
.access(myAuthorizationManager)

Context
What I want is when match /api url, spring security need do authn AND authz(call myAuthorizationManager).
But if I use .authenticated(), the myAuthorizationManager not called (below is my test code), and vice versa.

        http.authorizeHttpRequests(matchers -> matchers
                .requestMatchers(
                        "/api/",
                        "/api/**"
                )
                .authenticated()
                .anyRequest()
                .access(myAuthorizationManager)

Currently I can only do an extra check in myAuthorizationManager to verify the Authentication is not AnonymousAuthenticationToken which looks weird to me.

Hi @abccbaandy.

You can use

.requestMatchers("/api/", "/api/**").access(AuthorizationManagers.allOf(AuthenticatedAuthorizationManager.authenticated(), myOtherAuthorizationManager))

Does that work for you?

See https://docs.spring.io/spring-security/reference/servlet/authorization/authorize-http-requests.html#authorize-requests

commented

Thanks, it works.
I think this should be in the reference.

Thanks @abccbaandy. Would you like to send a PR that includes that information in the docs?