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.

Today, we’ll focus on annotated authentication in Sa-Token, which allows us to: gracefully separate authentication from business code!

GitHub open Source: github.com/dromara/sa-…

Pre-work:

1. First we introduce dependencies in POM.xml:

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

2. Register an sa-token annotation interceptor

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

3. Implement StpInterface interface to return the set of permission codes owned by each account

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

	// Return the set of permissions that an account has
	@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 set of role identifiers owned by an account
	@Override
	public List<String> getRoleList(Object loginId, String loginType) {
		return Arrays.asList("admin"."super-admin"); }}Copy the code

Create 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 successful");
		}
		return SaResult.error("Login failed");
	}
	
	/ / test cancelled - http://localhost:8081/logout
	@RequestMapping("logout")
	public SaResult logout(a) {
		StpUtil.logout();
		returnSaResult.ok(); }}Copy the code

5. Start classes

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

OK, the setup is complete, now we can start using the sa-token annotation authentication!

  • @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

Login authentication:

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

	/ / login authentication, login before they can enter - http://localhost:8081/at/checkLogin
	@SaCheckLogin
	@RequestMapping("checkLogin")
	public SaResult checkLogin(a) {
		returnSaResult.ok(); }}Copy the code

Note: The @sacheckLogin annotation can be applied to a class as if it were applied to all methods of that class

Permission authentication:

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

	/ / authority certification, have the user permissions - add can enter - http://localhost:8081/at/checkPermission
	@SaCheckPermission("user-add")
	@RequestMapping("checkPermission")
	public SaResult checkPermission(a) {
		return SaResult.ok();
	}

	/ / authority certification, at the same time have all permissions is allowed to enter, http://localhost:8081/at/checkPermissionAnd
	@SaCheckPermission({"user-add", "user-delete", "user-update"})
	@RequestMapping("checkPermissionAnd")
	public SaResult checkPermissionAnd(a) {
		return SaResult.ok();
	}

	/ / authority certification, as long as have one to get into - http://localhost:8081/at/checkPermissionOr
	@SaCheckPermission(value = {"user-add", "user-delete", "user-update"}, mode = SaMode.OR)
	@RequestMapping("checkPermissionOr")
	public SaResult checkPermissionOr(a) {
		returnSaResult.ok(); }}Copy the code

Role authentication:

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

	/ / role certification, only to have the admin role can access - http://localhost:8081/at/checkRole
	@SaCheckRole("admin")
	@RequestMapping("checkRole")
	public SaResult checkRole(a) {
		returnSaResult.ok(); }}Copy the code

Note: @ SaCheckRole like @ SaCheckPermission, can be specified and | or pattern

Level 2 Certification:

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

	/ / finish secondary certification - http://localhost:8081/at/openSafe
	@RequestMapping("openSafe")
	public SaResult openSafe(a) {
		StpUtil.openSafe(200); // Enable level 2 authentication, valid for 200 seconds
		return SaResult.ok();
	}
	
	/ / by secondary certification before can enter - http://localhost:8081/at/checkSafe
	@SaCheckSafe
	@RequestMapping("checkSafe")
	public SaResult checkSafe(a) {
		returnSaResult.ok(); }}Copy the code

Note: Level 2 authentication must be opened by stputil. openSafe(200) before it can pass the check of @sachecksafe.

HttpBasic authentication:

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

	/ / after Basic authentication is allowed to enter, http://localhost:8081/at/checkBasic
	@SaCheckBasic(account = "sa:123456")
	@RequestMapping("checkBasic")
	public SaResult checkBasic(a) {
		returnSaResult.ok(); }}Copy the code

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

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

conclusion

From the above examples, we can see that sa-Token annotation authentication is very powerful, which can simply and flexibly help us complete the authentication requirements.

The resources

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