Monday, 12 August 2019

Spring Security: Exclude public apis from authentication

In my previous post, I explained how to safe guard complete application using spring-secure project.

In any typical web application, there are public resources like home page, style sheets, java script files, images etc., we no need to safe guard these resources using spring-security.

How to exclude some resources from safe guarding?
By extending WebSecurityConfigurerAdapter class and overriding configure method, we can tell to spring security, which urls should be excluded and which should be safe guarded.
@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable().authorizeRequests().antMatchers("/", "/public/*", "/css/*", "/js/*").permitAll()
                .anyRequest().authenticated().and().httpBasic();

    }
}


Above snippet disable csrf security and exclude the urls /, "/public/*", "/css/*", "/js/*" from safe guarding and all other urls are safe guarded by basic authentication.

Find the below working application.

HelloWorldController.java    
package com.sample.app.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {
 @RequestMapping("/")
 public String homePage() {
  return "Welcome to Spring boot Application Development using Spring Security";
 }
 
 @RequestMapping("/public/aboutme")
 public String aboutMe() {
  return "I am securied by spring security module";
 }
 
}


EmployeeController.java
package com.sample.app.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("employees/")
public class EmployeeController {

 @RequestMapping(value = "registered/count", method = RequestMethod.GET)
 public String countEmps() {
  return "Total Registered Employees : "+  1024;
 }
}


ApplicationSecurityConfiguration.java
package com.sample.app.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter {

 @Override
 protected void configure(HttpSecurity httpSecurity) throws Exception {
  httpSecurity.csrf().disable().authorizeRequests().antMatchers("/", "/public/*", "/css/*", "/js/*").permitAll()
    .anyRequest().authenticated().and().httpBasic();

 }
}


App.java

package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
 public static void main(String[] args) {
  
  SpringApplication.run(App.class, args);
 }
}


pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>springSecurity</groupId>
 <artifactId>springSecurity</artifactId>
 <version>1</version>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.6.RELEASE</version>
 </parent>

 <dependencies>

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

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

 </dependencies>
</project>


Total project structure looks like below.

Run App.java, you can see below kind of messages in console.
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

2019-07-14 13:15:17.974  INFO 19933 --- [           main] com.sample.app.App                       : Starting App on C02X902SJGH5 with PID 19933 (/Users/krishna/Documents/EclipseWorkSpaces/Learnings/springSecurity/target/classes started by krishna in /Users/krishna/Documents/EclipseWorkSpaces/Learnings/springSecurity)
2019-07-14 13:15:17.976  INFO 19933 --- [           main] com.sample.app.App                       : No active profile set, falling back to default profiles: default
2019-07-14 13:15:18.942  INFO 19933 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-07-14 13:15:18.971  INFO 19933 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-07-14 13:15:18.972  INFO 19933 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-07-14 13:15:19.079  INFO 19933 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-07-14 13:15:19.080  INFO 19933 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1052 ms
2019-07-14 13:15:19.294  INFO 19933 --- [           main] .s.s.UserDetailsServiceAutoConfiguration : 

Using generated security password: f4be2aa8-c4b3-4ab3-bef8-96ce4e196c81

2019-07-14 13:15:19.401  INFO 19933 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@4925f4f5, org.springframework.security.web.context.SecurityContextPersistenceFilter@40147317, org.springframework.security.web.header.HeaderWriterFilter@2577d6c8, org.springframework.security.web.authentication.logout.LogoutFilter@e044b4a, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@7f4037ed, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@19542407, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@76304b46, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@1ad926d3, org.springframework.security.web.session.SessionManagementFilter@4c9e9fb8, org.springframework.security.web.access.ExceptionTranslationFilter@30cdae70, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@4aeaadc1]
2019-07-14 13:15:19.537  INFO 19933 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-14 13:15:19.803  INFO 19933 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-07-14 13:15:19.806  INFO 19933 --- [           main] com.sample.app.App                       : Started App in 2.122 seconds (JVM running for 2.484)

Search for string ‘password’ in console messages, you can see below kind of message.

Using generated security password: f4be2aa8-c4b3-4ab3-bef8-96ce4e196c81

We require above password to access the apis that are protected by spring security module. This password change for every run of the application.

Open the url ‘http://localhost:8080/’ in browser, you can see below kind of screen.

Open the url ‘http://localhost:8080/public/aboutme’, you can see below kind of screen.

Open the url ‘http://localhost:8080/employees/registered/count’, then browser prompts for the credentials to access the api.

Enter the user name as ‘user’ and password as ‘f4be2aa8-c4b3-4ab3-bef8-96ce4e196c81’ (password should be taken from console messages).


After click on OK button, you can see below kind of screen.


You can download complete working application from this link.

Previous                                                    Next                                                    Home

No comments:

Post a Comment