今天调试成功了,作一个记录。
一, pom.xml中导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
二,建立User实体和UserRepository的JPA
User.java
package com.packt.cardatabase.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Column;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false, updatable = false)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String role;
public User() {
}
public User(String username, String password, String role) {
super();
this.username = username;
this.password = password;
this.role = role;
}
public Long getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getRole() {
return role;
}
public void setId(Long id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setRole(String role) {
this.role = role;
}
}
UserRepository.java
package com.packt.cardatabase.domain;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends CrudRepository<User, Long> {
User findByUsername(String username);
}
三,在CommandLineRunner中新增两个用户
package com.packt.cardatabase;
import com.packt.cardatabase.domain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CardatabaseApplication {
@Autowired
private CarRepository carRepository;
@Autowired
private OwnerRepository ownerRepository;
@Autowired
private UserRepository userRepository;
private static final Logger logger = LoggerFactory.getLogger(CardatabaseApplication.class);
public static void main(String[] args) {
// After adding this comment the application is restarted
SpringApplication.run(CardatabaseApplication.class, args);
logger.info("Hello Spring Boot");
}
@Bean
CommandLineRunner runner() {
return args -> {
Owner owner1 = new Owner("John", "Johnson");
Owner owner2 = new Owner("Mary", "Robinson");
ownerRepository.save(owner1);
ownerRepository.save(owner2);
carRepository.save(new Car("Ford", "Mustang", "Red", "ADF-1121", 2017, 59000, owner1));
carRepository.save(new Car("Nissan", "Leaf", "White", "SSJ-3002", 2014, 29000, owner2));
carRepository.save(new Car("Toyota", "Prius", "Silver", "KKO-0212", 2018, 39000, owner2));
userRepository.save(new User("user","$2a$04$1.YhMIgNX/8TkCKGFUONWO1waedKhQ5KrnB30fl0Q01QKqmzLf.Zi","USER"));
userRepository.save(new User("admin","$2a$04$KNLUwOWHVQZVpXyMBNc7JOzbLiBjb9Tk9bP7KNcPI12ICuvzXQQKG","ADMIN"));
};
}
}
四,新增一个UserDetailsService的实现类
UserDetailServiceImpl.java
package com.packt.cardatabase.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.packt.cardatabase.domain.User;
import com.packt.cardatabase.domain.UserRepository;
@Service
public class UserDetailServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User currentUser = userRepository.findByUsername(username);
UserDetails user = new org.springframework.security.core.userdetails.User(username,
currentUser.getPassword(),
true,
true,
true,
true,
AuthorityUtils.createAuthorityList(currentUser.getRole()));
return user;
}
}
五,实现一个WebSecurityConfigurerAdapter实现类
SecurityConfig.java
package com.packt.cardatabase;
import org.springframework.beans.factory.annotation.Autowired;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.packt.cardatabase.service.UserDetailServiceImpl;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailServiceImpl userDetailService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailService).passwordEncoder(new BCryptPasswordEncoder());
}
}
六,项目目录结构
2020-10-10 18_59_10-cardatabase – SecurityConfig.java.png
七,测试
2020-10-10 18_46_35-Please sign in.png
2020-10-10 18_47_10-localhost_8080_api.png
网友评论