DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • MuleSoft OAuth 2.0 Provider: Password Grant Type
  • Is Spring AI Strong Enough for AI?
  • Spring OAuth Server: Authenticate User With user-details Service
  • Securing Your Applications With Spring Security

Trending

  • Unlocking Data with Language: Real-World Applications of Text-to-SQL Interfaces
  • Driving DevOps With Smart, Scalable Testing
  • Building an AI/ML Data Lake With Apache Iceberg
  • Dropwizard vs. Micronaut: Unpacking the Best Framework for Microservices
  1. DZone
  2. Coding
  3. Java
  4. Securing URLs Using Spring Security

Securing URLs Using Spring Security

Securing URLs using Spring Security is a pretty straight forward job. Read on to find out how to do it!

By 
Martin Farrell user avatar
Martin Farrell
·
Nov. 19, 16 · Tutorial
Likes (12)
Comment
Save
Tweet
Share
106.9K Views

Join the DZone community and get the full member experience.

Join For Free

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 URLs

The most common approach to specifying a URL is through antMatchers. 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:

.antMatchers("/register")

Or with multiple:

.antMatchers("/register","/login","/user","/admin")

We also specify individual pages or directories –

.antMatchers("register.html"); // Individual
.antMatchers("/admin/**"); // Directory


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

  • mvcMatcher.
  • requestMatcher.
  • regexMatcher.

Securing the URLs

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:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http
        .authorizeRequests()
           .antMatchers("/static","/register").permitAll()
           .antMatchers("/user/**").hasRoles("USER", "ADMIN") // can pass multiple roles
           .antMatchers("/admin/**").access("hasRole('ADMIN') and hasIpAddress('123.123.123.123')") // pass SPEL using access method
           .anyRequest().authenticated()
           .and()
       .formLogin()
           .loginUrl("/login")
           .permitAll();
    }

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.

Spring Security

Published at DZone with permission of Martin Farrell, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • MuleSoft OAuth 2.0 Provider: Password Grant Type
  • Is Spring AI Strong Enough for AI?
  • Spring OAuth Server: Authenticate User With user-details Service
  • Securing Your Applications With Spring Security

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!