我已经创建了用户和角色实体类,用于使用引导创建简单的注册页面,但每次我转到浏览器时,它都会重定向到spring security登录页面。我尝试了很多方法来防止这种情况发生,但都不管用。所以,请给我一个解决方案。
1.registration.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>
应用程序属性
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.1用户存储库接口
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.1用户服务接口
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.userregistrationdto.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.userregistrationcontroller
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);
}
}
1条答案
按热度按时间ndh0cuux1#
当使用spring boot并添加
spring-boot-starter-security
依赖于类路径,Spring Security 将在默认情况下自动保护所有端点,从而将您重定向到/login
每当您尝试访问受保护的资源时,都会显示此页。您可以删除
spring-boot-starter-security
如果您根本不需要安全性,或者您可以通过定义SecurityFilterChain
比恩,就像这样:如果您需要任何其他类型的定制,SpringSecuritySamples项目可以是一个很好的切入点。