Preface:

In JavaWeb projects, authentication and authorization is an essential function. The more traditional frameworks are Shiro, SpringSecurity and so on. These frameworks are not very easy to use now that the “front and back end separation” has become the mainstream, and need to write a lot of compatibility code to integrate. The framework recommended to you today is Sa-Token, which allows us to integrate the authentication function very elegantly! GitHub open Source: github.com/dromara/sa-…

Sa – Token is introduced

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.

Sa-token’s API design is very simple. How simple is it? Using login authentication as an example, you just need to:

// Write the account ID of the current session at login
StpUtil.login(10001);

// 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

So far, we have completed login authentication with sa-token!

Your little head might be full of question marks. Is that it? What about custom Realms? What about global filters? Don’t I have to write various configuration files?

Yes, in SA-Token, login authentication is as simple as that. There is no need to do any complicated upfront work, just one line of API calls, you can complete session login authentication!

When you’ve had enough of SpringSecurity, Shiro, etc., you’ll see how simple and elegant sa-token’s API design is compared to these traditional frameworks.

Permission authentication example (only sessions with user:add permission can enter requests)

@SaCheckPermission("user:add")
@RequestMapping("/user/insert")
public String insert(SysUser user) {
	// ...
	return "User increase";
}
Copy the code

Kick an account offline (NotLoginException will be thrown when the user accesses the system again)

// Force the session with account 10001 to log out
StpUtil.logoutByLoginId(10001);
Copy the code

In SA-Token, most functions can be done in one line of code:

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.logoutByLoginId(10001);   // Log out of the session with account 10001
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.logoutByLoginId(10001."PC");   // Specify device id to forcibly log out (different ends 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

Without running the tests, I’m sure you’ll get a sense of how most of the APIS are used.

List of sa-Token functions

  • Login authentication: Single-end login, multi-end login, mutually exclusive login at the same end, and no login within seven days
  • Permission authentication: Permission authentication, role authentication, and session level 2 authentication
  • Session Session: All-end shared Session, single-end exclusive Session, and custom Session
  • Kick people offline – Kick people offline according to the account ID and Token value
  • Account closure – specify the days of closure, permanent closure, set unclosure time
  • 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
  • Micro service network authentication — route interception authentication for Gateway, ShenYu, Zuul and other common gateways
  • Single sign-on – There are three built-in single sign-on modes: cross-domain and shared Redis
  • OAuth2.0 authentication – Based on RFC-6749 standard, OAuth2.0 standard process authorization authentication, support openID mode
  • Level 2 authentication: Re-authentication is performed on the basis of login to ensure security
  • Separate Redis – Separate permission cache from business cache
  • Temporary Token authentication – Resolves Token authorization issues for a short period of time
  • Simulate other’s account – Real-time operation of any user status data
  • Temporary Identity Switch – Temporarily switch the session identity to another account
  • Front and background separation – Apps, applets and other terminals that do not support cookies
  • 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, as well as custom token generation policies and custom token prefixes
  • 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
  • Global listener – Some AOP operations when the user logs in, logs out, gets kicked off, and so on
  • Out of the box – Provides SpringMVC, WebFlux and other common Web framework starter integration packages, truly out of the box

Single sign-on & OAuth2.0

Through sa-token, we can easily set up a single sign-on authentication center:

/** * Sa-token-SSO Server Controller */
@RestController
public class SsoServerController {
    // SSO-server: processes all SSO-related requests
    @RequestMapping("/sso/*")
    public Object ssoRequest(a) {
        returnSaSsoHandle.serverRequest(); }}Copy the code

Similarly, we can also easily set up an OAuth2.0 authentication center:

/** * sa-token-oauth2.0 Server Controller */
@RestController
public class SaOAuth2ServerController {
    // SSO-server: processes all SSO-related requests
    @RequestMapping("/oauth2/*")
    public Object request(a) {
        returnSaSsoHandle.serverRequest(); }}Copy the code

For detailed code, please refer to the official website of the framework.

conclusion

As can be seen from the above examples, SA-Token is an excellent framework worthy of getting started, considering both simplicity and comprehensiveness.

At the same time, its official website is also very detailed documentation, not only introduces the SA-Token framework, but also introduces a lot of permission design ideas, which is really teaching people to fish.

The resources

  • Open source: github.com/dromara/sa-…
  • Official document: sa-token.dev33.cn/