Yellown
Yellown

Reputation: 506

Spring Boot AuthenticationToken with path variable

i have a PreAuthenticatedProcessingFilter with a custom AuthenticationManager where i do my authentication and create a AuthenticationToken. I now need to access a path variable (eg. id of "/foo/{id}") and use that for my authentication. How can i access the variable? If i use .antMatchers("/foo/{id}").access("@demo.check(authentication,#id)"); for example i cant create my own token.

my current code is:

    MyAuthFilter filter = MyAuthFilter();
    filter.setAuthenticationManager(new AuthenticationManager() {

        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            // ... authentication stuff
            // here i want to access the path variable
            return new MyAuthenticationToken(foo);
        }
    });
    httpSecurity.antMatcher("/foo/**").csrf().disable().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().addFilter(filter).authorizeRequests().anyRequest().authenticated();

Update

i am now checking everything inside the access expression (you can access the HttpServletRequest there and have the path variables as parameter). I did not want to have logic in the controller or check the raw path. So this works fine for me now:

httpSecurity.antMatcher("/foo/**").csrf().disable().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
            .antMatchers("/foo/test/{testId}/**")
            .access("@fooApiGuard.check(authentication, #testId)");

@Service
public class FooApiGuard {

    @Autowired
    private HttpServletRequest request;

    public boolean check(Authentication authentication, Long testId) throws AuthenticationException {
        // check stuff
        return true;
    }
}

Upvotes: 1

Views: 1280

Answers (1)

user268396
user268396

Reputation: 11976

Spring Security is built as a Filter chain, which means that inside your custom filter or AuthenticationManager you do not have quite the same context as inside the controller method itself. In fact, your custom filter is supposed to augment the context which will be used down the line by your controller.

What you do have access to is the ServletRequest and ServletResponse objects, so if you must you could extract the raw path from that. However, that doesn't give you the nicely separated out request parameter.

If the path parameter is only necessary to determine whether or not someone is authorized then you could simplify your authentication logic and then subsequently augment your controller with additional security checks to validate e.g. domain level security concerns (does the resource belong to the current user).

Upvotes: 1

Related Questions