SA token annotation authentication: elegant separation of authentication and business code!

Keywords: Java Spring Boot token

SA token introduction:

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, OAuth2.0, micro service gateway authentication and so on.

Today, we mainly introduce annotation authentication in SA token, which allows us to elegantly separate authentication from business code!

GitHub open source address: https://github.com/dromara/sa-token

Front work:

1. First, we introduce dependencies in pom.xml:

<!-- Sa-Token Authority authentication -->
<dependency>
	<groupId>cn.dev33</groupId>
	<artifactId>sa-token-spring-boot-starter</artifactId>
	<version>1.26.0</version>
</dependency>

2. Register annotation interceptor for SA token

/**
 * Sa-Token Configuration class 
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/**").excludePathPatterns("");
	}
}

3. Implement the StpInterface interface and return the permission code set owned by each account

/**
 * Custom permission verification interface extension 
 */
@Component
public class StpInterfaceImpl implements StpInterface {

	// Returns the set of permission codes owned by an account 
	@Override
	public List<String> getPermissionList(Object loginId, String loginType) {
		return Arrays.asList("101", "user-add", "user-delete", "user-update", "user-get", "article-get");
	}

	// Returns the role ID set owned by an account 
	@Override
	public List<String> getRoleList(Object loginId, String loginType) {
		return Arrays.asList("admin", "super-admin");
	}

}

4. Then create the login interface:

/**
 * Login test 
 */
@RestController
public class LoginController {

	// Test login---- http://localhost:8081/doLogin?name=zhang&pwd=123456
	@RequestMapping("doLogin")
	public SaResult doLogin(String name, String pwd) {
		// This is only a simulation example. Real projects need to query data from the database for comparison 
		if("zhang".equals(name) && "123456".equals(pwd)) {
			StpUtil.login(10001);
			return SaResult.ok("Login succeeded");
		}
		return SaResult.error("Login failed");
	}
	
	// Test logout---- http://localhost:8081/logout
	@RequestMapping("logout")
	public SaResult logout() {
		StpUtil.logout();
		return SaResult.ok();
	}
	
}

5. Startup class

@SpringBootApplication
public class SaTokenDemoApplication {
	public static void main(String[] args) {
		SpringApplication.run(SaTokenDemoApplication.class, args);
	}
}

OK, the pre work is completed. Now we can start using SA token annotation authentication!

  • @SaCheckLogin: login authentication - this method can only be entered after login
  • @SaCheckRole("admin"): role authentication - you must have the specified role ID to enter this method
  • @SaCheckPermission("user:add"): permission authentication - you must have the specified permission to enter this method
  • @SaCheckSafe: Level 2 authentication verification - this method can only be accessed after level 2 authentication
  • @SaCheckBasic: HttpBasic authentication - you can enter this method only after passing Basic authentication

Login authentication:

/**
 * Annotation authentication test 
 */
@RestController
@RequestMapping("/at/")
public class AtController {

	// Login authentication. You can enter the method only after logging in---- http://localhost:8081/at/checkLogin 
	@SaCheckLogin
	@RequestMapping("checkLogin")
	public SaResult checkLogin() {
		return SaResult.ok();
	}
	
}

Note: @ SaCheckLogin annotation can be added to the class, and the effect is the same as that marked on all methods of this class

Authority authentication:

@RestController
@RequestMapping("/at/")
public class AtController {

	// Permission authentication. You can enter the method only with user add permission---- http://localhost:8081/at/checkPermission 
	@SaCheckPermission("user-add")
	@RequestMapping("checkPermission")
	public SaResult checkPermission() {
		return SaResult.ok();
	}

	// Permission authentication. You can enter only if you have all permissions at the same time---- http://localhost:8081/at/checkPermissionAnd 
	@SaCheckPermission({"user-add", "user-delete", "user-update"})
	@RequestMapping("checkPermissionAnd")
	public SaResult checkPermissionAnd() {
		return SaResult.ok();
	}

	// Authority authentication, as long as you have one of them, you can enter---- http://localhost:8081/at/checkPermissionOr 
	@SaCheckPermission(value = {"user-add", "user-delete", "user-update"}, mode = SaMode.OR)
	@RequestMapping("checkPermissionOr")
	public SaResult checkPermissionOr() {
		return SaResult.ok();
	}

}

Role authentication:

@RestController
@RequestMapping("/at/")
public class AtController {

	// Role authentication. You can only enter the admin role---- http://localhost:8081/at/checkRole 
	@SaCheckRole("admin")
	@RequestMapping("checkRole")
	public SaResult checkRole() {
		return SaResult.ok();
	}

}

Note: @ SaCheckRole is similar to @ SaCheckPermission, and | or mode can be specified

Secondary certification:

@RestController
@RequestMapping("/at/")
public class AtController {

	// Complete level II certification---- http://localhost:8081/at/openSafe 
	@RequestMapping("openSafe")
	public SaResult openSafe() {
		StpUtil.openSafe(200); // Open level 2 certification, valid for 200 seconds
		return SaResult.ok();
	}
	
	// You can only enter after passing the secondary certification---- http://localhost:8081/at/checkSafe 
	@SaCheckSafe
	@RequestMapping("checkSafe")
	public SaResult checkSafe() {
		return SaResult.ok();
	}

}

Note: you can pass @ SaCheckSafe's inspection only after StpUtil.openSafe(200) opens the secondary certification.

HttpBasic certification:

@RestController
@RequestMapping("/at/")
public class AtController {

	// You can enter only after passing Basic authentication---- http://localhost:8081/at/checkBasic 
	@SaCheckBasic(account = "sa:123456")
	@RequestMapping("checkBasic")
	public SaResult checkBasic() {
		return SaResult.ok();
	}
	
}

When we access this interface, the browser will force a form to pop up:

After we enter the account password (sa / 123456), we can continue to access the data:

summary

From the above examples, we can see that the annotation authentication of SA token is still very powerful and can help us complete the authentication requirements simply and flexibly.

reference material

Posted by johnnyblaze1980 on Sun, 12 Sep 2021 20:41:41 -0700