欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > saToken的集成和使用

saToken的集成和使用

2025/5/21 7:34:16 来源:https://blog.csdn.net/qq_55121347/article/details/141783845  浏览:    关键词:saToken的集成和使用

官网:Sa-Token

1.导入依赖

        <dependency><groupId>cn.dev33</groupId><artifactId>sa-token-spring-boot3-starter</artifactId><version>1.39.0</version></dependency>

2.写入配置

sa-token:  # sa-token ??????token-name: satoken  # ????????????? "satoken"timeout: 2592000  # ?????????????2592000 ??? 30 ?????????? 30 ?????is-concurrent: true  # ?????????????? true?????????????????? false??????????????????????is-share: true  # ???????????????? true?????????????????????? false???????????????token-style: uuid  # ????????????? "uuid"?????????? UUID?????????????is-log: true  # ?????????????? true?????????????????? false????????

3.创建配置文件,用于拦截和过滤

package com.satokentest.config;import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.interceptor.SaInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class SaTokenConfig implements WebMvcConfigurer {// 注册 Sa-Token 拦截器@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new SaInterceptor()).addPathPatterns("/**");}// 注册 Sa-Token 过滤器@Beanpublic SaServletFilter getSaTokenFilter() {return new SaServletFilter().addInclude("/**")  // 拦截的路径.addExclude("/favicon.ico");  // 排除的路径// 可以根据需要增加其他排除路径,如:.addExclude("/public/**")}
}

4.认证和登出等方法

在官网中使用方法,这是例子

    @GetMapping("/login")public Result login(String username, String password) {List<User> users = userService.getUsers(username,password);if (users.size() == 0) {return Result.fail("用户名或密码错误");} else {// 会话登录:参数填写要登录的账号id,建议的数据类型:long | int | String, 不可以传入复杂类型,如:User、Admin 等等StpUtil.login(users.get(0).getId());return Result.success(users);}
//当前会话登录
StpUtil.login();// 当前会话注销登录
StpUtil.logout();// 获取当前会话是否已经登录,返回true=已登录,false=未登录
StpUtil.isLogin();// 检验当前会话是否已经登录, 如果未登录,则抛出异常:`NotLoginException`
StpUtil.checkLogin();

5.权限和角色的校验

写一个配置类,这里虽然打了@Component但是不需要我们来进行调用

package com.satokentest.config;import cn.dev33.satoken.stp.StpInterface;
import org.springframework.stereotype.Component;import java.util.List;@Component
public class StpInterfaceImpl implements StpInterface {@Overridepublic List<String> getPermissionList(Object loginId, String loginType) {//这里我没写,就是查询这个用户的所有权限// 返回此loginId所拥有的权限列表listreturn null;}@Overridepublic List<String> getRoleList(Object loginId, String loginType) {//这里我没写,就是查询这个用户的所有角色// 返回此loginId所拥有的角色列表listreturn null;}
}

这样就完成了saToken的基本使用

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词