Shiro(一)——极简配置

用了相当久之后,有点想说的话:

  如果你有现成的权限框架,继续完善它,没必要特地换成Shiro。在开始阶段,套框架会让开发非常快速,但是,在后面不断迭代过程中,框架就显得十分鸡肋。目前,模块化开发的前端框架相当多,如果想采用 “模块化开发 + 模版引擎” 的模式,需要相当的时间进行设计;如果前后端完全分离,Shiro的标签也就没用了,剩下的功能就更加鸡肋了……随着开发的时间增多,想替换掉Shiro的想法越来越强烈

 

最简单的Demo

这是我权限框架最初的样子, 门槛较高,不推荐新手使用,容易返工。一万个人真可能有一万种用法,对比过其他同事的代码,使用方式和我完全不同。

参考:https://www.sojson.com/shiro

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>ShiroDemoa</display-name>


    <!-- context -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:applicationContext-shiro.xml
        </param-value>
    </context-param>

    <!-- 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>


    <!-- mvc -->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
</web-app>

 

applicationContext-shiro.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd"
> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="successUrl" value="/member/index.htm" /> <property name="loginUrl" value="/login.htm" /> <property name="unauthorizedUrl" value="/error.htm" /> <property name="filterChainDefinitions"> <value> /login.htm=anon /submit.htm=anon /error.htm=anon /member/**=authc,roles["member"] </value> </property> </bean> <!-- 授权 认证 --> <bean id="shiroRealm" class="com.sea.shiro.ShiroRealm" /> <!-- 安全管理器 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="shiroRealm" /> </bean> <!-- Shiro生命周期处理器 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> </beans>

mvc.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" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd 
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <mvc:annotation-driven />
    <!-- 自动扫描包 -->
    <context:component-scan base-package="com.sea.spring.controller" />

    <!-- mvc返回页面的配置 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

ShiroRealm

package com.sea.shiro;

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

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
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 com.sea.spring.entity.Role;
import com.sea.spring.entity.User;

public class ShiroRealm extends AuthorizingRealm {

    /** 
     * 授权 
     */ 
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println(principals);
        User user = new User("shiro", "123456");
        Set<String> roles = new HashSet<>();
        Role role = new Role("member");
        user.setRole(role);
        roles.add(role.getName());
        return new SimpleAuthorizationInfo(roles);
    }

    /**
     *  认证信息,主要针对用户登录, 
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        User user = new User("shiro", "123456");
        if (user.getName().equals(token.getUsername())) {
            return new SimpleAuthenticationInfo(user.getName(), user.getPassword(), getName());
        }
        return null;
    }
}

Controller

 

 

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/member")
public class IndexController {
    
    @RequestMapping(value = "/index")
    public ModelAndView index() {
        ModelAndView view = new ModelAndView();
        view.setViewName("/member/index");
        return view;
    }
}

import org.apache.shiro.SecurityUtils;
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.servlet.ModelAndView;

import com.sea.spring.entity.Role;
import com.sea.spring.entity.User;

@Controller
public class LoginController {
    @RequestMapping(value = "/login")
    public ModelAndView login() {
        return new ModelAndView("/login");
    }

    @RequestMapping(value = "/submit")
    public ModelAndView submit(String username, String password) {
        User user = new User("shiro", "123456");
        user.setRole(new Role("member"));
        try {
            // 如果登陆成功
            if (user.getName().equals(username) && user.getPassword().equals(password)) {
                UsernamePasswordToken token = new UsernamePasswordToken(user.getName(), user.getPassword().toString());
                Subject subject = SecurityUtils.getSubject();
                subject.login(token);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ModelAndView("redirect:/member/index.htm");
    }
}

 

Model

public class Role {
    private String name;
}

public class User {
    private String name;
    private String password;
    private Role role;
}

JSP

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>shiro 成功界面</title>
</head>
<body>
    <h3>shiro 成功界面 角色为 member</h3>
</body>
</html>

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>shiro 登入界面</title>
</head>
<body>
    <h3>shiro 登入界面</h3>
    <form action="submit.htm" method="post">
        <table>
            <tr>
                <td>账号</td>
                <td><input type="text" name="username" /></td>
            </tr>
            <tr>
                <td>密码</td>
                <td><input type="password" name="password" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="提交" /></td>
            </tr>
        </table>
    </form>
</body>
</html>

 

posted on 2018-03-28 23:03  疯狂的妞妞  阅读(132)  评论(0编辑  收藏  举报

导航