minte9
LearnRemember




Security Dependency

With security we automatically get basic authentication.
 
<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>

App Main

Spring web project with starter security and thymeleaf dependencies.
 
/**
 * Spring Boot Application
 */

package com.minte9.security_auth;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;

@SpringBootApplication
public class App {

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

    @GetMapping("/")
    public String home() {
        return "index.html";
    }
}

Configuration

Configure Spring MVC and set view controllers and templates.
 
/**
 * App Configuration
 * 
 * WebMvcConfigurer is used to configure view controllers 
 * that return HTML pages.
 * 
 * AddViewControllers() method is used to register view controllers 
 * that map specific URLs to view names.
 * 
 * In general, using @GetMapping annotations in your controller 
 * is the more common and flexible approach, but defining view controllers 
 * can be a useful tool in certain situations. 
 */

package com.minte9.security_auth;
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("/index").setViewName("index");
        registry.addViewController("/user").setViewName("user");
    }
}

Authorize

Configure security config, allowing access to index
 
/**
 * Auth Security Configuration
 * 
 * If you add Spring Security to your classpath (pom.xml), 
 * by default all endpoints will be secured.
 * 
 * You can configure Spring Security to permit access to the index page 
 * while requiring authentication for the RESTful API endpoints.
 */

package com.minte9.security_auth;

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

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/index").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .and()
            .httpBasic();
    }
}

Store Password

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

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

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

server.servlet.context-path=/myapp

Templates

Add index and user login form template.
 
<pre>
Welcome!

<a href='/myapp/user'>User page</a> (needs login)
</pre>

<br>
<form th:if="${#httpServletRequest.remoteUser != null}" 
        th:action="@{/logout}" method="post">
    <input type="submit" value="Sign Out"/>
</form>
 
<h3>Hello [[${#httpServletRequest.remoteUser}]]! </h3>

<form th:action="@{/logout}" method="post">
    <input type="submit" value="Sign Out"/>
</form>

<a href='/myapp/index'>Index page</a>

Run App

Test login by accesing app entry points.
 
mvn spring-boot:run

http://localhost:8080/myapp
http://localhost:8080/myapp/user

# Welcome
# Please sign in 



  Last update: 217 days ago