SoFunction
Updated on 2025-03-08

Sa-token integration code example display in springboot

sa-tokenis a lightweight Java permission authentication framework that can be easily integrated into Spring Boot projects to provide concise authentication and authorization functions. Althoughsa-tokenIt does not directly support the integration of OAuth 2.0, but you can combine the authentication process of OAuth 2.0 withsa-tokenThe permission control is used in combination.

Here is a simple example showing how tosa-tokenIntegrated into Spring Boot project:

Add tosa-tokenRely on yoursIn the file:

<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-spring-boot-starter</artifactId>
<version>Latest version</version>
</dependency>

Make sure you are using the latestsa-tokenVersion.

  • existorMedium configurationsa-token
# Examplesa-token:
token-name: Authorization # token name (key in header)token-type: bearer # token type (prefix of value in header)timeout: 3600 # token Expiration time, unit secondsactivity-timeout: -1 # Temporary token valid time, unit seconds, -1 means never expiredis-concurrent: true # Whether to allow concurrent login for the same account, default falseis-share: false # Sharing among multiple servicestokenhour,Need to be set totrue
  • Create a configuration class to initializesa-token
import cn.;
import cn.;
import cn.;
import cn.;
import ;
import ;
import ;
import ;
@Configuration
@AutoConfigureAfter()
public class SaTokenConfig {
@Bean
@ConditionalOnMissingBean
public SaTokenFilter saTokenFilter(SaTokenProperties saTokenProperties) {
return new SaTokenFilter(saTokenProperties);
}
// You can add custom SaToken initialization code here// For example: Set global permission verification rules, login verification processing, etc.@Bean
public void initSaToken() {
// Initialize Sa-Token and set global permission verification rules((request, response, exception) -> {
// Here you can customize the global permission verification logic// For example: Return custom unauthorized prompt information("application/json;charset=UTF-8");
().write("{\"code\":401,\"msg\":\"Unauthorized\"}");
().flush();
().close();
});
}
}
  • Use in your Controllersa-tokenThe annotations provided for permission control:
import cn.;
import cn.;
import ;
import ;
@RestController
public class MyController {
@GetMapping("/needPermission")
@SaCheckPermission("permission1") // Here we will verify whether the user has permission1 permissionpublic String needPermission() {
return "you have permission1";
}
@GetMapping("/needRole")
@SaCheckRole("admin") // Here we will verify whether the user has the admin rolepublic String needRole() {
return "you are admin";
}
}

This is the article about sa-token integrating the code in springboot. For more related sa-token integrating the springboot content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!