依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
新建配置类继承 WebSecurityConfigurerAdapter
- 配置认证方式,重写 configure(AuthenticationManagerBuilder auth) 方法
- 配置 http 请求 安全规则,重写 configure(HttpSecurity http) 方法
- 请求授权:
- 我们可以使用
authorizeRequests()
方法来定义哪些请求需要认证,哪些不需要。 - 例如,我们可以指定某些URL路径允许所有用户访问(无需认证),而其他路径则需要用户具有特定的角色或权限才能访问。
- 我们可以使用
- 表单登录:
- 使用
formLogin()
方法可以配置基于表单的登录。 - 我们可以指定登录页面的URL、登录成功后的跳转页面,以及登录失败时的处理。
- 使用
- HTTP Basic认证:
- 通过
httpBasic()
方法可以启用HTTP Basic认证,这通常用于简单的RESTful服务。
- 通过
- CSRF保护:
- 使用
csrf()
方法可以启用或禁用CSRF(跨站请求伪造)保护。
- 使用
- 注销:
- 使用
logout()
方法可以配置用户注销的功能,包括注销后的跳转页面。
- 使用
- 其他安全配置:
- 我们还可以配置headers()、session()等来控制HTTP头的安全性和会话管理。
- 请求授权:
package com.shore.my_spring_demo.web.config;
import com.shore.my_spring_demo.dal.entity.UserEntity;
import com.shore.my_spring_demo.dal.repo.UserServiceRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.annotation.Resource;
import java.util.ArrayList;
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Resource
private UserServiceRepo userServiceRepo;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(username -> {
UserEntity userEntity = userServiceRepo.getUserByUsername(username);
if (userEntity == null) {
throw new UsernameNotFoundException(String.format("User %s not found", username));
}
return new User(userEntity.getUsername(), userEntity.getPassword(), new ArrayList<>());
})
.passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/shore/demo/user/login", "/shore/demo/user/register").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
用户注册
用户密码转为密文方式保存
@Resource
private PasswordEncoder passwordEncoder;
@Override
public boolean register(UserReq userAddReq) {
UserEntity userEntity = new UserEntity();
userEntity.setUsername(userAddReq.getUsername());
userEntity.setPassword(passwordEncoder.encode(userAddReq.getPassword()));
userEntity.setEmail(userAddReq.getEmail());
userEntity.setPhone(userAddReq.getPhone());
userEntity.setNickname(userAddReq.getNickname());
userEntity.setAddress(userAddReq.getAddress());
userEntity.setAge(userAddReq.getAge());
return userServiceRepo.addUser(userEntity);
}
用户登录
调用上面配置的认证方式进行身份认证
@PostMapping("/login")
public String login(@RequestBody UserReq req) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(req.getUsername(), req.getPassword())
);
System.out.println(req);
System.out.println(authentication);
return "";
}