[JAVA] Spring 5 MVC-Webanwendungsentwicklung mit Visual Studio Code Spring Security-Verwendung 2/3 [Seitenerstellung 1/2]

Einführung

Dies ist eine Fortsetzung von hier. Dieses Mal erstellen wir eine Anmeldeseite und eine Seite zur Erstellung von Verwaltungsbenutzern.

Formularerstellung

Erstellen Sie ein Formular, das auf der Anmeldeseite und der Seite zur Benutzererstellung verwendet werden soll.

D:\JAVA\Project\securitySample\src\main\java\com\example
└─form
  └─AuthForm.java

AuthForm.java

AuthForm.java


package com.example.web.form;

import javax.validation.constraints.Size;

import lombok.Data;

@Data
public class AuthForm {
    private String userId;

    @Size(min=3, max=255)
    private String password;

    private String userNameJP;
    private String sectionNameJP;
    private Boolean enabled;

    private String[] authority;
}

Serviceerstellung

Erstellen Sie eine Geschäftslogik für die Benutzerregistrierung.

D:\JAVA\Project\securitySample\src\main\java\com\example
└─service
  ├─AuthService.java
  └─AuthServiceImpl.java

AuthService.java

AuthService.java


package com.example.service;

import java.util.List;

import com.example.persistence.entity.UserInfo;
import com.example.web.form.AuthForm;

public interface AuthService {
	void insertAdmin(AuthForm authForm);

	void insertUser(AuthForm authForm);

	void updateUser(AuthForm authForm);

	void deleteUser(String id);

	Integer adminCheck();

	List<UserInfo> findUserAll();

	AuthForm userRegById(String id);

}

AuthServiceImpl.java

AuthServiceImpl.java


package com.example.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.example.persistence.entity.UserInfo;
import com.example.persistence.entity.UserRoles;
import com.example.persistence.repository.UserInfoRepository;
import com.example.persistence.repository.UserRolesRepository;
import com.example.web.form.AuthForm;

@Service
public class AuthServiceImpl implements AuthService {
	@Autowired
	UserInfoRepository userInfoRepository;

	@Autowired
	UserRolesRepository userRolesRepository;

	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public void insertAdmin(AuthForm authForm) {

		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

		UserInfo userInfo = new UserInfo();
		UserRoles userRoles = new UserRoles();
		List<UserRoles> userRokesList  = new  ArrayList<UserRoles>();

		userInfo.setUserId(authForm.getUserId());
		userInfo.setPassword(encoder.encode( authForm.getPassword() ));

		userInfo.setUserNameJP("Administrator");
		userInfo.setSectionNameJP("Administrator");
		userInfo.setEnabled(true);

		userRoles.setUserId(authForm.getUserId());
		userRoles.setAuthority("ROLE_ADMIN");
		userRokesList.add(userRoles);

		userInfo.setUserRolesList(userRokesList);

		userInfoRepository.insert(userInfo);

		userInfo.getUserRolesList().forEach(s -> {
			userRolesRepository.insert(s);
		});
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public void insertUser(AuthForm authForm) {

		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

		UserInfo userInfo = new UserInfo();

		userInfo.setUserId(authForm.getUserId());
		userInfo.setPassword(encoder.encode( authForm.getPassword() ));

		userInfo.setUserNameJP(authForm.getUserNameJP());
		userInfo.setSectionNameJP(authForm.getSectionNameJP());
		userInfo.setEnabled(true);

		userInfoRepository.insert(userInfo);

		List<String> authorityList = new ArrayList<String>(Arrays.asList(authForm.getAuthority()));
		authorityList.add("ROLE_USER");

		authorityList.forEach(s -> {
			UserRoles userRoles = new UserRoles();
			userRoles.setUserId(authForm.getUserId());
			userRoles.setAuthority(s);

			userRolesRepository.insert(userRoles);
		});
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	public Integer adminCheck() {
		return userRolesRepository.adminCheck();
	}


	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public void updateUser(AuthForm authForm){
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

		UserInfo userInfo = new UserInfo();

		userInfo.setUserId(authForm.getUserId());
		userInfo.setPassword(encoder.encode(authForm.getPassword()));
		userInfo.setUserNameJP(authForm.getUserNameJP());
		userInfo.setSectionNameJP(authForm.getSectionNameJP());
		userInfo.setEnabled(authForm.getEnabled());

		userInfoRepository.update(userInfo);

		userRolesRepository.delete(authForm.getUserId());

		List<String> authorityList = new ArrayList<String>(Arrays.asList(authForm.getAuthority()));
		authorityList.add("ROLE_USER");

		authorityList.forEach(s -> {
			UserRoles userRoles = new UserRoles();
			userRoles.setUserId(authForm.getUserId());
			userRoles.setAuthority(s);

			userRolesRepository.insert(userRoles);
		});
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public void deleteUser(String id) {
		userInfoRepository.delete(id);
		userRolesRepository.delete(id);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	public List<UserInfo> findUserAll() {
		return userInfoRepository.findUserAll();
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	public AuthForm userRegById(String id){
		AuthForm authForm = new AuthForm();

		Optional<UserInfo> userInfoOpt = userInfoRepository.selectDetailByUserId(id);

		userInfoOpt.ifPresentOrElse(userInfo -> {
			authForm.setUserId(userInfo.getUserId());
			authForm.setPassword(userInfo.getPassword());
			authForm.setUserNameJP(userInfo.getUserNameJP());
			authForm.setSectionNameJP(userInfo.getSectionNameJP());
			authForm.setEnabled(userInfo.getEnabled());

			String[] arrayAuthority = new String[userInfo.getUserRolesList().size()];

			Integer i = 0;
			for (UserRoles ur : userInfo.getUserRolesList()) {
				arrayAuthority[i] = ur.getAuthority();
				i++;
			}

			authForm.setAuthority(arrayAuthority);
		},null);

		return authForm;
	}
}

Controller erstellen

Erstellen Sie einen Controller für die Anmeldeseite und die Erstellungsseite für Administratorbenutzer.

D:\JAVA\Project\securitySample\src\main\java\com\example
└─controller
  ├─AuthController.java
  └─AdminRegController.java

AuthController.java

AuthController.java


package com.example.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.service.AuthService;

@Controller
@RequestMapping("/auth")
public class AuthController {
	@Autowired
	AuthService authService;

	@GetMapping("/login")
    public String loginGet(Model model) {

		if(authService.adminCheck() <= 0) {
        	return "redirect:/adminReg/index";
        }
		return "auth/login";
    }

	@GetMapping("/403")
    public String index403(Model model) {
		return "auth/403";
    }

	@GetMapping("/login-error")
    public String loginErrorGet(Model model) {
        model.addAttribute("loginError", true);
        return "auth/login";
    }
}

AdminRegController.java

AdminRegController.java


package com.example.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.service.AuthService;
import com.example.web.form.AuthForm;

@Controller
@RequestMapping("/adminReg")
public class AdminRegController {
	@Autowired
	AuthService authService;

	@GetMapping("/index")
    public String indexGet(Model model) {
		//Nur ein ADMIN-Rollenbenutzer
        if(authService.adminCheck() > 0) {
        	return "redirect:registered";
        }

		model.addAttribute("authForm", new AuthForm());
        return "adminReg/index";
    }

	@PostMapping("/index")
    public String indexPost(Model model,
    		@Valid AuthForm authForm, BindingResult bindingResult, HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
        	model.addAttribute("signupError", true);
            return "adminReg/index";
        }

        try {
        	authService.insertAdmin(authForm);
        } catch (DataIntegrityViolationException e) {
            model.addAttribute("signupError", true);
            return "adminReg/index";
        }
        return "adminReg/done";
    }

	@GetMapping("/registered")
    public String registered(Model model) {
        return "adminReg/registered";
    }
}

Änderung von RootController.java

Legen Sie das Umleitungsziel fest, wenn auf die Route im Authentifizierungsbildschirm zugegriffen wird.

RootController.java


package com.example.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class RootController {
    @GetMapping("/")
    public String root() {
        return "redirect:auth/login";
    }
}

Ansicht erstellen

Erstellen Sie eine Ansicht der Anmeldeseite und der Erstellungsseite des Administrators.

D:\JAVA\Project\securitySample\src\main\webapp\WEB-INF\templates
├─adminReg
| ├─done.html
| ├─index.html
| └─registered.html
├─auth
| ├─403.html
| └─login.html
└─fragment
  └─frag01.html

Verwenden Sie Vorlagenfragmente, um gemeinsame Teile zu Teilen zu machen.

fragment/frag01.html

frag01.html


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<!--HTML-Header-->
<head th:fragment="htmlhead" th:remove="tag">
	<meta charset="UTF-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
</body>
</html>

adminReg/done.html

done.html


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
	<head th:include="fragment/frag01 :: htmlhead"></head>
	<title>Registrierungsseite für Administrator-ID abgeschlossen</title>
</head>
<body>
	<h1>Ich habe die Administrator-ID registriert.</h1>
	<a th:href="@{/auth/login}">oben</a>
</body>
</html>

adminReg/index.html

index.html


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
	<head th:insert="fragment/frag01 :: htmlhead"></head>
	<title>Registrierungsseite für die Administrator-ID</title>
</head>
<body>
	<h1>Registrierungsseite für die Administrator-ID</h1>

	<form method="post" action="#" th:action="@{index}" th:object="${authForm}">
		<div th:if="${signupDone}">
			<em>Hat sich registriert.</em>
		</div>

		<div th:if="${signupError}">
			<em>Ich konnte mich nicht registrieren.</em>
		</div>

		<div>
			<label for="userId">Anmelde-ID</label>:
			<input type="text" autofocus="autofocus" th:field="*{userId}">
		</div>

		<div>
			<label for="password">Passwort</label>:
			<input type="password" th:field="*{password}">
			<em th:if="${#fields.hasErrors('password')}" th:errors="*{password}">Password Error</em>
		</div>

		<div>
			<button type="submit">Anmeldung</button>
		</div>
	</form>
</body>
</html>

adminReg/registered.html

registered.html


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
	<head th:insert="fragment/frag01 :: htmlhead"></head>
	<title>Registrierungsseite für die Administrator-ID</title>
</head>
<body>
	<h1>Die Administrator-ID wurde registriert.</h1>
	<a th:href="@{/auth/login}">oben</a>
</body>
</html>

auth/403.html

403.html


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org" th:with="lang=${#locale.language}" th:lang="${lang}"
	xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
	<head th:insert="fragment/frag01 :: htmlhead"></head>
	<title>Error page</title>
</head>
<body>
	<div>
		<h1>Es tut mir Leid. Ein Fehler ist aufgetreten.</h1>
	</div>
</body>
</html>

auth/login.html

login.html


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
	<head th:insert="fragment/frag01 :: htmlhead"></head>
	<title>Loginseite</title>
</head>
<body>
	<h1>Loginseite</h1>

	<form method="post" action="#" th:action="@{/login}">
		<div th:if="${loginError}">
			<em>Ich konnte mich nicht einloggen. Bitte überprüfen Sie Ihre Login-ID und Ihr Passwort.</em>
		</div>

		<div>
	        <label for="uername">Anmelde-ID</label>:
	   		<input type="text" id="username" name="username" autofocus="autofocus">
		</div>

		<div>
	    	<label for="password">Passwort</label>:
			<input type="password" id="password" name="password">
		</div>

		<div>
			<button type="submit">Einloggen</button>
		</div>
	</form>
</body>
</html>

Zusammenfassung

Wenn Sie es bis jetzt geschafft haben, können Sie den Vorgang überprüfen. Bitte kompilieren und ausführen. Sie können sich als Administrator registrieren.

Erstellen Sie als Nächstes eine vom Benutzer erstellte Seite. Das ist es.

Recommended Posts

Spring 5 MVC-Webanwendungsentwicklung mit Visual Studio Code Spring Security-Verwendung 2/3 [Seitenerstellung 1/2]
Spring 5 MVC-Webanwendungsentwicklung mit Visual Studio Code Spring Security-Verwendung 3/3 [Seitenerstellung 2/2]
Spring 5 MVC-Webanwendungsentwicklung mit Visual Studio Code Spring Security-Nutzung 1/3 [Vorbereitung]
Entwicklung von Spring5 MVC-Webanwendungen mit Visual Studio Code Maven-Vorlagenerstellung
Spring5 MVC-Webanwendungsentwicklung mit Visual Studio Code SQL Server-Verbindung
Spring Boot2-Webanwendungsentwicklung mit Visual Studio Code Hello World-Erstellung
Spring Boot2-Webanwendungsentwicklung mit Visual Studio Code SQL Server-Verbindung
Entwicklung von Spring5 MVC-Webanwendungen mit Visual Studio Code Environment-Konstruktion (Installation von JDK11 / Maven / Tomcat / Visual Studio Code)
Erstellen Sie mit Java + Spring eine Web-APP-Entwicklungsumgebung mit Visual Studio Code
Starten Sie die Entwicklung von Webanwendungen mit Spring Boot
Verwendungshinweis zu Spring Security: Zusammenarbeit mit Spring MVC und Boot
Erstellen Sie eine Java-Programmentwicklungsumgebung mit Visual Studio Code
Erstellung einer Java-Webanwendungsentwicklungsumgebung mit VS-Code (struts2)
Verwenden Sie PlantUML mit Visual Studio Code
Erstellen Sie eine Anfrage-App mit Spring Boot
Eine Aufzeichnung zum Einrichten einer Java-Entwicklungsumgebung mit Visual Studio Code
Führen Sie die WEB-Anwendung mit Spring Boot + Thymeleaf aus
Erleben Sie .NET 5 mit Docker und Visual Studio Code
[Jakarta EE 8 Anwendungsentwicklung mit Gradle] 2. Projekterstellung
Erste Schritte mit Java-Programmen mit Visual Studio Code
Warum können Sie Java mit Visual Studio Code entwickeln?
Etwa der Ablauf der Entwicklung von Webanwendungen mit Rails.
Memo zur Entwicklung von Webanwendungen mit MVN, Tomcat, JSP / Servlet mit VScode
Die erste WEB-Anwendung mit Spring Boot-Making a Pomodoro Timer-
So erhalten Sie eine leere Anfrage mit Spring Web MVC @RequestBody