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

Using Apache Shiro for permission control in Java API development

Jun 17, 2023 pm 09:31 PM
java api shiro

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> 
Copy after login
  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;
    }
}
Copy after login

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();
    }
}
Copy after login

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!";
        }
    }
}
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles