Apache Shiro學習筆記(五)Web集成簡單配置

魯春利的工做筆記,好記性不如爛筆頭html



http://shiro.apache.org/web-features.html
前端


ShiroFilterjava

Shiro 提供了與Web集成的支持,其經過一個ShiroFilter來指定攔截的URL,而後進行相應的控制。ShiroFilter相似於如Strut2/SpringMVC這種Web框架的前端控制器,其負責讀取配置(如ini 配置文件),而後判斷URL 是否須要登陸/權限等工做。web


web.xmlapache

<?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>Invicme</display-name>
  <listener>
    <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
  </listener>
  
  <context-param>
    <param-name>shiroEnvironmentClass</param-name>
    <param-value>org.apache.shiro.web.env.IniWebEnvironment</param-value>
  </context-param>
  
  <!-- 修改默認實現及其加載的配置文件位置 -->
  <context-param>
    <param-name>shiroConfigLocations</param-name>
    <param-value>classpath:shiro/normal-shiro.ini</param-value>
  </context-param>
  
  <filter>
    <filter-name>ShiroFilter</filter-name>
    <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>ShiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
  • 一、EnvironmentLoaderListenersession

通 過EnvironmentLoaderListener 來建立相應的WebEnvironment, 並自動綁定到ServletContext,默認使用IniWebEnvironment實現。app

  • 二、shiroConfigLocations框架

默認是「/WEB-INF/shiro.ini」,IniWebEnvironment 默認是先從/WEB-INF/shiro.ini加載,經過配置指定後就加載classpath:shiro/normal-shiro.ini。jsp

wKioL1ed7VygTWJYAADm4XVitxY844.jpg


normal-shiro.iniide

[main]
#默認是/login.jsp
authc.loginUrl=/login
# unauthorizedUrl屬性指定若是受權失敗時重定向到的地址。
# roles 是org.apache.shiro.web.filter.authz.RolesAuthorizationFilter類型的實例。
roles.unauthorizedUrl=/unauthorized
# perms 是org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter類型的實例。
perms.unauthorizedUrl=/unauthorized

[users]
# 用戶名=密碼,角色
# 說明:這裏的密碼是加密以後的數據
lucl=e10adc3949ba59abbe56e057f20f883e,admin
wang=e10adc3949ba59abbe56e057f20f883e

[roles]
admin=user:*,menu:*

[urls]
/login=anon
/static/**=anon
/role=authc,roles[admin]
/permission=authc,perms["user:create"]
/unauthorized=anon
/logout=logout

說明:

    其中最重要的就是[urls]部分的配置,其格式是: 「url=攔截器[參數],攔截器[參數]」;即若是當前請求的url匹配[urls]部分的某個url模式,將會執行其配置的攔截器。
    好比anon攔截器表示匿名訪問(即不須要登陸便可訪問);

    authc攔截器表示須要身份認證經過後才能訪問;

    roles[admin]攔截器表示須要有admin 角色受權才能訪問;

    而perms["user:create"]攔截器表示須要有「user:create」權限才能訪問。


Servlet定義

  • LoginServlet

package com.invicme.apps.servlet.authc;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

/**
 * @author lucl
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public LoginServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            request.getRequestDispatcher("shiro/admin/login.jsp").forward(request, response);
            return;
        }
        
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, DigestUtils.md5Hex(password));
        String msg = "";
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            msg = "用戶名/密碼錯誤";
        } catch (IncorrectCredentialsException e) {
            msg = "用戶名/密碼錯誤";
        } catch (AuthenticationException e) {
        //其餘錯誤,好比鎖定,若是想單獨處理請單獨catch 處理
            msg = "其餘錯誤:" + e.getMessage();
        }
        if(!StringUtils.isBlank(msg)) {//出錯了,返回登陸頁面
            request.setAttribute("msg", msg);
            request.getRequestDispatcher("shiro/admin/login.jsp").forward(request, response);
        } else { // 登陸成功
            request.setAttribute("subject", subject);
            request.getRequestDispatcher("shiro/admin/success.jsp").forward(request, response);
        }
    }
    
    /**
     * 
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(DigestUtils.md5Hex("123456"));
    }
}


  • PermissionServlet

package com.invicme.apps.servlet.authc;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lucl
 */
@WebServlet("/permission")
public class PermissionServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public PermissionServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("shiro/user/perms.jsp").forward(request, response);
    }

}


  • RoleServlet

package com.invicme.apps.servlet.authc;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lucl
 */
@WebServlet("/role")
public class RoleServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public RoleServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("shiro/user/role.jsp").forward(request, response);
    }

}


  • UnauthorizedServlet

package com.invicme.apps.servlet.authc;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lucl
 */
@WebServlet("/unauthorized")
public class UnauthorizedServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public UnauthorizedServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("shiro/user/unauthorized.jsp").forward(request, response);
    }

}


Jsp

wKioL1ed8H3DtOyCAAEfIb295uI409.jpg

  • login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"   pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>登陸頁</title>
    </head>
    <body>
        <h1>This is login page.</h1><font color="red">${msg}</font>
        <form name="loginForm" action="<%=request.getContextPath()%>/login" method="POST">
            用戶名:<input type="text" name="username"    value="" />
            <br/>
            密碼:<input type="password" name="password"    value="" />
            <br/>
            <input type="submit" name="sub" value="提交" />
        </form>
    </body>
</html>


  • success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>登陸成功</title>
    </head>
    <body>
        <h1>Welcome,${subject.principal}.</h1>
    </body>
</html>


  • perms.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>權限</title>
    </head>
    <body>
        <h1>This is permission page.</h1>
    </body>
</html>


  • role.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>角色</title>
    </head>
    <body>
        <h1>This is role jsp.</h1>
    </body>
</html>


  • unauthorized.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>未受權</title>
    </head>
    <body>
        <h1>無訪問權限</h1>
    </body>
</html>
相關文章
相關標籤/搜索