SpringSecurity+Mysql数据库实现用户安全登录认证
以下是一个简化的例子,展示了如何使用Spring Security和MySQL数据库实现用户的安全登录认证。
- 在
pom.xml
中添加依赖:
<dependencies>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
- 配置
application.properties
或application.yml
以连接MySQL数据库:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
- 创建一个用户实体(User)和对应的仓库(UserRepository):
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
// 省略getter和setter
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
- 创建一个配置类(SecurityConfig)来配置Spring Security:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
// 其他配置...
}
- 实现
UserDetailsService
来加载用户详情:
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
return UserPrincipal.create(user);
}
}
- 创建一个用户主体类(UserPrincipal)实现
UserDetails
接口:
public class UserPrincipal implements Use
评论已关闭