Permission Management
Permission management is nothing more than assigning the usage permissions of a certain interface to a certain user.
Create a database
CREATE TABLE `user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL COMMENT 'name', `username` varchar(255) DEFAULT NULL, `password` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='User Test Table';
Create a project
- Create SpringBoot Project
- Editing to introduce dependencies
<dependencies> <!--SpringBoot Core--> <dependency> <groupId></groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--SpringMVC Core--> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--Mybatis core--> <!--<dependency> <groupId></groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency>--> <!--mybatis-plus core--> <dependency> <groupId></groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--lombok core--> <dependency> <groupId></groupId> <artifactId>lombok</artifactId> <version>1.16.14</version> </dependency> </dependencies>
- Write a file
server: #tomcat port port: 8080 spring: #MySQL database configuration datasource: url: jdbc:mysql://localhost:3306/springboot_demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC username: root password: 20220101 driver-class-name: mybatis-plus: configuration: log-impl: #Entity classpath typeAliasesPackage: #mapper path mapperLocations: classpath:mapper/*.xml # Global configuration id autoincrement => global-config: db-config: id-type: auto
- Create package, create class, configure mybatis-plus
@Configuration public class MybatisPlusConfig { // Latest version @Bean // <bean id=""/> public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); (new PaginationInnerInterceptor()); return interceptor; } }
- Create User Entity Class
package ; @Data @TableName("user") public class User { private Long id; private String name; private String username; private String password; }
- Create an interface and inherit the BaseMapper class of mybatis-plus
@Mapper public interface UserMapper extends BaseMapper<User> { public List<User> findAll(); }
- Created in the mapper directory
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/"> <mapper namespace=""> <select resultType=""> select * from user </select> </mapper>
- Create an interface and inherit the IService class of mybatis-plus
public interface UserService extends IService<User> { public List<User> findAll(); }
- Create a class, inherit the ServiceImpl class, and implement the UserService interface
@Service public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService { @Resource private UserMapper userMapper; @Override public List<User> findAll(){ return (); } }
- Create a class
@RestController @RequestMapping("login") public class UserController { @Autowired private UserServiceImpl service; @RequestMapping("findAll") public List<User> findAll(){ return (); } }
Implement the interceptor(Token method)
- Create an interceptor class
package ; public class LoginInterceptor implements HandlerInterceptor { private Logger log = (getClass()); @Autowired private HttpSession httpSession; //Before the Controller logic is executed @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { ("preHandle......"); String uri = (); ("uri:"+ uri); if (!(handler instance of HandlerMethod)) { return true; } String token=("qcby-token"); if (!(token)) { // Not logged in and jump to the login interface ("/login/login"); return false; }else { return true; } } //The Controller logic has been executed but the view parser has not yet parsed it @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { ("postHandle......"); } //Controller logic and view parser have been executed @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { ("afterCompletion..."); } }
- Create WebMvcConfig class and set the intercept path
package ; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { (loginInterceptor()) //Intercepted paths (*all) .addPathPatterns("/**") // Those paths are not intercepted .excludePathPatterns("/login/login","/error"); } @Bean public LoginInterceptor loginInterceptor(){ return new LoginInterceptor(); } }
- Create a class
package ; public class TokenUtil { private static Map<String, User> tokenMap=new HashMap<>(); public static String generateToken(User user){ String token= ().toString(); (token,user); return token; } public static boolean verify(String token){ return (token); } public static User getUser(String token){ return (token); } }
- Write a login method
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; @RestController @RequestMapping("login") public class UserController { @Autowired private UserServiceImpl service; @Autowired private HttpSession session; @RequestMapping(value = "login",method = ) public Map<String,Object> login(User user){ Map<String,Object> map = new HashMap<>(); ("code",0); if((()) || (()) ){ ("msg","User or password is empty!"); return map; } QueryWrapper<User> queryWrapper = new QueryWrapper<>(); ("username",()) .eq("password",()); User userDb = (queryWrapper); if(userDb != null){ ("code",1); ("data",userDb); String token= (userDb); ("qcby-token",token); }else{ ("msg","Under username or password!"); } return map; } @GetMapping("findAll") public List<User> findAll(){ return (); } }
【Notice】 After successful login, all method interfaces can be called and permission restrictions cannot be implemented.
Permission allocation(Method 1)
- The database creates menu, ref_menu_user table:Because all interface method paths are stored in the database
CREATE TABLE `menu` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, `url` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; CREATE TABLE `ref_menu_user` ( `user_id` bigint(20) NOT NULL, `menu_id` bigint(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
- Create Menu Entity Class
package ; @Data public class Menu { private Integer id; private String name; private String url; }
- Create MenuMapper interface
package ; public interface MenuMapper { //Get the interface method path that the user can use based on the id public Set<String> getUrlListById(@Param("id") Long id); }
- Created in the mapper directory
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/"> <mapper namespace=""> <select resultType=""> select url from menu left join ref_menu_user on =ref_menu_user.menu_id where ref_menu_user.user_id=#{id} </select> </mapper>
- Create MenuService interface
public interface MenuService { public Set<String> getUrlListById(Long id); }
- Create MenuServiceImpl class
@Service public class MenuServiceImpl implements MenuService { @Resource private MenuMapper menuMapper; public Set<String> getUrlListById(Long id){ return (id); } }
- Edit User Entity Class
@Data @TableName("user") public class User { private Long id; private String name; private String username; private String password; @TableField(exist = false)//Ignored when querying database private Set<String> url;//Deduplication storage }
- Edit UserController, write getUrlListById method,The method path to obtain authorization is stored in the url property of the User entity class
@RestController @RequestMapping("login") public class UserController { @Autowired private UserServiceImpl service; @Autowired private HttpSession session; @Autowired private MenuServiceImpl menuService; @RequestMapping(value = "login",method = ) public Map<String,Object> login(User user){ Map<String,Object> map = new HashMap<>(); ("code",0); if((()) || (()) ){ ("msg","User or password is empty!"); return map; } QueryWrapper<User> queryWrapper = new QueryWrapper<>(); ("username",()) .eq("password",()); User userDb = (queryWrapper); if(userDb != null){ ("code",1); ("data",userDb); String token= (userDb); ("qcby-token",token); /* *The key point is to save the method path queryed from the database into the URL of the entity class */ Set<String> url=(()); (url); }else{ ("msg","Under username or password!"); } return map; } @RequestMapping("getUrlListById") public Set<String> getUrlListById(Long id){ return (id); } @GetMapping("findAll") public IPage<User> findAll(Page<User> page){ return (page); } }
- Edit the interceptor class(Determine whether the user accessed path is authorized to this user)
package ; public class LoginInterceptor implements HandlerInterceptor { private Logger log = (getClass()); @Autowired private HttpSession httpSession; //Before the Controller logic is executed @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { ("preHandle......"); String uri = (); ("uri:"+ uri); if (!(handler instance of HandlerMethod)) { return true; } String token=("qcby-token"); if (!(token)) { // Not logged in and jump to the login interface ("/login/login"); return false; }else { //Login successfully //Verify identity User user=(token); //Get the url attribute of the entity class, the authorized method path Set<String> url=(); // Check whether the method called by the user is in the url collection if(!(uri)) throw new Exception("Insufficient permission"); return true; } } //The Controller logic has been executed but the view parser has not yet parsed it @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { ("postHandle......"); } //Controller logic and view parser have been executed @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { ("afterCompletion..."); } }
【Notice】 Finally, you need to configure the xxxapplication class
package ; import ; import ; import ; @MapperScan("") @SpringBootApplication public class Demo0325Application { public static void main(String[] args) { (, args); } }
Source code
The source code is the demo0326 file in this repositoryIncludes data tables and source code; it can be run by changing the configuration appropriately.