Roles hierarchy not working after upgrading to spring security 6 - spring

I am upgrading from spring boot 2.7.x to 3.0.0. After doing changes as recommended in the official docs I found that my role hierarchies are not being honored.
I added expressionHandler() to my code as suggested in AccessDecisionVoter Deprecated with Spring Security 6.x but it doesn't work.
Any ideas what am I missing?
#Configuration
#EnableWebSecurity
public class WebSecurityConfig {
#Bean
public SecurityFilterChain configure(
HttpSecurity http,
RequestHeaderAuthenticationFilter headerAuthenticationFilter) throws Exception {
HttpStatusEntryPoint authenticationEntryPoint =
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
http
.addFilterAfter(headerAuthenticationFilter, RequestHeaderAuthenticationFilter.class)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/actuator/**", "/", "/webjars/**").permitAll()
.requestMatchers(HttpMethod.POST).hasRole("SUPERUSER")
.requestMatchers(HttpMethod.GET).hasRole("USER"))
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling(ex -> ex
.authenticationEntryPoint(authenticationEntryPoint)
.accessDeniedHandler(accessDeniedHandler()))
.csrf(customizer -> customizer.disable());
return http.build();
}
#Bean
public RequestHeaderAuthenticationFilter headerAuthenticationFilter(
...
}
#Bean
public RoleHierarchy roleHierarchy() {
RoleHierarchyImpl r = new RoleHierarchyImpl();
r.setHierarchy("ROLE_SUPERUSER > ROLE_USER");
return r;
}
#Bean
public DefaultWebSecurityExpressionHandler expressionHandler() {
DefaultWebSecurityExpressionHandler expressionHandler = new DefaultWebSecurityExpressionHandler();
expressionHandler.setRoleHierarchy(roleHierarchy());
return expressionHandler;
}

AuthorityAuthorizationManager is not exposed as a bean. Indeed it is a final class with private constructor. So in order to use my role hierarchy I need to create manually the AuthorityAuthorizationManager.
This worked using spring boot 3.0.0 and spring security 6.0.0
#Bean
public SecurityFilterChain configure(
HttpSecurity http,
RequestHeaderAuthenticationFilter headerAuthenticationFilter) throws Exception {
var auth1 = AuthorityAuthorizationManager.<RequestAuthorizationContext>hasRole("USER");
auth1.setRoleHierarchy(roleHierarchy());
http
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET).access(auth1)
);
return http.build();
}
#Bean
public RoleHierarchy roleHierarchy() {
RoleHierarchyImpl r = new RoleHierarchyImpl();
r.setHierarchy("ROLE_SUPERUSER > ROLE_USER");
return r;
}

Related

Spring Boot 3 security cannot access H2 console - 403

I'm in the process of re-learning Spring security in Spring Boot 3. Things changed a little and for some reason the same settings working for WebSecurityConfigurerAdapter's config method will not work in SecurityFilterChain.
HERE IS SOME CODE FROM PREVIOUS SETUPS- WORKING
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final AppUserService userService;
private final PasswordEncoder bCryptPasswordEncoder;
public SecurityConfig(AppUserService userService, PasswordEncoder bCryptPasswordEncoder) {
this.userService = userService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
private static final String[] SWAGGER = {
"/v2/api-docs",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**",
"/v3/api-docs/**",
"/swagger-ui/**"
};
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.cors(c -> {
CorsConfigurationSource cs = request -> {
CorsConfiguration cc = new CorsConfiguration();
cc.setAllowedOrigins(List.of("*"));
cc.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
cc.setAllowedHeaders(List.of("Origin", "Content-Type", "X-Auth-Token", "Access-Control-Expose-Header",
"Authorization"));
cc.addExposedHeader("Authorization");
cc.addExposedHeader("User-Name");
return cc;
};
c.configurationSource(cs);
});
http.headers().frameOptions().disable();
http.sessionManagement().sessionCreationPolicy(STATELESS);
http.authorizeRequests().antMatchers("/login/**").permitAll();
http.authorizeRequests().antMatchers("/h2-console/**").permitAll();
http.authorizeRequests().antMatchers(SWAGGER).permitAll();
http.authorizeRequests().antMatchers("/users/password-reset-request").permitAll();
http.authorizeRequests().antMatchers("/users/password-change").permitAll();
http.authorizeRequests().antMatchers("/users/**").hasAnyAuthority("ADMIN");
http.authorizeRequests().antMatchers("/favorites/**").hasAnyAuthority("USER");
http.authorizeRequests().antMatchers(GET).hasAnyAuthority("USER");
http.authorizeRequests().antMatchers(POST).hasAnyAuthority("USER");
http.authorizeRequests().antMatchers(PUT).hasAnyAuthority("USER");
http.authorizeRequests().antMatchers(DELETE).hasAnyAuthority("MODERATOR");
http.authorizeRequests().anyRequest().authenticated();
http.addFilter(new CustomAuthenticationFilter(authenticationManager()));
http.addFilterBefore(new CustomAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder);
}
#Override
protected UserDetailsService userDetailsService() {
return userService;
}
}
NOW SINCE
WebSecurityConfigurerAdapter
is no longer available:
#Configuration
#EnableWebSecurity
#RequiredArgsConstructor
public class SecurityConfig {
private final JwtAuthenticationFilter jwtAuthenticationFilter;
private final AuthenticationProvider authenticationProvider;
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().disable();
http.sessionManagement().sessionCreationPolicy(STATELESS);
http.authorizeHttpRequests().requestMatchers("/h2-console/**").permitAll();
http.authorizeHttpRequests().requestMatchers("/auth/**").permitAll();
http.authorizeHttpRequests().anyRequest().authenticated();
http.authenticationProvider(authenticationProvider);
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
Long story short- previously working
http.headers().frameOptions().disable();
http.authorizeRequests().antMatchers("/h2-console/**").permitAll();
Will not work as
http.headers().frameOptions().disable();
http.authorizeHttpRequests().requestMatchers("/h2-console/**").permitAll();
Application.properties for H2 database are exact same, copied. I didn't changed default url for H2. It seems its the Spring Security standing in the way.
Please advice what to do.
Do you have any knowlage if anything changed for H2 setup since previous Spring Boot?
EDIT: If I simply http.authorizeHttpRequests().anyRequest().permitAll();, the console will work. It must be security related
The H2ConsoleAutoConfiguration will register a Servlet for H2's Web Console, therefore, the servletPath property is needed in order to use the MvcRequestMatcher, like so:
#Bean
public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospector introspector) {
// ...
MvcRequestMatcher h2RequestMatcher = new MvcRequestMatcher(introspector, "/**");
h2RequestMatcher.setServletPath("/h2-console");
http.authorizeHttpRequests((authorize) -> authorize
.requestMatchers(h2RequestMatcher).permitAll()
// ...
);
}
In summary, we are permitting every (/**) request under the h2-console servlet path.
Another option is to use PathRequest.toH2Console() as shown in the Spring Boot H2 Console's documentation, which in turn will create an AntPathRequestMatcher for you.
#Bean
public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospector introspector) {
// ...
http.authorizeHttpRequests((authorize) -> authorize
.requestMatchers(PathRequest.toH2Console()).permitAll()
// ...
);
}
This problem has also been answered in the project's repository

Spring Security Active Directory Authentication - infinite login pop-up

I am using Spring Boot (2.7.2) security. My security config is:
public class WebSecurityConfig {
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().fullyAuthenticated().and().httpBasic();
return http.build();
}
#Bean
public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(
"company.com", "ldap://ldap-company.com:389");
provider.setSearchFilter("(&(objectClass=user)(sAMAccountName={0}))");
provider.setConvertSubErrorCodesToExceptions(true);
provider.setUseAuthenticationRequestCredentials(true);
return provider;
}
}
Now when I hit my URI I keep getting the login pop-up infinitely.
The username and password I am providing is correct. No error(s) at the console whatsoever.
What am I doing wrong here or missing?
While I am still waiting for the right answer, I got the idea from here and it works.
So this is what I ended up with:
public class WebSecurityConfig extends GlobalAuthenticationConfigurerAdapter {
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated()
// .fullyAuthenticated()
.and().httpBasic();
return http.build();
}
#Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(
"ldap://ldap-company.com:389/dc=company,dc=com");
contextSource.setUserDn("CN=MYBindUser,OU=Ldap,dc=COMPANY,dc=com");
contextSource.setPassword("ComplexP#ssw0rd");
contextSource.setReferral("follow");
contextSource.afterPropertiesSet();
LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder> ldapAuthenticationProviderConfigurer = auth
.ldapAuthentication();
ldapAuthenticationProviderConfigurer
.userSearchFilter("(&(cn={0}))")
// .userSearchFilter("(sAMAccountName=%s)")
.userSearchBase("")
// .groupSearchBase("(&(objectCategory=group)(cn={0}))")
.contextSource(contextSource);
}
}
Now my HTTPBasic Authentication with ActiveDirectory LDAP works just fine.

Spring auth server code grant returns 401 unauthorized for endpoint /oauth2/authorize via Postman

Using the spring auth server dependency 0.3.0:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-authorization-server</artifactId>
<version>0.3.0</version>
</dependency>
I got these two config files:
#Configuration
#ComponentScan(basePackageClasses = AuthorizationServerConfig.class)
#Import(OAuth2AuthorizationServerConfiguration.class)
public class AuthorizationServerConfig {
private final RegisteredClientProvider registeredClientProvider;
#Autowired
public AuthorizationServerConfig(RegisteredClientProvider registeredClientProvider) {
this.registeredClientProvider = registeredClientProvider;
}
#Bean
#Order(Ordered.HIGHEST_PRECEDENCE)
public SecurityFilterChain authServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
return http.formLogin(Customizer.withDefaults()).build();
}
#Bean
#ConditionalOnMissingBean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient codeClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("code-auth-client")
.clientSecret("{noop}secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("http://127.0.0.1:8080/redirect/")
.scope("read-access")
.build();
return new InMemoryRegisteredClientRepository(codeClient);
}
}
__
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
#EnableWebSecurity
public class SpringSecurityConfiguration {
#Bean
public InMemoryUserDetailsManager userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
#Bean
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
http.authorizeRequests(authorizeRequests ->
authorizeRequests.anyRequest().authenticated()
)
.formLogin(withDefaults());
return http.build();
}
}
I use the folloing parameters to fetch the authorization code in order to trade it for the token itself:
Unfortunately the application responses with 401 unauthorized:
GET
http://localhost:9000/oauth2/authorize?response_type=code&state=&client_id=code-auth-client&scope=read-access&redirect_uri=http%3A%2F%2F127.0.0.1%3A8080%2Fredirect%2F 401
I tried to fix it in the SecurityFilterChain beans but I couldn't fix it so far. Basically I am using this example https://www.baeldung.com/spring-security-oauth-auth-server (without the clients tho).
EDIT: I've noticed that the parameter "grant_type=authorization_code" was missing. Appending that parameter did not work tho.
Removing #Import(OAuth2AuthorizationServerConfiguration.class) fixed the issue.

After implementing Spring Session Management Spring security keeps forwarding me to the login page

I am working on JEE application. We recently switched from container based security to spring security. I am now trying move session handling out of the container and into the application using spring-session-jdbc. I've created the required tables in our database and created the following SessionConfig file:
#Configuration
#EnableJdbcHttpSession
public class SessionConfig extends AbstractHttpSessionApplicationInitializer {
#Bean
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:jboss/MyDS");
bean.setProxyInterface(DataSource.class);
bean.setLookupOnStartup(false);
bean.afterPropertiesSet();
return (DataSource) bean.getObject();
}
#Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
#Bean
public FindByIndexNameSessionRepository<?> sessionRepository(PlatformTransactionManager txManager,
DataSource dataSource) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
TransactionTemplate txTemplate = new TransactionTemplate(txManager);
return new JdbcIndexedSessionRepository(jdbcTemplate, txTemplate);
}
}
We have a security config where I autowire the the sessionRepository and use it to create the SessionAuthenticationStrategy like:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final Logger log = LoggerFactory.getLogger(SecurityConfig.class);
#Autowired
public FindByIndexNameSessionRepository<?> repo;
#Override
public void configure(WebSecurity web) throws Exception {
// put all static resource or external urls here
web.ignoring().antMatchers("/external/**", "/react/**", "/images/**", "/js/**", "/css/**",
"/vendor/**", "/fonts/**");
}
#Override
protected void configure(final HttpSecurity http) throws Exception {
String maxSessions =
GenericPropertiesReader.getInstance().getValue("config.logins.max.sessions");
http.sessionManagement()// set the session management
.sessionAuthenticationStrategy(sessionAuthenticationStrategy())
.invalidSessionUrl("/login.html") // no user session forward here
.maximumSessions(Integer.valueOf(maxSessions))// 1 or -1 for unlimited
.maxSessionsPreventsLogin(false)// new session will terminate old session and forward them
// to the log in page
.expiredUrl("/login.html?type=expired-session");
http.headers().frameOptions().disable();
http.authorizeRequests()// put any antMatchers after this
.antMatchers("/login.html").permitAll() // permit any login page
.anyRequest().authenticated().and().formLogin() // we are using form login
.loginPage("/login.html") // show our custom login form
.loginProcessingUrl("/login") // post to Spring's action URL so our custom auth provider is invoked
.successHandler(successHandler()).failureHandler(failureHandler())
.permitAll() // so anyone can see it
.and().logout().logoutUrl("/logout")
.logoutSuccessHandler(new MyLogoutSuccessHandler())// our custom logout handler
.invalidateHttpSession(true) // delete session, need more work??
.deleteCookies("JSESSIONID") // and get rid of that cookie so they can't auto-login again
.permitAll()
.and().x509().x509AuthenticationFilter(this.x509AuthFilter());
}
#Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(x509AuthProvider()).authenticationProvider(loginAuthProvider());
}
#Bean
public PreAuthenticatedAuthenticationProvider x509AuthProvider() {
PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
provider.setPreAuthenticatedUserDetailsService(x509PreAuthUserDetailsService());
return provider;
}
#Bean // this irks me.
public AuthenticationManager myAuthenticationManager() throws Exception {
return this.authenticationManager();
}
#Bean
X509AuthenticationFilter x509AuthFilter() throws Exception {
X509AuthenticationFilter filter = new X509AuthenticationFilter();
filter.setAuthenticationSuccessHandler(x509SuccessHandler());
filter.setPrincipalExtractor(x509Extractor());
filter.setAuthenticationManager(this.myAuthenticationManager());
filter.setAuthenticationFailureHandler(failureHandler());
return filter;
}
#Bean
public X509PrincipalExtractor x509Extractor() {
return new MyX509DodIdExtractor();
}
#Bean
public MyX509PreAuthUserDetailsService x509PreAuthUserDetailsService() {
return new MyX509PreAuthUserDetailsService();
}
#Bean
public MyAuthenticationProvider loginAuthProvider() {
return new MyAuthenticationProvider ();
}
#Bean
MyAuthenticationSuccessHandler x509SuccessHandler() {
MyAuthenticationSuccessHandler handler = new MyAuthenticationSuccessHandler ();
handler.setForwardResonse(false);
return handler;
}
#Bean
public MyAuthenticationSuccessHandler successHandler() {
return new MyAuthenticationSuccessHandler();
}
#Bean
public MyAuthenticationFailureHandler failureHandler() {
MyAuthenticationFailureHandler failureHandler = new MyAuthenticationFailureHandler();
failureHandler.setExceptionMappings(LoginFailures.exceptionMap());
failureHandler.setDefaultFailureUrl("/login.html?login-failure=" + LoginFailures.DEFAULT.code);
return failureHandler;
}
#Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
#Bean
public SpringSessionBackedSessionRegistry<? extends Session> sessionRegistry()
throws IllegalArgumentException, NamingException {
return new SpringSessionBackedSessionRegistry<>(repo);
}
#Bean
public SessionAuthenticationStrategy sessionAuthenticationStrategy()
throws IllegalArgumentException, NamingException {
ConcurrentSessionControlAuthenticationStrategy sessionAuthenticationStrategy =
new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry());
return sessionAuthenticationStrategy;
}
}
I see the session tables in the database being filled when attempting to login. I never hit any of the authentication code when debugging. I just am redirected to the login page every time.
I feel like I must be missing something obvious. I was getting errors that there was no unique bean of type FindByIndexNameSessionRepository<?> until I changed the name of the bean in SessionConfig to sessionRepository. Which makes me think there's another bean of that type being instantiated by Spring (not in our code base) that might be interfering?

Roles Hierarchy in Spring Webflux Security

I have implemented Webflux security by implementing:
ReactiveUserDetailsService
ReactiveAuthenticationManager
ServerSecurityContextRepository
Now, I am trying to introduce RoleHierarchy following the docs here: Role Hierarchy Docs
I have a user with role USER but he is getting 403 Denied on hitting a controller annotated with GUEST role. Role hierarchy is: "ROLE_ADMIN > ROLE_USER ROLE_USER > ROLE_GUEST"
#Configuration
#EnableWebFluxSecurity
#EnableReactiveMethodSecurity
public class SecurityConfig {
private final DaoAuthenticationManager reactiveAuthenticationManager;
private final SecurityContextRepository securityContextRepository;
private static final String ROLE_HIERARCHIES = "ROLE_ADMIN > ROLE_USER ROLE_USER > ROLE_GUEST";
#Autowired
public SecurityConfig(DaoAuthenticationManager reactiveAuthenticationManager,
SecurityContextRepository securityContextRepository) {
this.reactiveAuthenticationManager = reactiveAuthenticationManager;
this.securityContextRepository = securityContextRepository;
}
#Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.authenticationManager(reactiveAuthenticationManager)
.securityContextRepository(securityContextRepository)
.authorizeExchange()
.anyExchange().permitAll()
.and()
.logout().disable()
.build();
}
#Bean(name = "roleHierarchy")
public RoleHierarchy roleHierarchy() {
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
roleHierarchy.setHierarchy(ROLE_HIERARCHIES);
return roleHierarchy;
}
#Bean(name = "roleVoter")
public RoleVoter roleVoter() {
return new RoleHierarchyVoter(roleHierarchy());
}
}
#Component
public class DaoAuthenticationManager implements ReactiveAuthenticationManager {
private final DaoUserDetailsService userDetailsService;
private final Scheduler scheduler;
#Autowired
public DaoAuthenticationManager(DaoUserDetailsService userDetailsService,
Scheduler scheduler) {
Assert.notNull(userDetailsService, "userDetailsService cannot be null");
this.userDetailsService = userDetailsService;
this.scheduler = scheduler;
}
#Override
public Mono<Authentication> authenticate(Authentication authentication) {
final String username = authentication.getName();
return this.userDetailsService.findByUsername(username)
.publishOn(this.scheduler)
.switchIfEmpty(
Mono.defer(() -> Mono.error(new UsernameNotFoundException("Invalid Username"))))
.map(u -> new UsernamePasswordAuthenticationToken(u, u.getPassword(),
u.getAuthorities()));
}
}
#Component
public class SecurityContextRepository implements ServerSecurityContextRepository {
private final DaoAuthenticationManager authenticationManager;
#Autowired
public SecurityContextRepository(DaoAuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
#Override
public Mono<Void> save(ServerWebExchange swe, SecurityContext sc) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public Mono<SecurityContext> load(ServerWebExchange swe) {
ServerHttpRequest request = swe.getRequest();
if (request.getHeaders().containsKey("userName") &&
!Objects.requireNonNull(request.getHeaders().get("userName")).isEmpty()) {
String userName = Objects.requireNonNull(swe
.getRequest()
.getHeaders()
.get("userName")).get(0);
Authentication auth = new UsernamePasswordAuthenticationToken(userName,
Security.PASSWORD);
return this.authenticationManager.authenticate(auth).map(SecurityContextImpl::new);
} else {
return Mono.empty();
}
}
}
Anyway to get the role hierarchy thing working in Webflux security.
EDIT
Controller:
#GetMapping
#PreAuthorize("hasRole('USER')")
public Mono<Device> getDevice(#RequestParam String uuid) {
return deviceService.getDevice(uuid);
}
Normal role authorization is working for me, whats not working is the hierarchy part.
Here a very naive solution by overriding DefaultMethodSecurityExpressionHandler.
I supposed you annotated your controller with this king of expression : #PreAuthorize("hasRole('ROLE_USER')")
securityConfig.java
#Configuration
#EnableWebFluxSecurity
#EnableReactiveMethodSecurity
public class SecurityConfig {
private final DaoAuthenticationManager reactiveAuthenticationManager;
private final SecurityContextRepository securityContextRepository;
private static final String ROLE_HIERARCHY = "ROLE_ADMIN > ROLE_USER ROLE_USER > ROLE_GUEST";
#Autowired
public SecurityConfig(DaoAuthenticationManager reactiveAuthenticationManager,
SecurityContextRepository securityContextRepository) {
this.reactiveAuthenticationManager = reactiveAuthenticationManager;
this.securityContextRepository = securityContextRepository;
}
#Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.authenticationManager(reactiveAuthenticationManager)
.securityContextRepository(securityContextRepository)
.authorizeExchange()
.anyExchange().permitAll()
.and()
.logout().disable()
.build();
}
#Bean
public RoleHierarchy roleHierarchy() {
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
roleHierarchy.setHierarchy(ROLE_HIERARCHY);
return roleHierarchy;
}
// Overriding spring default bean
#Bean
public DefaultMethodSecurityExpressionHandler methodSecurityExpressionHandler(RoleHierarchy roleHierarchy) {
DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
handler.setRoleHierarchy(roleHierarchy);
return handler;
}
}
Then you have to authorize spring bean overriding by modifying your application property file:
application.properties
spring.main.allow-bean-definition-overriding=true
Sources : issue 1 issue role hierarchy doc
Going a little bit further... This part can be optimized and cleaner.
Using url patterns setup from ServerHttpSecurity object.
Note that the following setup won't use role hierarchy :
#Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.authenticationManager(reactiveAuthenticationManager)
.securityContextRepository(securityContextRepository)
.authorizeExchange()
.pathMatchers("/user/**").hasRole("ROLE_USER") // This won't use role hierarchy because it will use implemention of hasRole defined in your 'reactiveAuthenticationManager'
.anyExchange().permitAll()
.and()
.logout().disable()
.build();
}
A solution could be to create your own implementation of ReactiveAuthorizationManager and overriding check method in order to call access(...) from your http object (ServerHttpSecurity). Ie :
public class CustomReactiveAuthorizationManager<T> implements ReactiveAuthorizationManager<T> {
private final static Logger logger = LoggerFactory.getLogger(CustomReactiveAuthorizationManager.class);
private final RoleHierarchyVoter roleHierarchyVoter;
private final String authority;
CustomReactiveAuthorizationManager(String role, RoleHierarchy roleHierarchy) {
this.authority = ROLE_PREFIX + role;
this.roleHierarchyVoter = new RoleHierarchyVoter(roleHierarchy);
}
#Override
public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, T object) {
return authentication
.map(a -> {
ConfigAttribute ca = (ConfigAttribute) () -> authority;
int voteResult = roleHierarchyVoter.vote(a, object, Collections.singletonList(ca));
boolean isAuthorized = voteResult == AccessDecisionVoter.ACCESS_GRANTED;
return new AuthorizationDecision(isAuthorized);
})
.defaultIfEmpty(new AuthorizationDecision(false))
.doOnError(error -> logger.error("An error occured voting decision", error));
}
}
and then calling access method :
#Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http, RoleHierarchy roleHierarchy() {
return http
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.authenticationManager(reactiveAuthenticationManager)
.securityContextRepository(securityContextRepository)
.authorizeExchange()
.pathMatchers("/user/**").access(new CustomReactiveAuthorizationManager<>("USER", roleHierarchy))
.anyExchange().permitAll()
.and()
.logout().disable()
.build();
}
One way I was able to achieve role hierarchy in Webflux was by creating custom annotations.
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
#PreAuthorize("hasRole('ADMIN')")
public #interface IsAdmin {
}
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
#PreAuthorize("hasAnyRole('ADMIN', 'USER')")
public #interface IsUser {
}
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
#PreAuthorize("hasAnyRole('ADMIN', 'USER', 'GUEST')")
public #interface IsGuest {
}
–––––––––––––––––
And annotating the controllers like this:
#GetMapping
#IsUser
public Mono<Device> getDevice(#RequestParam String uuid) {
return deviceService.getDevice(uuid);
}
#PostMapping
#IsAdmin
#ResponseStatus(HttpStatus.CREATED)
public Mono<Device> createDevice(#Valid #RequestBody Device device) {
return deviceService.createDevice(device);
}

Resources