PROGRAMMING

m9/ JAVA
REMEMBERS




Last update:   17-09-2021

Application

Start by creating a simple Spring Boot java project with no authentication. Select Spring Web and Thymeleaf as dependencies.
 
// src/main/java/com/example/securingweb/App.java

package com.example.securingweb;
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);
    }

}
... 4 lines
 
The Web application is based on Spring MVC. You need to configure Spring MVC and set view controllers and templates.
 
// src/main/java/com/example/securingweb/MvcConfig.java

package com.example.securingweb;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {
    
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("hello");
    }
}

/*
// src/main/resources/templates/hello.html 

    <h1>Hello World</h1>
*/
 
... 8 lines
 
 
http://localhost:8080/
    # Hello World

AUTH

! Add Spring Security dependency in pom.xml Spring Boot automatically secures all HTTP enpoints with basic authentication.
 
// pom.xml

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-test</artifactId>
  <scope>test</scope>
</dependency>
... 4 lines
 
 
// src/main/resources/application.properties

spring.security.user.name=myuser
spring.security.user.password=mypass
 
// src/main/resources/templates/hello.html 

<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
    <input type="submit" value="Sign Out"/>
</form>
 
http://localhost:8080/
    # Please sign in 

ENCRYPT

To avoid storing raw password, bcrypt it with and Spring CLI.
 
spring encodepassword mypass

// {bcrypt}$2a$10$2wRXv3x28CiFAq966H93PeAvaRHKMF.ItkMC.CsPBdYTZ2xLO2sLy
 
// src/main/resources/application.properties

spring.security.user.name=myuser
spring.security.user.password={bcrypt}$2a$10$2wRXv3x28CiFAq966H93...

Questions    
Command-Line