Apache Shiro怎么入门

发布时间:2021-10-19 20:32:25 作者:柒染
来源:亿速云 阅读:90

今天就跟大家聊聊有关Apache Shiro怎么入门,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

项目权限 表

Shiro与Spring的整合

导入 shiro-all-1.4.1.jar 包

配置 web.xml

    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

spring配置文件 applicationContext.xml

    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"></property>

        <!-- 配置登录页面 -->
        <property name="loginUrl" value="/login.jsp"></property>

        <!-- url拦截规则 -->
        <property name="filterChainDefinitions">
            <value>
                /validatecode.jsp* = anon
                /userAction_login = anon
                /* = authc
            </value>
        </property>

    </bean>

    <!-- 配置shiro的安全管理者 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="realm"></property>
    </bean>

    <!-- extends AuthorizingRealm -->
    <bean id="realm" class="com.gwl.bos.web.realm.BosRealm"></bean>

验证 登录功能

BosRealm

package com.gwl.bos.web.realm;

import com.gwl.bos.dao.UserDao;
import com.gwl.bos.model.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class BosRealm extends AuthorizingRealm {

    /**
     * 权限 与角色相关
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Autowired
    private UserDao userDao;

    /**
     * 登录认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        User user = userDao.findByUsername(token.getUsername());

        if (user != null) {

            /**
             * Object principal  数据库查询的对象
             * Object credentials  查询出来的密码,自动验证
             * String realmName  当前类名
             */
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this
                    .getClass().getSimpleName());

            return info;
        }

        return null;
    }
}

userAction

package com.gwl.bos.web.action;

public class UserAction extends BaseAction<User> {

    public String login() {

        String username = getModel().getUsername();
        String password = getModel().getPassword();

        HttpServletRequest request = ServletActionContext.getRequest();
        String serviceCheckCode = (String) request.getSession().getAttribute("key");
        String clienCheckCode = request.getParameter("checkcode");

        if (serviceCheckCode.equalsIgnoreCase(clienCheckCode)) {

            //使用shiro验证登录
            Subject subject = SecurityUtils.getSubject();

            UsernamePasswordToken token = new UsernamePasswordToken(username, MD5Utils.text2md5(password));

            try {
                subject.login(token);

                User loginUser = (User) subject.getPrincipal();
                subject.getSession().setAttribute("loginUser", loginUser);
                return "home";
            } catch (AuthenticationException e) {
                e.printStackTrace();
                System.out.println("登录失败,用户名密码不正确");
            }
        } else {
            System.out.println("验证码不正确");
        }
        return "loginfailure";
    }
}

struts.xml 中配置全局的权限url

        <!-- 配置全局的结果视图 -->
        <global-results>
            <result name="unauthorizedUrl" type="redirect">/authorizing.jsp</result>
        </global-results>

        <!-- shiro抛出具体的异常来到的页面 -->
        <global-exception-mappings>
            <!-- 权限 -->
            <exception-mapping exception="org.apache.shiro.authz.UnauthorizedException"
                               result="unauthorizedUrl"></exception-mapping>
            <!-- 登录 -->
            <exception-mapping exception="org.apache.shiro.authz.AuthorizationException"
                               result="unauthorizedUrl"></exception-mapping>
        </global-exception-mappings>

权限控制

url拦截

spring配置文件 applicationContext.xml

        <property name="filterChainDefinitions">
            <value>
                /page_base_staff = perms["staff"]
                <!-- /page_base_staff = roles["staff"] -->
            </value>
        </property>
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //根据数据库查询的角色权限赋予不同权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("staff");
//        info.addRole("staff");
        return info;
    }

方法注解

spring配置文件 applicationContext.xml

    <!-- 开启shiro注解 -->
    <bean id="defaultAdvisorAutoProxyCreator"
          class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator">
        <property name="proxyTargetClass" value="true"></property>
    </bean>

    <!-- 切面类 -->
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"></bean>

    <!-- 解决泛型问题 -->
    <bean class="com.gwl.bos.web.action.StaffAction" scope="prototype"></bean>

 @RequiresPermissions

    @RequiresPermissions("staff")
    @Override
    public String save() {
        staffService.save(getModel());
        return SUCCESS;
    }

页面标签

在jsp页面引入shiro标签

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>

根据当前用户的权限动态展示页面元素有无

            <shiro:hasPermission name="staff">
                <a id="save" icon="icon-save" href="#" class="easyui-linkbutton" plain="true">保存</a>
            </shiro:hasPermission>

代码

    @Override
    public String save() {
        SecurityUtils.getSubject().checkPermission("staff");

        staffService.save(getModel());
        return SUCCESS;
    }

看完上述内容,你们对Apache Shiro怎么入门有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. Apache Shiro在web开发安全框架中的应用
  2. Apache Shiro 认证、授权、加密和会话管理

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

shiro apache

上一篇:Message Queue Selector如何实现顺序消费

下一篇:hashcode和hash算法的实现原理是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》