Spring Boot Basic Authentication Example

By | 2018-10-27T08:23:32+00:00 March 12th, 2018|Spring Boot|0 Comments

In this tutorials, we are going show you how to use Spring Boot Basic Authentication.

Spring Boot Basic Authentication :

We can provide the basic authentication for a Spring Boot application by simply adding the below dependency in pom.xml.

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

Technologies :

  • Spring Boot 2.0.0.RELEASE
  • Spring Security
  • Java 8

Project Structure :

Spring Boot Basic Authentication Example

pom.xml

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>com.onlinetutorialspoint</groupId>
  <artifactId>SpringBoot_Basic_Authentication</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>SpringBoot_Basic_Authentication</name>
  <description>Demo project for Spring Boot</description>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

Create Simple Rest Controller :

HelloController.java

HelloController.java
package com.onlinetutorialspoint;

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

@RestController
public class HelloController {
    @RequestMapping("/hello")
    @ResponseBody
    public String sayHello(){
        return "<h2>Greetings.. !</h2>";
    }
}

Application.java

Application.java
package com.onlinetutorialspoint;

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

@SpringBootApplication
public class Application {

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

Run :

Terminal
mvn clean install
mvn spring-boot:run

[INFO] --- spring-boot-maven-plugin:2.0.0.RELEASE:run (default-cli) @ SpringBoot_Basic_Authentication ---

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.0.RELEASE)

2018-03-11 21:30:37.225  INFO 2356 --- [           main] com.onlinetutorialspoint.Application     : Starting Application on DESKTOP-RN4SMHT with PID 2356 (E:\work\SpringBoot_Basic_Au
thentication\target\classes started by Lenovo in E:\work\SpringBoot_Basic_Authentication)
2018-03-11 21:30:37.241  INFO 2356 --- [           main] com.onlinetutorialspoint.Application     : No active profile set, falling back to default profiles: default
2018-03-11 21:30:37.350  INFO 2356 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWeb
ServerApplicationContext@563670cc: startup date [Sun Mar 11 21:30:37 IST 2018]; root of context hierarchy
2018-03-11 21:30:40.886  INFO 2356 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-03-11 21:30:40.949  INFO 2356 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-03-11 21:30:40.949  INFO 2356 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.28
2018-03-11 21:30:40.980  INFO 2356 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in pro
duction environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_161\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\ProgramData\Oracle\Java
\javapath;C:\oraclexe\app\oracle\product\11.2.0\server\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\
MySQL\MySQL Server 5.5\bin;C:\php;C:\Apache24;C:\Apache24\bin;C:\Program Files\Java\jdk1.8.0_161\bin;D:\Softwares\apache-maven-3.5.2\bin;C:\Program Files\Git\cmd;C:\Program Files\Git
\mingw64\bin;C:\Program Files\Git\usr\bin;D:\Softwares\apache-ant-1.10.2\bin;C:\Users\Lenovo\AppData\Local\Microsoft\WindowsApps;C:\Users\Lenovo\AppData\Local\atom\bin;%USERPROFILE%\
AppData\Local\Microsoft\WindowsApps;;.]
2018-03-11 21:30:41.574  INFO 2356 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-03-11 21:30:41.589  INFO 2356 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 4239 ms
2018-03-11 21:30:42.131  INFO 2356 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-03-11 21:30:42.146  INFO 2356 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-03-11 21:30:42.146  INFO 2356 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-03-11 21:30:42.146  INFO 2356 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-03-11 21:30:42.146  INFO 2356 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-03-11 21:30:42.146  INFO 2356 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-03-11 21:30:43.193  INFO 2356 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.Annota
tionConfigServletWebServerApplicationContext@563670cc: startup date [Sun Mar 11 21:30:37 IST 2018]; root of context hierarchy
2018-03-11 21:30:43.397  INFO 2356 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello]}" onto public java.lang.String com.onlinetutorialspoint.HelloCon
troller.sayHello()
2018-03-11 21:30:43.428  INFO 2356 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.
Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-03-11 21:30:43.428  INFO 2356 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=}" onto public org.springframework.web.servl
et.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-03-11 21:30:43.522  INFO 2356 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.
servlet.resource.ResourceHttpRequestHandler]
2018-03-11 21:30:43.522  INFO 2356 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.
resource.ResourceHttpRequestHandler]
2018-03-11 21:30:43.647  INFO 2356 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.
web.servlet.resource.ResourceHttpRequestHandler]
2018-03-11 21:30:44.287  INFO 2356 --- [           main] .s.s.UserDetailsServiceAutoConfiguration :

Using generated security password: ef4512ac-aebc-40f8-b589-37cd3b1fc460

2018-03-11 21:30:44.853  INFO 2356 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMat
cher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@203364d6, org.springframework.security.web.context.SecurityContextPersistenceFilter@6
f53f03a, org.springframework.security.web.header.HeaderWriterFilter@7e765142, org.springframework.security.web.csrf.CsrfFilter@396c3d2f, org.springframework.security.web.authenticati
on.logout.LogoutFilter@4e980e94, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@12e2d748, org.springframework.security.web.authentication.ui.Def
aultLoginPageGeneratingFilter@28c3e342, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@aaeec51, org.springframework.security.web.savedrequest.RequestCa
cheAwareFilter@7c7fca3e, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@6d51bf8a, org.springframework.security.web.authentication.AnonymousAuthen
ticationFilter@5f832ac6, org.springframework.security.web.session.SessionManagementFilter@6250c19a, org.springframework.security.web.access.ExceptionTranslationFilter@6835f9de, org.s
pringframework.security.web.access.intercept.FilterSecurityInterceptor@24b65d7d]
2018-03-11 21:30:45.119  INFO 2356 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-03-11 21:30:45.353  INFO 2356 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-03-11 21:30:45.353  INFO 2356 --- [           main] com.onlinetutorialspoint.Application     : Started Application in 9.346 seconds (JVM running for 26.637)

On the above console output, we can see the default authentication password. We can use this password to access the application.

User Name : user

Password : ef4512ac-aebc-40f8-b589-37cd3b1fc460

Spring Boot Basic Authentication Example output

The above password is only for one time, for each time while running the applicaiton, we should get the different password.

Spring Boot Basic Authentication Example output 2

Happy Learning 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment