Home >Java >javaTutorial >Using Apache Shiro for permission control in Java API development

Using Apache Shiro for permission control in Java API development

WBOY
WBOYOriginal
2023-06-17 21:31:40972browse

Using Apache Shiro for permission control in Java API development

With the development of Internet technology, more and more applications adopt API-based architecture. For this architecture, data or services are exposed to external systems or applications in the form of APIs. In this case, user permission control is very important. This article mainly introduces how to use Apache Shiro to manage permission issues in Java API.

Overview of Apache Shiro

Apache Shiro is an open source framework from the Apache Software Foundation that provides basic functions such as security authentication, authorization, password management, and session management in applications. Apache Shiro is a simple, easy-to-use security framework that allows Java developers to focus on business logic without worrying about security issues.

The main components of Apache Shiro include:

  1. Subject: represents a user interacting with our application, which can be a person, program, service, etc. Each Subject has a set of security-related "principals" that can be used to represent the user's identity.
  2. SecurityManager: Used to manage the security operations of applications. Its main responsibilities are authentication, authorization, encryption, etc.
  3. Realm: used to obtain application data, such as users, roles, permissions, etc. Data may be stored in databases, files, etc.
  4. SessionManager: Manage session information for each user, including creation, invalidation, maintenance, etc.
  5. Session: Maintain session information for each user, including user login status, etc.
  6. Cryptography: Provides security services such as encryption and hashing algorithms.

Based on the above components, Shiro provides a complete security framework that can be used to develop security modules in Java applications.

Use Apache Shiro for permission control

In the process of developing Java API, it is often necessary to control user permissions. Shiro provides a flexible and streamlined solution to achieve this function. The specific implementation method is introduced below:

  1. Introducing Shiro dependency packages

First, you need to add Shiro’s relevant dependency packages to the project. For example, in a Maven project, you can add the following code in pom.xml:

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.5.3</version>
</dependency> 
  1. Define Realm class

In Shiro, Realm is responsible for defining users, roles and Permissions and other related data, and integrate it with the Shiro framework. Therefore, defining the Realm class is the first step for permission control.

We can customize a Realm class to achieve the function of obtaining user-related information from the database, as shown below:

public class MyRealm extends AuthorizingRealm {
    
    // 根据用户名获取用户即其角色、权限等相关信息
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取当前用户的身份信息
        String username = (String) principalCollection.getPrimaryPrincipal();
        
        // 从数据库中查询用户及其角色
        User user = userService.loadByUsername(username);
        List<Role> roles = roleService.getRolesByUsername(username);
        
        // 添加角色
        List<String> roleNames = new ArrayList<>();
        for (Role role : roles) {
            roleNames.add(role.getName());
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roleNames);
        
        // 添加权限
        List<String> permissionNames = new ArrayList<>();
        for (Role role : roles) {
            List<Permission> permissions = permissionService.getPermissionsByRoleId(role.getId());
            for (Permission permission : permissions) {
                permissionNames.add(permission.getName());
            }
        }
        info.addStringPermissions(permissionNames);
        
        return info;
    }
    
    // 根据用户名和密码验证用户
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取用户提交的身份信息
        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
        
        // 根据用户名查询用户
        User user = userService.loadByUsername(username);
        if (user == null) {
            throw new UnknownAccountException();
        }
        
        // 验证用户密码
        String encodedPassword = hashService.hash(password, user.getSalt());
        if (!user.getPassword().equals(encodedPassword)) {
            throw new IncorrectCredentialsException();
        }
        
        // 如果验证成功,则返回一个身份信息
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password, getName());
        return info;
    }
}

In the above code, we implement the AuthorizingRealm abstract class provided by The doGetAuthorizationInfo method and the doGetAuthenticationInfo method are used to obtain the user's role and permission information, and to verify the user's identity. These methods will call UserService, RoleService, PermissionService and other service layers to query relevant information in the database in order to obtain user data.

  1. Configuring Shiro Filter

In the Java API, we can configure Shiro Filter to intercept requests and control user permissions. Shiro Filter is a Servlet filter that can be used for permission filtering, session management, etc. in web applications.

When configuring Shiro Filter, we need to configure Shiro's security manager, customized Realm class, written login page, etc. An example is as follows:

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);

        // 设置登录URL
        shiroFilter.setLoginUrl("/login");
        // 设置无权访问的URL
        shiroFilter.setUnauthorizedUrl("/unauthorized");
        
        // 配置拦截器规则
        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/logout", "logout");
        filterChainDefinitionMap.put("/home", "authc");
        filterChainDefinitionMap.put("/admin/**", "roles[admin]");
        filterChainDefinitionMap.put("/**", "authc");
        shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilter;
    }

    @Bean
    public SecurityManager securityManager(MyRealm myRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm);

        return securityManager;
    }
    
    @Bean
    public MyRealm myRealm(HashService hashService,
                           UserService userService,
                           RoleService roleService,
                           PermissionService permissionService) {
        return new MyRealm(userService, roleService, permissionService, hashService);
    }
    
    @Bean
    public HashService hashService() {
        return new SimpleHashService();
    }
}

In the above code, we use the @Configuration annotation to define a ShiroConfig class for configuring Shiro-related parameters. In this class, we define the shirFilter() method, securityManager() method, and myRealm() method for configuring Shiro filters, security managers, and custom Realm classes. In the corresponding method, we can use dependencies such as UserService, RoleService, PermissionService, HashService, etc. to inject related services through dependency injection to achieve permission control and user verification.

  1. Use Shiro in Java API for permission control

After completing the above steps, we can use Shiro in Java API for permission control. In specific implementation, we can use the Subject class provided by Shiro to represent the current user. We can check whether the user has a certain role or permission through the hasRole(), isPermitted() and other methods of this class. The following is an example:

@Controller
public class ApiController {

    @RequestMapping("/api/test")
    @ResponseBody
    public String test() {
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.hasRole("admin")) {
            return "Hello, admin!";
        } else if (currentUser.isAuthenticated()) {
            return "Hello, user!";
        } else {
            return "Please login first!";
        }
    }
}

In the above code, we define an ApiController class and define a test() method in it. In this method, we first obtain the current user Subject object, and then make permission judgments by calling hasRole(), isPermitted() and other methods.

Summary

In Java API development, permission control is a very important issue. Apache Shiro provides a convenient and easy-to-use security framework that can help Java developers quickly implement user authentication, authorization, password management, session management and other functions. Through the introduction of this article, I hope readers can clearly understand how to use Shiro to implement permission control functions in Java API development.

The above is the detailed content of Using Apache Shiro for permission control in Java API development. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn