今天分享的是 Spring Boot
整合 Sa-Token
實現登入認證。
依賴
首先,我們需要新增依賴:
- 關鍵依賴:
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-spring-boot-starter</artifactId>
<version>1.28.0</version>
</dependency>
- 其他依賴:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.fengwenyi</groupId>
<artifactId>JavaLib</artifactId>
<version>2.1.5</version>
</dependency>
<dependency>
<groupId>com.fengwenyi</groupId>
<artifactId>api-result</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
登入
- 構造使用者資料
public class UserData {
private static final Map<String, User> users = Map.of(
"u1", new User("01", "u1", "123456", List.of("ROLE_USER")),
"a2", new User("02", "a2", "123456", List.of("ROLE_ADMIN", "ROLE_USER"))
);
public static class User {
public String uid;
public String username;
public String password;
public List<String> roles;
public User(String uid, String username, String password, List<String> roles) {
this.uid = uid;
this.username = username;
this.password = password;
this.roles = roles;
}
}
public static User queryByUsername(String username) {
return users.get(username);
}
public static List<String> queryRolesByUid(String uid) {
for (Map.Entry<String, User> entry : users.entrySet()) {
if (uid.equals(entry.getValue().uid)) {
return entry.getValue().roles;
}
}
return null;
}
}
- 登入認證
@RestController
@RequestMapping("/auth")
public class AuthController {
@PostMapping("/login")
public ResponseTemplate<LoginResponseVo> login(@RequestBody @Validated LoginRequestVo requestVo) {
String username = requestVo.getUsername();
String password = requestVo.getPassword();
UserData.User user = UserData.queryByUsername(username);
if (Objects.isNull(user)) {
return ResponseTemplate.fail("使用者名稱不正確");
}
if (!user.password.equals(password)) {
return ResponseTemplate.fail("密碼不正確");
}
StpUtil.login(user.uid);
LoginResponseVo responseVo = new LoginResponseVo()
.setToken(StpUtil.getTokenValue())
;
return ResponseTemplate.success(responseVo);
}
}
關鍵程式碼
StpUtil.login(user.uid);
LoginResponseVo responseVo = new LoginResponseVo()
.setToken(StpUtil.getTokenValue())
;
- 測試
請求:
POST localhost:8080/auth/login
{
"username": "u1",
"password": "123456"
}
響應:
{
"code": 0,
"message": "Success",
"success": true,
"body": {
"token": "f2f9a82f-bc6a-460a-877e-9d3e4c8867de"
}
}
退出登入
@RestController
@RequestMapping("/auth")
public class AuthController {
@PostMapping("/logout")
public ResponseTemplate<Void> logout() {
StpUtil.logout();
return ResponseTemplate.success();
}
}
前後端分離
header 新增
satoken
= f2f9a82f-bc6a-460a-877e-9d3e4c8867de
到這裡,登入就算完成了,希望今天的分享能夠在工作中幫助到你。