shiro 基础

本文详细介绍如何使用Apache Shiro进行权限管理,包括引入依赖、配置文件、自定义Realm及登录控制器等内容。通过具体步骤展示如何实现用户认证与授权。

1、引入jar包

<!-- apache.shiro -->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-ehcache</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-web</artifactId>
    <version>1.3.2</version>
</dependency>

2、配置web.xml

<!-- apache shiro -->
<filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
        <param-name>targetFilterLifecycle</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

3、配置shiro.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <!-- 安全管理器
        1、缓存技术:缓存管理
        2、realm:负责获取处理数据
    -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="cacheManager" ref="cacheManager"/>
        <!-- Realm 实现类-->
        <property name="realm" ref="jdbcRealm"/>
    </bean>

    <!-- 自定义shiro-->
    <bean id="jdbcRealm" class="com.shiro.bean.ShiroRealm">
        <!-- 加密 -->
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <!-- 设置加密算法类型 -->
                <property name="hashAlgorithmName" value="MD5"/>
                <!-- 加密次数 -->
                <property name="hashIterations" value="21" />
                <!-- true: hex编码, false: base64编码 -->
                <property name="storedCredentialsHexEncoded" value="false"/>
            </bean>
        </property>
    </bean>

    <!-- 使用的缓存技术 -->
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <!-- 不配置则创建默认实例 -->
        <!-- <property name="cacheManager" ref="ehCacheManager"/> -->
        <!-- 不配置则使用默认配置 -->
        <!-- <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>-->
    </bean>


    <!-- 必须有这样的实例,管理Spring容器中常用的对象 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

    <!-- 启用shiro 注解 -->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
          depends-on="lifecycleBeanPostProcessor"/>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>

    <!-- 网络方面 -->
    <bean id="secureRemoteInvocationExecutor" class="org.apache.shiro.spring.remoting.SecureRemoteInvocationExecutor">
        <property name="securityManager" ref="securityManager"/>
    </bean>

    <!--
        核心配置 ShiroFilter
        1、shiroFilter这个bean的id必须web.xml文件中的filter-name一致
    -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="/s/login"/>
        <property name="successUrl" value="/"/>
        <property name="unauthorizedUrl" value="/s/unauthorized"/>
        
        <property name="filterChainDefinitions">
            <value>
                /s/login = anon
                /s/logout = logout

                /admin = roles[admin]
                /user = roles[user]
                /** = authc
            </value>
        </property>
    </bean>
</beans>

4、自定义shiroRealm实现类

package com.shiro.bean;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashSet;

/**
 * @author: gpj
 * @Description: 查询数据库 并得到正确的数据
 * @Date: Created in 15:36 2017/10/21
 * @Modified By:
 */
public class ShiroRealm extends AuthorizingRealm {

    /**
     * 用户登录
     * @param token 我们认证token,用于获取用户名
     * @return 使用SimpleAuthenticationInfo实现类,封装查询到的用户名与密码
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1、封装查询到的用户名与密码
        SimpleAuthenticationInfo info = null;
        //2、获取用户名
        String username = token.getPrincipal().toString();
        //3、查询数据库,是否存在指定用户名和密码的用户
        // 模拟查询
        String ADMIN = "admin";
        if (ADMIN.equals(username)) {
            // 盐值加密
            ByteSource salt = ByteSource.Util.bytes(username);
            // 模拟加密之后的密码,实际从数据库中读取
            Md5Hash md5Password = new Md5Hash("123456", salt, 21);
            info = new SimpleAuthenticationInfo(username, md5Password, salt, this.getName());
        } else {
            throw new AuthenticationException();
        }
        //4、如果查询到了,封装查询结果,返回给我们调用
        //5、如果没有查询到,返回一个异常
        return info;
    }

    /**
     * 用户授权
     * @param principalCollection 登录的身份,用户名
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1、封装获得的用户对应的角色,SimpleAuthorizationInfo(Set<String>)
        SimpleAuthorizationInfo info = null;
        //2、获取用户名
        String username = principalCollection.toString();
        //3、查询用户名所对应的角色
        // 模拟
        // 角色集合
        HashSet<String> roles = new HashSet<String>();
        if ("admin".equals(username)) {
            roles.add("admin");
        } else {
            roles.add("user");
        }

        info = new SimpleAuthorizationInfo(roles);
        return info;
    }
}

5、登录控制器

package com.ives.core.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author: gpj
 * @Description: 登录控制器
 * @Date: Created in 15:48 2017/10/21
 * @Modified By:
 */
@Controller
@RequestMapping("/s")
public class LoginController {

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String loginSubmit(String username, String password) {
        // 1、创建subject对象
        Subject subject = SecurityUtils.getSubject();

        // 2、判断当前用户是否登录
        if (!subject.isAuthenticated()) {
            //3、将用户名密码封装
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                subject.login(token);
            } catch (AuthenticationException e) {
                return "redirect:/s/login";
            }
        }


        return "redirect:/";
    }

    @RequestMapping(value = "/unauthorized", method = RequestMethod.GET)
    @ResponseBody
    public String unauthorized() {
        return "this is a unauthorized page";
    }
}

 

转载于:https://my.oschina.net/iamgpj/blog/1554414

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值