The article directories

    • Why try sa-Token
    • What is an SA-token?
    • What can an SA-Token do?
    • Rapid integration
      • Rely on the import
      • The configuration file
      • The login
      • logout
      • Request interception authentication
        • Permissions and role extensions
      • Cluster environment
        • Rely on the import
        • The configuration file
    • conclusion

At present, I only integrate for learning and experimenting purposes. I do not recommend using it in a formal environment such as the company, which still recommends Shiro and Spring Security. (Wait till I see the effect)

Why try sa-Token

Before I’m still pretty exclusive domestic small workshops of open source works, after all, not red seedling root is, but as the open source community to vigorously develop the domestic in recent years, as well as contact and learn a lot in the work at ordinary times, slowly changed my view, people actually open source work is also very sweet, the Api easy to use, source and official documents are in Chinese, It has rich functions and can meet many Chinese-style needs. Various QQ and wechat communication groups are very active. In short, it can meet chinese-style needs to a great extent.

In the domain of authorization authentication framework, Shiro and Spring Security are the most used. However, one day when I was browsing the same gender dating website (Github), I suddenly found that sa-Token is a lightweight Java authorization framework with a number of 2K stars. After looking at its characteristics and function points, I was aroused by my strong curiosity, and thus had today’s taste.

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), and OAuth2.0

Framework for kicking people offline, automatic renewal, front and background separation, distributed session… Through sa-token, you can realize the permission authentication part of the system in a simple way

Compared with other permission authentication frameworks, SA-Token has the following advantages:

  1. Simple: zero configuration startup framework, real out of the box, low-cost start
  2. Powerful: It integrates dozens of permission-related features, covering solutions in most service scenarios
  3. Easy to use: Silky API calls and a host of advanced features all in one line of code
  4. High scalability: Almost all components provide an extension interface, and more than 90% of the logic can be rewritten on demand

What can an SA-Token do?

  • Login authentication – Easy login authentication with five segmented scenario values
  • Authorization authentication – To adapt to the RBAC authorization model, different roles are authorized differently
  • Session – A professional data caching center
  • Kick the user offline – immediately remove the illegal user offline
  • Persistence layer extension – can integrate Redis, Memcached and other professional cache middleware, restart data is not lost
  • Distributed session – Provides two distributed session solutions, JWT integration and shared data center
  • Single sign-on (SSO) – One login, access everywhere
  • Simulate other’s account – Real-time operation of any user status data
  • Temporary Identity Switch – Temporarily switch the session identity to another account
  • Cookie-free mode: Scenarios where front and back are separated, such as APPS and small programs
  • Mutually exclusive login – like QQ, both mobile phones and computers are online at the same time, but the login on both mobile phones is mutually exclusive
  • Multi-account authentication system – for example, the user and admin tables of a mall project are authenticated separately
  • Fancy Token Generation — There are six built-in token styles and custom token generation strategies
  • Annotated authentication – elegantly separates authentication from business code
  • Route interception authentication: Restful authentication based on route interception
  • Automatic renewal – Provides two token expiration policies that can be flexibly used together and can be automatically renewed
  • Session governance – Provides a convenient and flexible session query interface
  • Remember me mode – adapt [Remember me] mode, restart the browser without authentication
  • Password encryption: Provides the password encryption module, which can be used for fast MD5, SHA1, SHA256, AES, and RSA encryption
  • Automatic component injection — zero configuration integration with frameworks like Spring

Rapid integration

Rely on the import

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

The latest version of maven is 1.15.2.

The configuration file

You can start the project with zero configuration, but you can also add the following configuration to application.yml to customize the use frame:

spring: 
    # 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)
        allow-concurrent-login: 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
Copy the code

The login

	@PostMapping("/api/v1/login")
    @ApiOperationSupport(order = 1)
    @apiOperation (value = "login ")
    public Response login(String userName, String pwd) {
        log.info("Login, username: {}, PWD: {}", userName, pwd);
        // Simulate the verification user name and password
        Long userId = check(userName,pwd);
        StpUtil.setLoginId(userId);
        return Response.ok(StpUtil.getTokenInfo());
    }
Copy the code

The core line is stputil.setLoginID (userId). Let’s see what it does for us.

Source code and its simple, there are a lot of Chinese notes, follow read on the line, directly stick to the conclusion.

  • Create a token
  • Create SaSession
  • The token signature was recorded in the session
  • Example Create token and loginId mappings
  • Write a cookie token

Stores such as underlying sessions use maps

The source code is as follows:

/** * data set */
public Map<String, Object> dataMap = new ConcurrentHashMap<String, Object>();

/** * Expiration time set (milliseconds), records the expiration time of all keys */
public Map<String, Long> expireMap = new ConcurrentHashMap<String, Long>();
Copy the code

The result is as follows:

  • Response Heards
Connection: keep-alive
Content-Type: application/json
Date: Fri, 09 Apr 2021 07:33:59 GMT
Keep-Alive: Timeout = 60 / / keySet-Cookie: LakerToken=da14afd3f4b648a889a1e51ac3ec53d7; Max-Age=1800; Expires=Fri, 09-Apr-2021 08:03:59 GMT; Path=/
Transfer-Encoding: chunked
Copy the code
  • Response Body
{
	"code": 200."msg": ""."data": {
		"tokenName": "LakerToken"."tokenValue": "da14afd3f4b648a889a1e51ac3ec53d7"."isLogin": true."loginId": "1"."loginKey": "login"."tokenTimeout": 1784."sessionTimeout": 1784."tokenSessionTimeout": 2 -."tokenActivityTimeout": 30."loginDevice": "default-device"}}Copy the code

Can see return heards have automatically Set: the Set – cookies: LakerToken = da14afd3f4b648a889a1e51ac3ec53d7; Max-Age=1800; Expires=Fri, 09-Apr-2021 08:03:59 GMT; Path=/

logout

    @PostMapping("/api/v1/loginOut")
    @ApiOperationSupport(order = 3)
    @apiOperation (value = "log out ")
    @SaCheckLogin
    public Response loginOut(a) {
        StpUtil.logout();
        return Response.ok();
    }
Copy the code

The core is also a line of stputil.logout (). Let’s see what it does for us.

  • To obtainHttpRequest
  • Attempt to read token from request
  • Attempt to read token from request body
  • Try to read the token from the header
  • Attempt to read token from cookie
  • Delete the cookie
  • Delete the token and loginId mappings
  • The cancellation of the session

Request interception authentication

Step 1: Configure the global interceptor

@Configuration
public class MySaTokenConfig implements WebMvcConfigurer {
	/** * Register the sa-token interceptor and turn on annotated authentication (if you don't need this feature, you can remove it) */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/ * *"); }}Copy the code

Step 2: Annotate the class or method you want to intercept

  • @SaCheckLogin: indicates that on a method or class, the current session must be logged in to pass verification
  • @SaCheckRole("admin"): mark On a method or class, the current session must have the specified role identifier to pass the verification
  • @SaCheckPermission("user:add"): annotation On a method or class, the current session must have the specified permission to pass the verification

Such as:

    @GetMapping("/api/v1/tokenInfo")
    @ApiOperationSupport(order = 2)
    @apiOperation (value = "get token information for current session ")
    @SaCheckLogin
    public Response tokenInfo(a) {
        return Response.ok(StpUtil.getTokenInfo());
    }
Copy the code

If @sachecklogin is added, the interface must be in the login state to pass verification.

How does core intercept verification work here? May have a look SaAnnotationInterceptor. Java source code, based on the interceptor for SpringMvc block the implementation check.

The functions are as follows:

  • Verify the login
  • Verify the role
  • Verify permissions

The implementation process principle is as follows:

  • Obtain the token in HttpRequest

    • Attempt to read token from request
    • Attempt to read token from request body
    • Try to read the token from the header
    • Attempt to read token from cookie
  • Judge the token

    • Invalid token
    • overdue
    • By offline
    • Kicked offline
  • Automatic renewal

Permissions and role extensions

Directly implement the StpInterface interface, overwrite the getPermissionList and getRoleList methods.

@Component
public class StpInterfaceImpl implements StpInterface {
    /** * returns the set of permissions that an account has */
    @Override
    public List<String> getPermissionList(Object loginId, String loginKey) {
       xxx
    }
    /** * returns a set of role identifiers owned by an account */
    @Override
    public List<String> getRoleList(Object loginId, String loginKey) {
        xxx
    }
}
Copy the code

Cluster environment

By default, sa-Token stores session data in memory. This mode has the fastest read and write speed and avoids performance consumption caused by serialization and deserialization. However, this mode has some disadvantages, such as data loss after restart and data cannot be shared in cluster mode.

Therefore, sa-Token abstracts all data persistence operations into SaTokenDao interface. This design can ensure that developers can flexibly extend the framework. For example, we can store session data in Redis, Memcached and other professional cache middleware, so that restart data is not lost. Moreover, the session consistency of multiple nodes in distributed environment is guaranteed.

In addition to the default memory-based implementation provided by SaTokenDao within the framework, we used the Redis extension provided by the official website.

Rely on the import

<! -- Sa-token integration redis (using Jackson serialization) -->
<dependency>
    <groupId>cn.dev33</groupId>
    <artifactId>sa-token-dao-redis-jackson</artifactId>
    <version>1.15.2</version>
</dependency>
<! Redis connection pool -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>
Copy the code

With Jackson serialization, Session serialization is readable and can be changed manually

The configuration file

spring: 
    # redis configuration
    redis:
        # Redis database index (default 0)
        database: 0
        # Redis server address
        host: 127.0. 01.
        # Redis server connection port
        port: 6379
        # Redis server connection password (default null)
        # password: 
        Connection timeout (ms)
        timeout: 1000ms
        lettuce:
            pool:
                # Maximum number of connections in the pool
                max-active: 200
                Maximum connection pool blocking wait time (negative value indicates no limit)
                max-wait: -1ms
                The maximum number of free connections in the connection pool
                max-idle: 10
                Minimum free connection in connection pool
                min-idle: 0
Copy the code

After importing dependencies and configurations, the framework automatically uses Redis storage.

conclusion

Preliminary attempt is quite good, documents and code examples are very full, basic functions can meet, the source code is simple and easy to understand, can be open at will, packaging degree is very high, do not understand the principle is easy to become a tool, others and so on for a period of time to comment.

Reference:

  • sa-token.dev33.cn/

  • Github.com/dromara/sa-…


    Keep warm together and make progress together

🍎QQ group [837324215] 🍎 pay attention to my public number [Java Factory interview officer], learn together 🍎🍎🍎 🍎 personal vx [Lakernote]