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>
相关文章
相关标签/搜索