使用Spring Security实现用户登录以及权限控制,那么在每次请求的时候都会创建一个SecurityContextHolder对象存储用户信息吗
时间: 2023-02-08 08:09:22 浏览: 296
是的,在使用 Spring Security 时,每次请求都会创建一个 SecurityContextHolder 对象来存储用户信息。SecurityContextHolder 是一个全局的单例对象,它的作用是存储当前用户的认证信息,并且在整个应用的生命周期内都可以访问到这些信息。它使用了持有者模式来存储用户信息,因此可以在任何地方访问到当前用户的认证信息。
相关问题
Spring Boot为什么每次请求还能从SecurityContextHolder中获取用户信息呢?
Spring Security使用ThreadLocal存储SecurityContext对象,该对象包含了当前用户的认证信息和授权信息。在Spring Boot中,每个请求都会创建一个新的线程,因此每个请求都有自己的SecurityContext对象。在处理请求时,Spring Security会从当前线程的SecurityContextHolder中获取SecurityContext对象,然后从中获取当前用户的认证信息和授权信息。
因此,即使在同一个请求中,不同的方法或组件也可以通过SecurityContextHolder获取到当前用户的信息。这种方式可以方便地实现权限控制和安全验证,避免了在每个方法或组件中都需要手动获取和验证用户信息的麻烦。
springboot整合spring security 实现用户登录注册与鉴权全记录,权限从数据库中查询
首先,需要在pom.xml中加入spring security和相关依赖文件:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-data</artifactId>
</dependency>
```
接着,在application.properties中配置数据库信息:
```
spring.datasource.url=jdbc:mysql://localhost:3306/security?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
```
然后,创建用户表和权限表,用来存储用户和权限信息。用户表包括用户名和密码,权限表包括权限名称和对应的URL。
接下来,创建UserDetailService实现类,用于从数据库中读取用户信息。代码如下:
```
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
User user = userDao.findByUserName(userName);
if (user == null) {
throw new UsernameNotFoundException("用户名不存在");
}
List<GrantedAuthority> authorities = new ArrayList<>();
List<Role> roles = user.getRoles();
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
}
return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), authorities);
}
}
```
然后,创建SecurityConfig类,用于配置Spring Security。代码如下:
```
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsServiceImpl userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
其中,configure方法用于配置请求的权限,configureGlobal方法用于设置自定义的UserDetailsService,passwordEncoder方法用于设置密码加密方式。
最后,创建UserController类,用于处理用户登录注册和鉴权请求。代码如下:
```
@RestController
public class UserController {
@Autowired
private UserDao userDao;
@Autowired
private PasswordEncoder passwordEncoder;
@PostMapping("/register")
public String register(@RequestParam String userName, @RequestParam String password) {
User user = userDao.findByUserName(userName);
if (user != null) {
return "用户名已存在";
}
user = new User();
user.setUserName(userName);
user.setPassword(passwordEncoder.encode(password));
userDao.save(user);
return "注册成功";
}
@PostMapping("/login")
public String login(@RequestParam String userName, @RequestParam String password) {
try {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, password);
Authentication authentication = authenticationManager().authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
return "登录成功";
} catch (Exception e) {
return "用户名或密码错误";
}
}
@GetMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public String admin() {
return "管理员权限";
}
@GetMapping("/user")
@PreAuthorize("hasAnyRole('USER','ADMIN')")
public String user() {
return "用户权限";
}
}
```
其中,register方法用于处理用户注册请求,login方法用于处理用户登录请求,admin和user方法用于处理鉴权请求。
至此,整合spring security实现用户登录注册与鉴权全记录,权限从数据库中查询的操作已经完成。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)