国产化驱动经济自主性与科技创新的未来之路
556
2022-11-07
SpringBoot整合Sa
目录依赖登录退出登录前后端分离
今天分享的是 Spring Boot 整合 Sa-Token 实现登录认证。
依赖
首先,我们需要添加依赖:
关键依赖:
其他依赖:
登录
构造用户数据
public class UserData {
private static final Map
"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;
pubhttp://lic String username;
public String password;
public List
public User(String uid, String username, String password, List
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
for (Map.Entry
if (uid.equals(entry.getValue().uid)) {
return entry.getValue().roles;
}
}
return null;
}
}
登录认证
@RestController
@RequestMapping("/auth")
public class AuthController {
@PostMapping("/login")
public ResponseTemplate
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
StpUtil.logout();
return ResponseTemplate.success();
}
}
前后端分离
header 添加
satoken = f2f9a82f-bc6a-460a-877e-9d3e4c8867de
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~