Try to implement login function with Spring Boot

Continuing from the previous article [Try automation of migration with Spring Boot Flyway], try implementing login processing.

build.gradle Add ** spring-boot-starter-security **.

build.gradle



plugins {
    id 'java'
    id 'org.springframework.boot' version '2.3.1.BUILD-SNAPSHOT'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'com.avast.gradle.docker-compose' version '0.12.1' 
    id 'org.flywaydb.flyway' version '6.4.3'
}

// ...Abbreviation

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.flywaydb:flyway-core'
    implementation "org.springframework.boot:spring-boot-starter-security" //add to
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'mysql:mysql-connector-java'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    testImplementation 'org.springframework.security:spring-security-test' //add to
}

Create SecurityConfig.java

Create in the same hierarchy as ** Application **.

SecurityConfig.java



package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.sql.DataSource;

//Security setting class
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    //Password encoder
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
     }

    @Autowired
    private DataSource dataSource;

    //Sql statement to get the user
    private static final String USER_SQL = "SELECT"
        + " email,"
        + " password,"
        + " true"
        + " FROM"
        + " users"
        + " WHERE"
        + " email = ?";

    //Sql statement to get permission
    private static final String ROLE_SQL = "SELECT"
        + " email,"
        + " role"
        + " FROM"
        + " users"
        + " WHERE"
        + " email = ?";

    @Override
    public void configure(WebSecurity web) throws Exception {

        //Do not apply security to access to static resources
        web.ignoring().antMatchers("/resources/**");
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //Login-free page settings
        http.authorizeRequests()
            .antMatchers("/resources/**");
            //Access to other pages is denied
            .anyRequest().authenticated();
        
        //Login form settings
        http.formLogin()
            //User parameter name
            .usernameParameter("email")
            //Password parameter name
            .passwordParameter("password");

        //Disable CSRF measures
        http.csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //Get user information at the time of login process from DB
        auth.jdbcAuthentication()
            .dataSource(dataSource)
            .usersByUsernameQuery(USER_SQL)
            .authoritiesByUsernameQuery(ROLE_SQL)
            .passwordEncoder(passwordEncoder());
    }
}

Modify R__1_insert_datas.sql

Change the password to an encoded string. The original string is ** passw0rd **.

R__1_insert_datas.sql


INSERT INTO `users` VALUES
    (1,'Yamada','Hanako','[email protected]','$2a$06$hY5MzfruCds1t5uFLzrlBuw3HcrEGeysr9xJE4Cml5xEOVf425pmK',NULL,NOW(),NULL,NULL,NULL,NULL,1),
    (2,'Suzuki','Taro','[email protected]','$2a$06$hY5MzfruCds1t5uFLzrlBuw3HcrEGeysr9xJE4Cml5xEOVf425pmK',NULL,NOW(),NULL,NULL,NULL,NULL,1);

Application launch

If you have already started docker. Execute ./gradlew composeDown once to delete all containers etc.

$ ./gradlew composeDown


> Task :composeDown
Stopping todoDb ... 
Stopping todoDb ... done
Removing todoDb ... 
Removing todoDb ... done
Removing network eb415214cdb915cc9f956bc6e963ac23_spring-boot-todo-sample__default

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.4.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 4s
1 actionable task: 1 executed

Start docker again with ./gradlew composeUp and create the database.

Then start the application with ./graldew bootRun. [Previous article ** application.yml **](https://qiita.com/megumi_622/items/c38100ca5b266e301643#applicationyml%E3%82%92%E4%BD%9C%E6%88%90%E3%81 You can check the login screen with the port number specified in server.port of% 99% E3% 82% 8B).

If you access the following URL, you will be redirected to ** / login **. http://localhost:18082 スクリーンショット 2020-06-15 23.42.58.png

Since the page after login is not specified, a blank page will be displayed after login. Username: [email protected] or [email protected] Password: passw0rd

Next time, I will write user registration and editing process.

Recommended Posts

Try to implement login function with Spring Boot
Try to implement login function with Spring-Boot
Implement paging function with Spring Boot + Thymeleaf
Try to automate migration with Spring Boot Flyway
[Introduction to Spring Boot] Authentication function with Spring Security
Try Spring Boot from 0 to 100.
Implement GraphQL with Spring Boot
SNS login with Spring Boot
Login function with Spring Security
With Spring boot, password is hashed and member registration & Spring security is used to implement login function.
Try to implement iOS14 Widget function
Try using Spring Boot with VS Code
How to implement TextInputLayout with validation function
Implement CRUD with Spring Boot + Thymeleaf + MySQL
Part 1: Try using OAuth 2.0 Login supported by Spring Security 5 with Spring Boot
How to use MyBatis2 (iBatis) with Spring Boot 1.4 (Spring 4)
How to use built-in h2db with spring boot
Try LDAP authentication with Spring Security (Spring Boot) + OpenLDAP
Try to implement TCP / IP + NIO with JAVA
[Java] Article to add validation with Spring Boot 2.3.1.
I wanted to gradle spring boot with multi-project
Try to display hello world with spring + gradle
"Teacher, I want to implement a login function in Spring" ① Hello World
Download with Spring Boot
Create login / logout function with Spring Security according to Spring official guide [For beginners]
Settings for connecting to MySQL with Spring Boot + Spring JDBC
Try using DI container with Laravel and Spring Boot
I tried to implement file upload with Spring MVC
Automatically map DTOs to entities with Spring Boot API
Try using OpenID Connect with Keycloak (Spring Boot application)
Implement a simple Rest API with Spring Security with Spring Boot 2.0
Try Dependency Inversion Principle with Multiple Spring Boot Projects
How to boot by environment with Spring Boot of Maven
Attempt to SSR Vue.js with Spring Boot and GraalJS
Try to work with Keycloak using Spring Security SAML (Spring 5)
Generate barcode with Spring Boot
Hello World with Spring Boot
Java to play with Function
Get started with Spring boot
Hello World with Spring Boot!
Run LIFF with Spring Boot
Introduction to Spring Boot ① ~ DI ~
File upload with Spring Boot
Spring Boot starting with copy
Introduction to Spring Boot ② ~ AOP ~
Spring Boot starting with Docker
Hello World with Spring Boot
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Add module with Spring Boot
Getting Started with Spring Boot
Introduction to Spring Boot Part 1
Try using Spring Boot Security
Try Spring Boot on Mac
Create microservices with Spring Boot
Send email with spring boot
Output embedded Tomcat access log to standard output with Spring Boot
About the function of Spring Boot due to different versions
Implement REST API with Spring Boot and JPA (Application Layer)
Implement REST API with Spring Boot and JPA (Infrastructure layer)
Extract SQL to property file with jdbcTemplate of spring boot