溫馨提示×

如何配置shiro框架權限管理

小樊
82
2024-10-13 13:19:40
欄目: 編程語言

Apache Shiro是一個強大且易用的Java安全框架,用于身份驗證、授權、加密和會話管理。以下是配置Shiro框架權限管理的基本步驟:

1. 添加依賴

首先,在你的項目中添加Shiro的依賴。如果你使用的是Maven,可以在pom.xml文件中添加以下依賴:

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.7.1</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.7.1</version>
</dependency>

2. 配置Shiro

創(chuàng)建一個Shiro配置類,通常命名為ShiroConfig.java。在這個類中,你需要配置Shiro的核心組件,包括SecurityManager、RealmFilter等。

import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class ShiroConfig {

    @Bean
    public DataSource dataSource() {
        // 配置數(shù)據(jù)源
        return ...;
    }

    @Bean
    public AuthorizingRealm authorizingRealm() {
        JdbcRealm jdbcRealm = new JdbcRealm();
        jdbcRealm.setDataSource(dataSource());
        jdbcRealm.setPermissionsLookupEnabled(true);
        return jdbcRealm;
    }

    @Bean
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(authorizingRealm());
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        // 配置過濾器鏈
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/admin/**", "authc");
        filterChainDefinitionMap.put("/**", "anon");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilterFactoryBean;
    }
}

3. 定義權限和角色

在你的數(shù)據(jù)庫中定義權限和角色。例如,你可以創(chuàng)建一個roles表和一個permissions表,然后在authorizingRealm中配置這些表。

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

public class AuthorizingRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();

        // 查詢用戶權限
        Set<String> permissions = getPermissionsFromDatabase(username);

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(permissions);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();

        // 查詢用戶信息
        User user = getUserFromDatabase(username);

        if (user == null) {
            throw new UnknownAccountException("用戶不存在");
        }

        return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
    }

    private Set<String> getPermissionsFromDatabase(String username) {
        // 從數(shù)據(jù)庫中獲取用戶權限
        // 返回權限集合
    }

    private User getUserFromDatabase(String username) {
        // 從數(shù)據(jù)庫中獲取用戶信息
        // 返回用戶對象
    }
}

4. 配置Spring集成

確保你的Spring應用能夠掃描到Shiro配置類。你可以在Spring Boot應用中使用@ComponentScan注解來掃描配置類。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = "com.example")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

5. 測試權限管理

啟動你的應用,并嘗試訪問不同的URL,確保權限管理配置正確。例如,訪問/admin/**需要管理員權限,訪問/**則不需要任何權限。

通過以上步驟,你應該能夠成功配置Shiro框架的權限管理。根據(jù)你的具體需求,你可能需要進一步調(diào)整和擴展這些配置。

0