I’m participating in nuggets Creators Camp # 4. Click here to learn more!

preface

Shiro is easy to learn and lightweight. However, when I use it personally, I think sa-Token is easier to learn than Shiro. Basically out of the box.

What is an SA-token?

Sa-token is a lightweight Java permission authentication framework, which mainly solves a series of permission related problems such as login authentication, permission authentication, Session Session, single sign-on (SSO), OAuth2.0, and micro-service network authentication.

How to use it?

Introduction of depend on

<dependency>
    <groupId>cn.dev33</groupId>
    <artifactId>sa-token-spring-boot-starter</artifactId>
    <version>1.29.0</version>
</dependency>
Copy the code

The sample code

The login interface is a single line: stputil.login (ID)

@RestController
@RequestMapping
public class LoginController {

    @GetMapping("doLogin")
    public ResultModel doLogin(String name, String pwd) {
        // This is only a simulation example. Real projects need to query data from the database for comparison
        if("jayjay".equals(name) && "123456".equals(pwd)) {
            StpUtil.login(1001);
            return ResultModel.success("Login successful",StpUtil.getTokenInfo());
        }
        return ResultModel.error("Login failed");
    }

    @GetMapping("isLogin")
    public ResultModel isLogin(a) {
        return ResultModel.success("Login or not:"+StpUtil.isLogin(),StpUtil.getTokenInfo());
    }

    @GetMapping("logout")
    public ResultModel logout(a) {
        StpUtil.logout();
        return ResultModel.success("Logout successful"); }}Copy the code

Let’s log in:

If the login is successful, request isLogin to test whether the login is successful and obtain the current login user

That’s right. In SA-Token, login authentication is as simple as that. It doesn’t require any complicated pre-processing, just one line of API calls.

So how do you verify your login? Just call this method where you need to verify the login:

// Then call the following method where you want to validate the login:
// If the current session is not logged in, this code throws a NotLoginException exception
StpUtil.checkLogin();
Copy the code

You can also use annotations or interceptors, but more on that later

Commonly used method

Most of the functions in sa-Token can be done in one line of code. Here are some common methods:

StpUtil.login(10001);    // Marks the id of the current session login account
StpUtil.getLoginId();    // Obtain the id of the current session login account
StpUtil.isLogin();    // Gets whether the current session is logged in, returning true or false
StpUtil.logout();    // The current session is logged out
StpUtil.kickout(10001);    // Kick the session with account 10001 offline
StpUtil.hasRole("super-admin");    // Checks whether the current account contains the specified role id. Returns true or false
StpUtil.hasPermission("user:add");    // Check whether the current account has specified permissions. Return true or false
StpUtil.getSession();    // Get the Session of the current account ID
StpUtil.getSessionByLoginId(10001);    // Obtain the Session whose id is 10001
StpUtil.getTokenValueByLoginId(10001);    // Obtain the token value of account 10001
StpUtil.login(10001."PC");    // Specify the device id for login. This is usually used for mutually exclusive login.
StpUtil.kickout(10001."PC");    // Specify an account, specify a device id, and kick it offline (different terminals are not affected)
StpUtil.openSafe(120);    // Enable level-2 authentication for the current session. The validity period is 120 seconds
StpUtil.checkSafe();    // Verifies whether the current session is in the level-2 authentication period. If the verification fails, an exception will be thrown
StpUtil.switchTo(10044);    // Temporarily switch the current session id to another account
Copy the code

Commonly used annotations

  • @SaCheckLogin: Login authentication – This method can only be accessed after login
  • @SaCheckRole("admin"): Role authentication – You must have the specified role identity to enter this method
  • @SaCheckPermission("user:add"): Permission authentication – You must have specified permissions to access this method
  • @SaCheckSafe: Level 2 authentication verification – Level 2 authentication is required to enter this method
  • @SaCheckBasic: HttpBasic Authentication – This method can only be accessed if you have passed Basic authentication

The above notes can be seen in the official website usage, I will not list one

However, before using annotations, you must turn the Sa-Token interceptor on, which is turned off by default

Register interceptors

Using SpringBoot2.0 as an example, create a new configuration class satokenconfigure.java

@configuration public class SaTokenConfigure implements WebMvcConfigurer {// Public void addInterceptors(InterceptorRegistry registry) {Override public void addInterceptors(InterceptorRegistry registry) { Registry. AddInterceptor (new SaAnnotationInterceptor()).addPathPatterns("/**"); }} Copy to clipboard error copy success 123456789Copy the code

Ensure that this class is scanned by the SpringBoot boot class

Spring integration of the boot

The integration is simple, just add dependencies, and sa-Token can be started with zero configuration in Spring Boot, as in the above test case

Of course, can also be configured according to their own needs

1. Configure in application.yml

# Sa - Token configuration
sa-token: 
    # token name (also cookie name)
    token-name: satoken
    The value -1 indicates that the token will never expire
    timeout: 2592000
    # Token temporary validity period (if no operation is performed within the specified period, the token is regarded as expired) unit: second
    activity-timeout: - 1
    # allow concurrent logins with the same account (true allows simultaneous logins, false allows new logins to replace old logins)
    is-concurrent: true
    # Whether to share one token when multiple users log in to the same account (if true, all logins share one token, if false, create one token for each login)
    is-share: false
    Style # token
    token-style: uuid
    # Whether to output operation logs
    is-log: false
Copy the code

2. Configure through code

/** */ @configuration public class SaTokenConfigure {// @bean@primary public SaTokenConfig getSaTokenConfigPrimary() {SaTokenConfig config = new SaTokenConfig(); config.setTokenName("satoken"); // Token name (also the cookie name) config.setTimeout(30 * 24 * 60 * 60); / / token is valid, the unit s default config. 30 days setActivityTimeout (1); // Token temporary validity period (if no operation is performed within the specified period, the token is regarded as expired) Unit: second config.setisConcurrent (true); Config.setisshare (true); config.setisshare (true); Config.settokenstyle ("uuid"); // token config.setislog (false); // Whether to output operation logs return config; }}Copy the code

The above configuration is not all configuration, all configuration can be viewed on the official website, according to their own needs to choose to use

conclusion

There are many other functions not introduce one by one, interested can go to the Sa – Token website, preliminary attempt is quite good, documentation and code samples are complete, can satisfy the basic function, source code simple and easy to understand, to 2, encapsulation degree is very high, because of the development of Chinese, comments are in Chinese, look not to understand don’t have to worry about. If you’re looking for an out-of-the-box login authorization framework, you can choose sa-Token, especially for small projects.