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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Security for Rest

Spring Security for Rest

Want to learn more about how you can enable Spring Security for Rest and a simple GET endpoint? Click here to learn more.

Saurabh Sharma user avatar by
Saurabh Sharma
CORE ·
Nov. 09, 18 · Tutorial
Like (6)
Save
Tweet
Share
14.28K Views

Join the DZone community and get the full member experience.

Join For Free

My last blog talked about exposing a simple GET endpoint. In this article, I will try to protect that same endpoint using an LDAP-backed IdP via the Spring framework.

Spring Security aims to operate in a self container manner. There is no need to place any special configuration files into your Java Runtime Environment.

Authentication and Access Control

The application security is about two main components:

  1. Authentication: Establishing who you are
  2. Authorization: Authorities you have to perform

As per the Spring Security architecture, the main strategy interface for authentication is the AuthenticationManager.

The most commonly used implementation of AuthenticationManager is ProviderManager, which delegates to a chain of AuthenticationProvider instances.

The first thing to add is the dependency in your POM.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
  <groupId>org.springframework.ldap</groupId>
  <artifactId>spring-ldap-core</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-ldap</artifactId>
</dependency>


This will be followed by creating a new class SecurityEnforcer in the com.samarthya.security package that will act as a Spring Security configuration enabler and extend the WebSecurityConfigurerAdapter. This class allows customization by overriding the methods required.

@Configuration
public class SecurityEnforcer extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.ldapAuthentication()
                .userDnPatterns("ou=User,ou=Engineering,ou=system")
                .groupSearchBase("ou=Group")
                .userSearchFilter("uid={0}")
                .contextSource()
                .url("ldap://myldapmachine.samarthya.com:10389/ou=Engineering,ou=system")
                .managerPassword("secureldappassword")
                .managerDn("uid=admin,ou=system");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
       http.authorizeRequests().anyRequest().authenticated().and().formLogin();
    }
}


What Is This Class Doing?

Line 1: @Configuration marks the class processed by the Spring Container to generate definitions.

Line 4: This defines an overridden function that configures and builds the AuthenticationBuilder. This is required for authentication. It enables building a local AuthenticationManager, which is a child of the global one. It is connecting to a local LDAP (Apache DS) instance that I have posted on one of my machines.

Image title

Line 16: This defines the authorization pattern that will ensure the GET endpoint is exposed and protected and demand the FORM login whenever visited.

We are done enabling the security. Now, it is time to test it. Once you execute your Spring Boot application, you can check the logs. You will see multiple entries trying to fetch the LDAP information beforehand.

main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello],methods=[GET]}" onto com.samarthya.model.MessageModel com.samarthya


The mapping is defined.

[main] s.s.l.DefaultSpringSecurityContextSource :  URL 'ldap://myldapmachine.samarthya.com:10389/ou=Engineering,ou=system', root DN is 'ou=Engineering,ou=system'


Next, we need to set up the context.

[main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@48581a3b, org.springframework.security.web.context.SecurityContextPersistenceFilter@51d0ec6f, org.springframework.security.web.header.HeaderWriterFilter@3a38f122, org.springframework.security.web.csrf.CsrfFilter@48268eec, org.springframework.security.web.authentication.logout.LogoutFilter@2e7af36e, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@310a7859, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@1ac6dd3d, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@1e12a5a6, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@7bbcf6f0, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@531ec978, org.springframework.security.web.session.SessionManagementFilter@1c628f6a, org.springframework.security.web.access.ExceptionTranslationFilter@3cc053, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@739265f1]


Lastly, we need to create the filter, and finally:

[main] com.samarthya.ServicesApplication        : Started ServicesApplication in 2.606 seconds (JVM running for 3.478)


Spring Framework Spring Security

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Upgrade Guide To Spring Data Elasticsearch 5.0
  • Educating the Next Generation of Cloud Engineers With Google Cloud
  • AIOps Being Powered by Robotic Data Automation
  • How To Convert HTML to PNG in Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: