Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security fullyAuthenticated() and hasRole("ADMIN")

I want to secure my application so that some URLs are accessible to anybody fully authenthicated and admin URL to be accessible to admin user, fully authenticated as well.

But right now, I can't manage to find a way to use fullyAuthenticaded() AND hasrole() together.

@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .requestMatchers()
            .antMatchers("/api/**", "/health")
            .and()
        .authorizeRequests()
            .antMatchers("/health").permitAll()
            .and()
        .authorizeRequests()
            .antMatchers("/api/get-data").fullyAuthenticated()
            .and()
        .authorizeRequests()
            .anyRequest().hasRole("ADMIN");
}
like image 864
Leamas Avatar asked Oct 17 '22 21:10

Leamas


1 Answers

You can write something like this:

antMatchers("/api/get-data").access("isFullyAuthenticated() and hasRole('ROLE_BANNED')")

This is like you are writing the access when you define in xml file. Its same thing here.

Now you can define some url for one antMatches with only isFullyAuthenticated and some url for another antMatches with admin role and isFullyAuthenticated.

For more clarification read this and this.

like image 88
SachinSarawgi Avatar answered Oct 21 '22 06:10

SachinSarawgi