Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Security for Rest

DZone's Guide to

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.

· Security Zone ·
Free Resource

Discover how to provide active runtime protection for your web applications from known and unknown vulnerabilities including Remote Code Execution Attacks.

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)


Find out how Waratek’s award-winning application security platform can improve the security of your new and legacy applications and platforms with no false positives, code changes or slowing your application.

Topics:
spring ,security ,ldap authentication

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}