sa token是一个全新的权限框架,相比spring security和apache shiro来说,使用起来更加便捷,配置更少,侵入性更小。
下面是一个简单的登录认证示例,以一个spring boot+thymeleaf来实现具体逻辑
首先导入sa token的Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-spring-boot-starter</artifactId>
<version>1.26.0</version>
</dependency>
配置文件application.yml,更多的sa token配置请参考Sa-Token
server:
port: 8080
spring:
application:
name: sa-simple-auth
thymeleaf:
cache: false
sa-token:
token-name: satoken
timeout: -1
token-style: simple-uuid
spring boot启动类
@SpringBootApplication
@Slf4j
public class SaTokenAuthenticationExampleApp {
public static void main(String[] args) {
SpringApplication.run(SaTokenAuthenticationExampleApp.class, args);
log.info("Sa-Token配置:{}", SaManager.getConfig());
}
}
业务逻辑控制器,具体的逻辑非常简单,doLogin方法验证登录页输入的用户名和密码,成功直接调用sa token的工具方法StpUtil.login(用户ID)登录 ,并跳转到登录成功页;失败则跳转到失败页面。
@Controller
public class SimpleAuthenticateController {
@GetMapping("/home")
public String home(Model model){
if(StpUtil.isLogin()){
model.addAttribute("loginId", StpUtil.getLoginId());
return "home";
}
return "redirect:/login";
}
@GetMapping("/login")
public String login(){
return "login";
}
@PostMapping("/doLogin")
public String doLogin(String username, String password){
if("admin".equals(username) && "123456".equals(password)){
StpUtil.login(10001);
return "loginSucceed";
}
return "loginFailed";
}
@GetMapping("/doLogout")
public String doLogout(){
StpUtil.logoutByLoginId(10001);
return "redirect:/login";
}
}
login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>login</title>
<link type="text/css" rel="stylesheet" th:href="@{/css/login.css}"/>
</head>
<body>
<form id="login-form" th:action="@{/doLogin}" method="post">
<div>
<label>用户名:</label>
<input name="username"/>
</div>
<div>
<label>密 码:</label>
<input name="password" type="password"/>
</div>
<div>
<button type="submit">登录</button>
</div>
</form>
</body>
</html>
home.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>主页</title>
</head>
<body>
<h3>主页</h3>
<p>欢迎!<span th:text="${loginId}"></span></p>
<a th:href="@{/doLogout}">退出</a>
</body>
</html>
loginFailed.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>登录失败</title>
</head>
<body>
登录失败! <a th:href="@{/login}">登录</a>
</body>
</html>
loginSucceed.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>登录成功</title>
</head>
<body>
登录成功! <br/>
<a th:href="@{/home}">进入主页</a> | <a th:href="@{/doLogout}">退出</a>
</body>
</html>