学习shiro框架

来源:互联网 发布:马里亚纳网络性奴 编辑:程序博客网 时间:2024/06/07 12:58

前言:shiro是权限控制常用框架,安全,易上手,是项目中常用权限控制框架,最近学习了一下,做了如下总结

Shrio单词

Incorrect 错误的
Credentials 证书,凭证
Principal 主要的,当事人
security 安全
Authenticator 认证者
Authentication 证明
Strategy 战略、策略
permission 允许、许可
role 角色、任务
subject 主题、科目
realm 领域、范围
permitted 被允许的
anonymous 匿名的

权限的组成部分

subject 登录的用户
role 角色(权限的集合 管理员(添加、删除、修改))
permission 权限(添加、修改、删除、查询、打印、发送…)
resource 资源(URL、按钮…)

粒度

Shiro在web环境下使用

  1. 添加Maven依赖
  2. 添加过滤器
<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>
  1. 创建spring的配置文件,并添加一个bean,bean的id需要filter的name值相同
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"></bean>
  1. 创建自己的Realm,用来指定认证和权限列表
  2. 接受账号和密码,进行登录

被认证 被记住
UI URL

Shiro第一个例子

写配置文件shiro.ini

[users]tom=123123jack=000000

测试代码为:

@Test    public void hello() {        //1. 读取classpath中的shiro.ini配置文件,并创建securityManagerFactory对象        Factory<SecurityManager> securityManagerFactory = new IniSecurityManagerFactory("classpath:shiro.ini");        //2. 获取SecurityManager        SecurityManager securityManager = securityManagerFactory.getInstance();        //3.设置SecurityManager(仅设置一次)        SecurityUtils.setSecurityManager(securityManager);        //4.获取当前登录的对象        Subject subject = SecurityUtils.getSubject();        //5.根据账号和密码进行登录        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("tom","123123");        //6.登录        try {            subject.login(usernamePasswordToken);        } catch (UnknownAccountException ex) {            ex.printStackTrace();            System.out.println("无此账号");        } catch (LockedAccountException ex) {            ex.printStackTrace();            System.out.println("账号被锁定");        } catch (IncorrectCredentialsException ex) {            ex.printStackTrace();            System.out.println("密码错误");        } catch (AuthenticationException ex) {            ex.printStackTrace();            System.out.println("账号或密码错误");        }        //7.安全退出        subject.logout();    }

Shiro在web环境下使用

  1. 添加Maven依赖
        <dependency>            <groupId>org.apache.shiro</groupId>            <artifactId>shiro-all</artifactId>            <version>1.2.4</version>        </dependency>        <dependency>            <groupId>commons-logging</groupId>            <artifactId>commons-logging</artifactId>            <version>1.2</version>        </dependency>

2.在web.xml中添加过滤器

<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.创建spring配置文件

<?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.xsd">    <bean id="myRealm" class="com.kaishengit.shiro.MyRealm">        <property name="userService" ref="userService"/>    </bean>    <!--securityManager-->    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">        <property name="realm" ref="myRealm"/>        <property name="cacheManager" ref="cacheManager"/>    </bean>    <!--cacheManager-->    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"/>    <!--lifeCicle-->    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>    <!--form认证过滤器-->    <bean id="formAuthenticationFilter" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">        <!--表单中账号的name属性值-->        <property name="usernameParam" value="tel"/>        <!--表单中密码-->        <property name="passwordParam" value="password"/>        <property name="loginUrl" value="/tourism/"/>        <property name="successUrl" value="/tourism/home"/>    </bean>    <bean id="shiro" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">        <!--登录地址-->        <property name="loginUrl" value="/tourism/"/>        <!--登录成功地址-->        <property name="successUrl" value="/tourism/home"/>        <!--无权限地址-->        <property name="unauthorizedUrl" value="/static/html/403.html"/>        <property name="securityManager" ref="securityManager"/>        <!--添加表单验证器-->        <property name="filters">            <map>                <entry key="authc" value-ref="formAuthenticationFilter"/>            </map>        </property>        <!--定义过滤规则-->        <property name="filterChainDefinitions">            <value>                /static/** = anon                /** = authc            </value>        </property>    </bean></beans>
  1. 创建自己的Realm,用来指定认证和权限列表
import com.kaishengit.pojo.User;import com.kaishengit.service.UserService;import org.apache.shiro.authc.*;import org.apache.shiro.authz.AuthorizationInfo;import org.apache.shiro.realm.AuthorizingRealm;import org.apache.shiro.subject.PrincipalCollection;public class MyRealm extends AuthorizingRealm {    private UserService userService;    public void setUserService(UserService userService) {        this.userService = userService;    }    /**     * 权限认证     * @param principalCollection     * @return     */    @Override    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {        return null;    }    /**     * 登录认证     * @param authenticationToken     * @return     * @throws AuthenticationException     */    @Override    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;        String tel = token.getUsername();        User user = userService.findByTel(tel);        if(user == null) {            throw new UnknownAccountException("该账户不存在");        } else if(User.STATE_DISABLE.equals(user.getState())) {            throw new LockedAccountException("该帐号已被禁用");        }        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());    }}
  1. 控制器中接受账号和密码,进行登录
@PostMapping("/")    public String login(String tel,String password,RedirectAttributes redirectAttributes) {        Subject subject = SecurityUtils.getSubject();        UsernamePasswordToken token = new UsernamePasswordToken(tel,password);        String errorMessage = "";        try {            subject.login(token);        }catch (UnknownAccountException e) {            errorMessage = "账号或密码错误";        }catch (LockedAccountException e) {            errorMessage = "账号被锁定";        }catch (AuthenticationException e) {            errorMessage = "认证异常";        }        if(!"".equals(errorMessage)){            redirectAttributes.addFlashAttribute("message",errorMessage);            return "redirect:/tourism/";        }        return "redirect:/tourism/home";    }

权限控制

权限控制分为UI和URL级别

UI级别

使用标签库

<shiro:hasRole name="综合办公">    <h3>综合办公</h3></shiro:hasRole>

URL级别

<!--定义过滤规则--><property name="filterChainDefinitions">    <value>        /static/** = anon        /tourism/user/** = roles[系统管理]        /tourism/ticket/** = roles[基本信息]        /tourism/place/** = roles[基本信息]        /** = user    </value></property>
原创粉丝点击