search
HomeJavajavaTutorialUsing Apache Shiro for permission control in Java API development

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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools