我已经创建了User&使用引导程序创建简单注册页面的角色实体类,但每次我进入浏览器时,它都会重定向到春季安全登录页面。我已经尝试了很多方法来防止这种情况,但都不适用。所以,请给我一个解决方案。
1.注册.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Registration</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
</head>
<body>
<!-- Create navigation bar (header) -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header" >
<button type="button" class="navbar-toggle collapsed"
data-toggle="collapse" data-target="#navbar" aria-expanded="false"
aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#" th:href="@{/}">Registration and Login Module</a>
</div>
</div>
</nav>
<br>
<br>
<!-- Create HTML registration form -->
<div class = "container">
<div class = "row">
<div class = "col-md-6 col-md-offset-3">
<!-- success message -->
<div th:if="${param.success}">
<div class="alert alert-info">You've successfully registered to our awesome app!</div>
</div>
<h1>Registration</h1>
<form th:action="@{/registration" method="post" th:object = "${user}">
<div class = "form-group">
<label class = "control-label" for="firstName"> First Name </label>
<input id = "firstName" class = "form-control" th:field="*{firstName}"
required autofocus="autofocus" />
</div>
<div class = "form-group">
<label class = "control-label" for="lastName"> Last Name </label>
<input id = "lastName" class = "form-control" th:field="*{lastName}"
required autofocus="autofocus" />
</div>
<div class = "form-group">
<label class = "control-label" for="email"> Email </label>
<input id = "email" class = "form-control" th:field="*{email}"
required autofocus="autofocus" />
</div>
<div class = "form-group">
<label class = "control-label" for="password"> Password </label>
<input id = "password" class = "form-control" th:field="*{password}"
required autofocus="autofocus" />
</div>
<div class = "form-group">
<button type="submit" class="btn btn-success">Register</button>
<span>Already registered? <a href="/" th:href="@{/login}"> Login here </a> </span>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
- application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useSSL=false&serverTime=UTC&useLegacyDatetimeCode=false
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=1441
server.port=8084
server.error.whitelabel.enabled=false
#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
spring.thymeleaf.check-template=true
spring.thymeleaf.check-template-location=true
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
debug=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE
spring.profiles.active=@spring.profiles.active@
spring.jpa.open-in-view=false
logging.level.org.springframework.boot.autoconfigure=ERROR
3.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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>net.javaguides</groupId>
<artifactId>registration-login-spring-boot-security-thymeleaf</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>registration-login-spring-boot-security-thymeleaf</name>
<description>Demo project for Spring Boot Thymeleaf and Hibernate</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency> -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4.用户实体类
package net.javaguides.springboot.model;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@Entity
@Table(name = "user", uniqueConstraints = @UniqueConstraint(columnNames = "email"))//for email should be unique
public class User
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "first_Name")
private String firstName;
@Column(name = "last_Name")
private String lastName;
private String email;
private String password;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
private Collection<Role> roles;
public User(String firstName, String lastName, String email, String password, Collection<Role> roles) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.roles = roles;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Collection<Role> getRoles() {
return roles;
}
public void setRoles(Collection<Role> roles) {
this.roles = roles;
}
}
5.角色实体类
package net.javaguides.springboot.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "role")
public class Role
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
public Role(String name) {
super();
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
6.UserRepository接口
package net.javaguides.springboot.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.javaguides.springboot.model.User;
@Repository
public interface UserRepository extends JpaRepository<User, Long>
{
}
7.用户服务接口
package net.javaguides.springboot.Service;
import net.javaguides.springboot.model.User;
import net.javaguides.springboot.web.dto.UserRegistrationDto;
public interface UserService
{
User save(UserRegistrationDto registrationDto);
}
8.UserServiceImpl.Class
package net.javaguides.springboot.Service;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import net.javaguides.springboot.Repository.UserRepository;
import net.javaguides.springboot.model.Role;
import net.javaguides.springboot.model.User;
import net.javaguides.springboot.web.dto.UserRegistrationDto;
@Service
public class UserServiceImpl implements UserService
{
@Autowired
private UserRepository userRepository;
public UserServiceImpl(UserRepository userRepository) {
super();
this.userRepository = userRepository;
}
@Override
public User save(UserRegistrationDto registrationDto)
{
User user = new User(registrationDto.getFirstName(), registrationDto.getLastName(),
registrationDto.getEmail(),registrationDto.getPassword(),Arrays.asList(new Role("ROLE_USER")));
return userRepository.save(user);
}
}
9.用户注册Dto.Class
package net.javaguides.springboot.web.dto;
public class UserRegistrationDto
{
private String firstName;
private String lastName;
private String email;
private String password;
public UserRegistrationDto()
{
super();
}
public UserRegistrationDto(String firstName, String lastName, String email, String password) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
10.用户注册控制器
package net.javaguides.springboot.webb;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import net.javaguides.springboot.Service.UserService;
import net.javaguides.springboot.web.dto.UserRegistrationDto;
@Controller
@RequestMapping("/registration")
public class UserRegistrationController
{
private UserService userService;
public UserRegistrationController(UserService userService) {
super();
this.userService = userService;
}
@ModelAttribute("user")
public UserRegistrationDto userRegistrationDto()
{
return new UserRegistrationDto();
}
@GetMapping
public String showRegistrationForm()
{
return "registration";
}
@PostMapping
public String registerUserAccount(@ModelAttribute("user") UserRegistrationDto registrationDto)
{
userService.save(registrationDto);
return "redirect:/registration?success";
}
}
11.主要类别
package net.javaguides.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
@SpringBootApplication(scanBasePackages = {"net.javaguides.springboot.model","net.javaguides.springboot.Repository","net.javaguides.springboot.Service","net.javaguides.springboot.web.dto","net.javaguides.springboot.webb"})
@ComponentScan(basePackages = {"net.javaguides.springboot.model","net.javaguides.springboot.Repository","net.javaguides.springboot.Service","net.javaguides.springboot.web.dto","net.javaguides.springboot.webb"})
@EnableJpaRepositories("net.javaguides.springboot.Repository")
@EntityScan("net.javaguides.springboot.model")
//@EnableSpringDataWebSupport
public class RegistrationLoginSpringBootSecurityThymeleafApplication {
public static void main(String[] args) {
SpringApplication.run(RegistrationLoginSpringBootSecurityThymeleafApplication.class, args);
}
}
当使用Spring Boot并将spring-boot-starter-security
依赖项添加到类路径时,Spring Security将在默认情况下自动保护所有端点,从而在您尝试访问受保护的资源时将您重定向到/login
页面。
如果根本不需要安全性,您可以删除spring-boot-starter-security
依赖项,也可以通过定义SecurityFilterChain
bean来允许所有端点,如下所示:
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) {
http.authorizeRequests((requests) ->
requests.anyRequest().permitAll();
);
return http.build();
}
}
如果您需要任何其他类型的自定义,Spring Security Samples项目可以是一个很好的切入点。