springboot扫码登录
时间: 2023-07-01 10:15:20 浏览: 48
以下是一个简单的Spring Boot扫码登录示例代码,使用了Google提供的ZXing扫码库和Spring Security:
1. 在pom.xml文件中添加依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
```
2. 创建一个实体类用于存储扫码登录状态:
```
@Entity
public class QrCodeLogin {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String code;
@OneToOne
private User user;
private boolean used;
// getter and setter...
}
```
3. 创建一个Controller用于生成和验证扫码登录二维码:
```
@RestController
@RequestMapping("/qrcode")
public class QrCodeController {
private final QrCodeLoginRepository qrCodeLoginRepository;
public QrCodeController(QrCodeLoginRepository qrCodeLoginRepository) {
this.qrCodeLoginRepository = qrCodeLoginRepository;
}
@GetMapping
public ResponseEntity<byte[]> generateQrCode(HttpSession session) throws WriterException, IOException {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// 生成唯一的二维码字符串
String code = UUID.randomUUID().toString();
// 保存二维码信息到数据库中
QrCodeLogin qrCodeLogin = new QrCodeLogin();
qrCodeLogin.setCode(code);
qrCodeLogin.setUser(user);
qrCodeLogin.setUsed(false);
qrCodeLoginRepository.save(qrCodeLogin);
// 生成二维码图片
ByteArrayOutputStream out = new ByteArrayOutputStream();
QRCodeWriter writer = new QRCodeWriter();
BitMatrix bitMatrix = writer.encode(code, BarcodeFormat.QR_CODE, 200, 200);
MatrixToImageWriter.writeToStream(bitMatrix, "png", out);
byte[] imageBytes = out.toByteArray();
// 将二维码字符串保存到session中
session.setAttribute("qrCode", code);
// 返回二维码图片
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
}
@GetMapping("/check")
public ResponseEntity<String> checkQrCode(HttpSession session) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// 从session中获取二维码字符串
String code = (String) session.getAttribute("qrCode");
// 根据二维码字符串从数据库中获取扫码信息
QrCodeLogin qrCodeLogin = qrCodeLoginRepository.findByCode(code);
if (qrCodeLogin != null && !qrCodeLogin.isUsed() && qrCodeLogin.getUser().equals(user)) {
// 将扫码信息标记为已使用
qrCodeLogin.setUsed(true);
qrCodeLoginRepository.save(qrCodeLogin);
// 清除session中的二维码字符串
session.removeAttribute("qrCode");
return ResponseEntity.ok("登录成功");
} else {
return ResponseEntity.ok("登录失败");
}
}
}
```
4. 在Spring Security配置类中添加扫码登录相关配置:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsService userDetailsService;
private final PasswordEncoder passwordEncoder;
private final QrCodeAuthenticationProvider qrCodeAuthenticationProvider;
public SecurityConfig(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder, QrCodeAuthenticationProvider qrCodeAuthenticationProvider) {
this.userDetailsService = userDetailsService;
this.passwordEncoder = passwordEncoder;
this.qrCodeAuthenticationProvider = qrCodeAuthenticationProvider;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login/**", "/qrcode/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/")
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.and()
.addFilterBefore(qrCodeAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.authenticationProvider(qrCodeAuthenticationProvider);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
auth.authenticationProvider(qrCodeAuthenticationProvider);
}
private QrCodeAuthenticationFilter qrCodeAuthenticationFilter() throws Exception {
QrCodeAuthenticationFilter qrCodeAuthenticationFilter = new QrCodeAuthenticationFilter();
qrCodeAuthenticationFilter.setAuthenticationManager(authenticationManager());
qrCodeAuthenticationFilter.setAuthenticationSuccessHandler(new QrCodeAuthenticationSuccessHandler());
return qrCodeAuthenticationFilter;
}
}
```
5. 创建一个QrCodeAuthenticationFilter用于处理扫码登录请求:
```
public class QrCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public QrCodeAuthenticationFilter() {
super(new AntPathRequestMatcher("/qrcode/login", "POST"));
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
String code = request.getParameter("code");
QrCodeAuthenticationToken token = new QrCodeAuthenticationToken(code);
return this.getAuthenticationManager().authenticate(token);
}
}
```
6. 创建一个QrCodeAuthenticationToken用于存储扫码登录信息:
```
public class QrCodeAuthenticationToken extends AbstractAuthenticationToken {
private final String code;
public QrCodeAuthenticationToken(String code) {
super(null);
this.code = code;
}
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getPrincipal() {
return null;
}
public String getCode() {
return code;
}
}
```
7. 创建一个QrCodeAuthenticationProvider用于处理扫码登录验证:
```
public class QrCodeAuthenticationProvider implements AuthenticationProvider {
private final QrCodeLoginRepository qrCodeLoginRepository;
public QrCodeAuthenticationProvider(QrCodeLoginRepository qrCodeLoginRepository) {
this.qrCodeLoginRepository = qrCodeLoginRepository;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String code = (String) authentication.getCredentials();
QrCodeLogin qrCodeLogin = qrCodeLoginRepository.findByCode(code);
if (qrCodeLogin != null && !qrCodeLogin.isUsed()) {
User user = qrCodeLogin.getUser();
// 标记扫码信息为已使用
qrCodeLogin.setUsed(true);
qrCodeLoginRepository.save(qrCodeLogin);
// 返回用户信息
return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
} else {
throw new BadCredentialsException("扫码信息无效");
}
}
@Override
public boolean supports(Class<?> authentication) {
return QrCodeAuthenticationToken.class.isAssignableFrom(authentication);
}
}
```
8. 创建一个QrCodeAuthenticationSuccessHandler用于处理扫码登录成功后的跳转:
```
public class QrCodeAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_OK);
}
}
```
以上代码仅为示例,实际应用中还需要根据具体业务逻辑进行修改。