Social Media

Securing URLs using Spring Security

Typically when securing a URL you are looking to do one of the following –

  • Allow access to everyone to a given URL
  • Secure URL based on roles
  • Secure URL based on multiple roles
  • Secure URL based on IP Address

This post shows how to do this using spring security

Specifying URL’s

The most common approach to specifying a URL is through antMatcher’s

So if we want to secure –

http://www.example.com/static Open to everyone – css, javascript
http://www.example.com/register Open to everyone
http://www.example.com/login Open to everyone
http://www.example.com/user/ ROLE_USER or ROLE_ADMIN – User Area
http://www.example.com/admin/ ROLE_ADMIN only and restrict on IPADDRESS – Admin Area

We would simply use –

Or with multiple –

We also specify individual pages or directories –

Depending on the complexity of pattern you are securing you can also consider –

Securing the URL’s

The methods to secure URL’s are defined in AuthorizedUrl

The most common methods are –

  • authenticated() – This is the URL you want to protect, and requires the user to login
  • permitAll() – This is used for URL’s with no security applied for example css, javascript
  • hasRole(String role) – Restrict to single role. Note that the role will have “ROLE_” appended. So role=”ADMIN” has a comparison against “ROLE_ADMIN”. An alternatve is hasAuthority(String authority)
  • hasAnyRole(String… roles) – Allows multiple roles. An alternative is hasAnyAuthority(String… authorities)

Other useful methods are –

  • access(String attribute) – This method takes SPEL, so you can create more complex restrictions. For those who are interested a lot of the methods in  ExpressionUrlAuthorizationConfigurer.AuthorizedUrl ultimately call access with the required SPEL
  • hasIpAddress(String ipaddressExpression) – Restrict on IP address or subnet

Putting it all together

We can put this altogher and create a method like –

The key points are –

  • permitAll gives everyone access to a file or directory
  • hasRoles passes multiple roles
  • access for more compicated access

As a side note I am currently working on a project to automatically generate this configuration with my spring-security-generator

 

 

About the Author Martin Farrell

My name is Martin Farrell. I have almost 20 years Java experience. I specialize inthe Spring Framework and JEE. I’ve consulted to a range of businesses, and have provide Java and Spring mentoring and training. You can learn more at About

follow me on:

Leave a Comment: