Spring Boot Basic Authentication Example - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorials, we are going show you how to use Spring Boot Basic Authentication.
We can provide the basic authentication for a Spring Boot application by simply adding the below dependency in pom.xml.
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
</dependency>
Spring Boot 2.0.0.RELEASE
Spring Security
Java 8
Project Structure :
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
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
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);
  }
}

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.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=[text/html]}" 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
The above password is only for one time, for each time while running the applicaiton, we should get the different password.
Happy Learning 🙂

How to use Spring Boot Random Port
Spring Boot How to change the Tomcat to Jetty Server
Spring Boot In Memory Basic Authentication Security
How to set Spring Boot SetTimeZone
How to Create own Spring Boot Error Page
Spring Boot Environment Properties reading based on activeprofile
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
MicroServices Spring Boot Eureka Server Example
How to Get All Spring Beans Details Loaded in ICO
Spring Boot Apache ActiveMq In Memory Example
How to set Spring boot favicon image
Spring Boot Security MySQL Database Integration Example
Spring Boot MongoDB + Spring Data Example
Spring Boot JPA Integration Example

How to use Spring Boot Random Port
Spring Boot How to change the Tomcat to Jetty Server
Spring Boot In Memory Basic Authentication Security
How to set Spring Boot SetTimeZone
How to Create own Spring Boot Error Page
Spring Boot Environment Properties reading based on activeprofile
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
MicroServices Spring Boot Eureka Server Example
How to Get All Spring Beans Details Loaded in ICO
Spring Boot Apache ActiveMq In Memory Example
How to set Spring boot favicon image
Spring Boot Security MySQL Database Integration Example
Spring Boot MongoDB + Spring Data Example
Spring Boot JPA Integration Example
 


Δ
 Spring Boot – Hello World
 Spring Boot – MVC Example
 Spring Boot- Change Context Path
 Spring Boot – Change Tomcat Port Number
 Spring Boot – Change Tomcat to Jetty Server
 Spring Boot – Tomcat session timeout
 Spring Boot – Enable Random Port
 Spring Boot – Properties File
 Spring Boot – Beans Lazy Loading
 Spring Boot – Set Favicon image
 Spring Boot – Set Custom Banner
 Spring Boot – Set Application TimeZone
 Spring Boot – Send Mail
 Spring Boot – FileUpload Ajax
 Spring Boot – Actuator
 Spring Boot – Actuator Database Health Check
 Spring Boot – Swagger
 Spring Boot – Enable CORS
 Spring Boot – External Apache ActiveMQ Setup
 Spring Boot – Inmemory Apache ActiveMq
 Spring Boot – Scheduler Job
 Spring Boot – Exception Handling
 Spring Boot – Hibernate CRUD
 Spring Boot – JPA Integration CRUD
 Spring Boot – JPA DataRest CRUD
 Spring Boot – JdbcTemplate CRUD
 Spring Boot – Multiple Data Sources Config
 Spring Boot – JNDI Configuration
 Spring Boot – H2 Database CRUD
 Spring Boot – MongoDB CRUD
 Spring Boot – Redis Data CRUD
 Spring Boot – MVC Login Form Validation
 Spring Boot – Custom Error Pages
 Spring Boot – iText PDF
 Spring Boot – Enable SSL (HTTPs)
 Spring Boot – Basic Authentication
 Spring Boot – In Memory Basic Authentication
 Spring Boot – Security MySQL Database Integration
 Spring Boot – Redis Cache – Redis Server
 Spring Boot – Hazelcast Cache
 Spring Boot – EhCache
 Spring Boot – Kafka Producer
 Spring Boot – Kafka Consumer
 Spring Boot – Kafka JSON Message to Kafka Topic
 Spring Boot – RabbitMQ Publisher
 Spring Boot – RabbitMQ Consumer
 Spring Boot – SOAP Consumer
 Spring Boot – Soap WebServices
 Spring Boot – Batch Csv to Database
 Spring Boot – Eureka Server
 Spring Boot – MockMvc JUnit
 Spring Boot – Docker Deployment