springboot中使用shiro

導入pom依賴

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

添加shiro配置

@Configuration
public class ShiroConfig {
    
    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 必須設置 SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 設置登錄頁面
        shiroFilterFactoryBean.setLoginUrl("/notLogin");
        // 設置沒權限頁面
        shiroFilterFactoryBean.setUnauthorizedUrl("/notRole");

        // 設置攔截器
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        //遊客,開發權限
        filterChainDefinitionMap.put("/guest/**", "anon");
        //用戶,需要角色權限 “user”
        filterChainDefinitionMap.put("/user/**", "roles[user]");
        //管理員,需要角色權限 “admin”
        filterChainDefinitionMap.put("/admin/**", "roles[admin]");
        //開放登陸接口
        filterChainDefinitionMap.put("/login", "anon");
        //其餘接口一律攔截
        //主要這行代碼必須放在所有權限設置的最後,不然會導致所有 url 都被攔截
        filterChainDefinitionMap.put("/**", "authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        System.out.println("Shiro攔截器工廠類注入成功");
        return shiroFilterFactoryBean;
    }

    /**
     * 注入 securityManager
     */
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 引用自定義 Realm
        securityManager.setRealm(simpleAuthRealm());
        return securityManager;
    }

    /**
     * 自定義身份認證 Realm
     */
    @Bean
    public SimpleAuthRealm simpleAuthRealm() {
        return new SimpleAuthRealm();
    }
}

自定義 Realm 認證

public class SimpleAuthRealm extends AuthorizingRealm {
    
    @Autowired
    private UserMapper userMapper;
    
    /**
     * 驗證用戶信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("————身份認證方法————");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String password = userMapper.getPassword(token.getUsername());
        
        if (null == password) {
            throw new AccountException("用戶名不正確");
        } else if (!password.equals(new String((char[]) token.getCredentials()))) {
            throw new AccountException("密碼不正確");
        }
        
        return new SimpleAuthenticationInfo(token.getPrincipal(), password, getName());
    }

    /**
     * 初始化當前用戶的 Role
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        String role = userMapper.getRole(username);
        Set<String> set = new HashSet<>();
        set.add(role);
        info.setRoles(set);
        return info;
    }
}

realm中獲取session

SecurityUtils.getSubject().getSession();

---
    
SecurityUtils.getSubject().logout();

shiro 配置加密方式

{
    HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
    matcher.setHashAlgorithmName("MD5");
    matcher.setHashIterations(1314);
    setCredentialsMatcher(matcher);
}

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.debug("開始執行身份認證");
    UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        
    User user = userMapper.selectOne(queryWrapper);
    if (null == user) {
        throw new AccountException("用戶名不正確");
    } else if (!UserStatuEnum.OK.getCode().equals(user.getStatu())){
        throw new AccountException("用戶被狀態波動");
    }
		
	ByteSource credentialsSalt = ByteSource.Util.bytes(String.valueOf(user.getId()));
    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
    	user.getName(),
        user.getPassword(),
        credentialsSalt,
        getName()
	);
    return authenticationInfo;
}

shiro 生成鹽值密碼

String hashAlgorithmName = "MD5";
Object crdentials = "123456";
Object salt = String.valueOf(1);
int hashIterations = 1314;
Object result = new SimpleHash(hashAlgorithmName,crdentials,salt,hashIterations);
System.out.println(">>"+crdentials+">>"+hashAlgorithmName+">>"+salt+">"+hashIterations+">" + result + ":" + salt);
發佈了52 篇原創文章 · 獲贊 41 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章