Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deny access to all URLs by default?

When defining new spring boot REST resources, I tend to forget to also create a spring security configuration for their url patterns.

How can I, by default, deny access to all URLs, and only allow access to explicitly configured URL patterns? (I am using .hasRole for to allow access) I want to avoid as many unintended security holes as possible.

Let's say I have three REST resources: /jobs, /desks and /salary. My current code might look like this:

http.authorizeRequests()

    .antMatchers(HttpMethod.GET, "/jobs")
    .hasRole("my_user")

    .antMatchers(HttpMethod.GET, "/desks")
    .hasRole("my_user");

But currently, access to url /salary is provided to everyone (because it is not yet configured)!

like image 399
slartidan Avatar asked Jul 17 '18 15:07

slartidan


2 Answers

Spring's Expression-Based Access Control has a denyAll expression which always evaluates to false.

So what you can do is use this denyAll method to deny access to everything, and then perhaps allow access to a certain URL(s) via hasRole:

http.authorizeRequests().antMatchers("/admin/**").access("hasRole('ADMIN')").antMatchers("/**").denyAll();

So for example, this will allow users with ADMIN access to access any page starting with /admin. And then it will deny access to all other pages. Note that the order is important as if you put in .antMatchers("/**").denyAll() first, it will deny all access and ignore the rest of your expression.

Or alternatively, you could use permitAll() for a certain URL pattern:

http.authorizeRequests().antMatchers("/users/**").permitAll().antMatchers("/**").denyAll();

Just to note that you might need to allow access to some way of logging in too, so the system can let someone log in with a specific role, so to combine it all together, and allow everyone to try login, only admin users to access the admin page(s) and deny all others, then something like:

http.authorizeRequests().antMatchers("/login").permitAll().antMatchers("/admin/**").access("hasRole('ADMIN')").antMatchers("/**").denyAll();
like image 173
achAmháin Avatar answered Nov 07 '22 23:11

achAmháin


You can deny all requests by default with: .anyRequest().denyAll() and explicit allow requests with .hasRole

like image 21
max Avatar answered Nov 08 '22 01:11

max