Can a login function play so many tricks? sa-token takes you to easily handle multiple logins, single logins, and same-end mutual exclusion logins

demand scene

Speaking of login, you may dismiss it, is there any simpler function than this?

Get the parameters submitted by the user username+ passwordcompare with the database, if there is a record, return [login success], if there is no record, return [username or password error]

What, that's it?

After you have skillfully packaged, deployed, and started the project and started fishing for a day, the product manager can't sit still

"Xiao Shunzi, let's see if we can add a function to our APP login, that is... that... After a user logs in, it can automatically push the previous one to log off."

At this time, you are lost in thought, how to let him squeeze the session of the previous logger offline after logging in?

Do you want to loop through it after each login Session列表, find the session with the same account as this user and log it out? If you are smart, you immediately think that this solution will bring huge performance pressure to the server!

So what to do? Is it necessary to build a Map userId做keyto Session做valueestablish a mapping relationship, and then manually take it out Sessionand mark it [already pushed offline]?

Just do it, when you roll up your sleeves, click on the above logic, and then test, package, deploy, and upload in one go, and start another day of fishing...

However, you still underestimate the brain power of the product manager

"Xiao Shunzi, you see that there is a small problem with the function you wrote. Every time I log in, other logins will be squeezed out."

At this time, you subconsciously retorted: "What's the problem? Isn't this the effect you want?"

"en... that is... can we do this, if I log in on my mobile phone, can I just squeeze other mobile phones offline, but the ones already logged in on my computer will not be affected"

"Squeeze out must be all squeezed out, how can it be possible to leave only your computer without squeezing out? The function you want is impossible to achieve"

At this time, the product manager smiled slightly and released a big move:

"Then how did Tencent QQ do it?"

A word of critical hit 99999+, suddenly you are speechless, yes, 腾讯QQhow to achieve this function? One QQ number can be online on both mobile phone and computer at the same time, but not on two mobile phones at the same time

Could it be that the device ID of each login is recorded when logging in? Circularly detect the device name of the login list, the same device is squeezed out, and different devices remain logged in?

The product manager rushed to the coffee and left the room with a triumphant smile, leaving you with a sad face, thinking hard about the realization of the plan...


topic

Well, having said so much, let's enter today's topic——sa-token, an authority authentication framework that allows you to easily solve various login problems!

As mentioned in the above scenario, the problems you encounter are nothing more than three typical login models: multi-site login, single-site login, and mutually exclusive login on the same end

  • Multi-location login: means that the same account can log in at any place at the same time without affecting each other
  • Single sign-on: An account can only be logged in at one location at a time, and new logins will crowd out old logins
  • Mutually exclusive login on the same terminal: only single-site login is allowed on the same type of device, and simultaneous online access is allowed on different types of devices

Next, let's see sa-tokenhow to easily handle these three login problems using

Multiple logins

This mode is relatively simple, and sa-tokenthe default mode is the multi-site login mode

  1. First add pom.xmlthe frame
<!-- sa-token 权限认证, 在线文档:http://sa-token.dev33.cn/ -->
<dependency>
	<groupId>cn.dev33</groupId>
	<artifactId>sa-token-spring-boot-starter</artifactId>
	<version>1.12.1</version>
</dependency>
  1. Write the account id into the session when the user logs in
@RestController
@RequestMapping("user")
public class UserController {
    
    
	@RequestMapping("doLogin")
	public String doLogin(String username, String password) {
    
    
		// 此处仅作示例模拟,真实项目需要从数据库中查询数据进行比对 
		if("zhang".equals(username) && "123456".equals(password)) {
    
    
			StpUtil.setLoginId(10001);
			return "登录成功";
		}
		return "登录失败";
	}
}
  1. Create a new startup class
@SpringBootApplication
public class SaTokenDemoApplication {
    
    
	public static void main(String[] args) {
    
    
		SpringApplication.run(SaTokenDemoApplication.class, args); 
		System.out.println("\n启动成功:sa-token配置如下:" + SaTokenManager.getConfig());
	}
}

So far, we have completed all the codes for multi-location login. The above code will not do anything to the old session when multiple people log in to the same account. The same account can log in at any location without affecting each other.

single sign on

单地登录The only 多地登录difference is that you need to change the yml configuration file

spring: 
    # sa-token配置
    sa-token: 
        allow-concurrent-login: false

allow-concurrent-loginThe meaning of the configuration item is: whether to allow the same account to log in concurrently (when this value is true, it allows to log in together, and when it is false, the new login squeezes out the old login)

Other codes are the same as [Multi-site login]. When we log in to the same account in two browsers, the old session will access the system again and we will get the following prompt:

{
    
    
	"code": 401,
	"msg": "token已被顶下线",
	"data": null,
	"dataCount": null
}

Mutually exclusive login at the same end

Well, finally came the final problem, mutual exclusive login on the same side allows us to 腾讯QQonly allow single-site login on the same type of device, and allow simultaneous online access on different types of devices

So sa-tokenhow to achieve mutually exclusive login at the same end?

First 单地登录, in the configuration file, allowConcurrentLoginconfigure as false, and then declare the device identifier when calling login and other related interfaces:

Specify device ID login
StpUtil.setLoginId(10001, "PC");    

After calling this method to log in, the same device will be offline (different devices will not be affected), and NotLoginExceptionan exception , scene value=-4

Specify device ID to force logout (kick people offline)
StpUtil.logoutByLoginId(10001, "PC");		

If the second parameter is filled with null or not filled, it means that the account id will be kicked offline from the online terminal, and NotLoginExceptionan exception , scene value = -5

Query the currently logged-in device ID
StpUtil.getLoginDevice(); 

end

The above are sa-tokenthe various skills of the framework when dealing with login problems. It can be seen that no matter it is simple 多地登录or complex 同端互斥登录, there sa-tokenare complete solutions

sa-tokenIt is a recently open-source domestic excellent authority authentication framework. In addition to various login authentication, it sa-tokencan also easily solve various authority authentication problems in the project,
such as: kicking people offline, automatic renewal, temporary identity switching and other common services can be called by one line of code In the next article, I will introduce these features one by one, so that everyone can have sa-tokena comprehensive understanding of

If you think the article is well written, please don’t hesitate to give it a thumbs up. Your support is my biggest motivation for updating!

Finally, attach the project link:





Guess you like

Origin blog.csdn.net/shengzhang_/article/details/112670550