Spring Security

Spirng Security主要涵盖的方面有

1. 登录验证管理,包括登录成功后保存用户信息到Session

2. URL级别和Controller方法级别的访问控制

3. 对于访问控制采取的授权管理方法,包括用户授权和用户组授权

下面是例子

security-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
             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
             http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd"
             xmlns:beans="http://www.springframework.org/schema/beans">
    <!-- auto-config表示开启自动的<form-login>(权限验证失败回到登录页面) <http-basic>(权限验证失败弹框) <logout>(提供登出链接) -->
    <!-- use-expressions表示在access是可以使用函数如hasAnyRole -->
    <http auto-config="false" use-expressions="true">
        <!-- url级别访问控制 -->
        <intercept-url pattern="/hotel/list"
                       access="hasAnyRole('${role.admin}', '${role.user}')" />
        <intercept-url pattern="/hotel/add"
                       access="hasRole('${role.admin}')" />
        <intercept-url pattern="/hotel/delete"
                       access="hasRole('${role.admin}')" />
        <!--<intercept-url pattern="/login" requires-channel="https" />-->

        <!-- 自定义登录页面,登录验证url(验证方法还是由SpringSecurity提供,不需要自己实现) -->
        <!-- 登录成功后访问url,登录失败后访问url -->
        <form-login login-page="/login.jsp"
                    login-processing-url="/login"
                    default-target-url="/hotel/list"
                    authentication-failure-url="/login.jsp?error=true" />
        <!-- 登出成功后访问url -->
        <logout logout-success-url="/login.jsp" />
        <!-- 自动登录key以及保存时间 -->
        <remember-me key="userLoginKey" token-validity-seconds="2419200" />
    </http>

    <!-- 自定义数据用户登录验证方法 -->
    <authentication-manager>
        <authentication-provider>
            <!--<password-encoder hash="md5" ref="passwordEncoder">-->
                <!--<salt-source ref="saltSource" />-->
            <!--</password-encoder>-->
            <!-- 以下一次为用户登录验证sql,用户个人权限查询sql,以及用户组权限查询sql -->
            <!-- 这些sql会在用户登录验证,访问控制时查询 -->
            <jdbc-user-service
                    data-source-ref="dataSource"
                    users-by-username-query=
                            "SELECT username, password, enabled
                            FROM `user`
                            WHERE username = ?"
                    authorities-by-username-query=
                            "SELECT gm.username AS username, ga.group_authority AS authority
                            FROM group_authority AS ga
                            JOIN group_member AS gm ON ga.group_id = gm.group_id
                            WHERE gm.username = ?"
                    group-authorities-by-username-query=
                            "SELECT g.id, g.name AS group_name, ga.group_authority AS authority
                            FROM `group` AS g
                            JOIN group_authority AS ga ON g.id = ga.group_id
                            JOIN group_member AS gm ON g.id = gm.group_id
                            WHERE gm.username = ?"
            />
        </authentication-provider>
    </authentication-manager>

</beans:beans>

 

login.jsp

<%--
  Created by IntelliJ IDEA.
  User: zhenwei.liu
  Date: 13-7-30
  Time: 上午10:22
  To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="utf-8" %>
<html>
<head>
    <title>登录</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body>
<%-- ERROR 信息 --%>
<c:if test="${not empty param.error}">
    Error: ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
</c:if>
<%-- Login 表单 --%>
<%-- 注意此处用户名和密码以及"记住我"的name都是用spring默认的 --%>
<form action="<c:url value="/login" />" method="POST">
    <table>
        <tr>
            <td align="right">用户名</td>
            <td><input type="text" name="j_username"/></td>
        </tr>
        <tr>
            <td align="right">密码</td>
            <td><input type="password" name="j_password"/></td>
        </tr>
        <tr>
            <td></td>
            <td align="right">记住我 &nbsp
                <input id="remember_me"
                       name="_spring_security_remember_me"
                       type="checkbox" /></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="登录"/>
                <input type="reset" value="重置"/></td>
        </tr>
    </table>
</form>
</body>
</html>

 

hotelList.jsp

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="security"
          uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ page contentType="text/html;charset=utf-8" pageEncoding="utf-8" %>
<%@ include file="/WEB-INF/views/public/initVariables.jsp" %>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>酒店列表</title>
</head>
<body>
<%-- security:authentication 用户获取登录时SpringSecurity存在session中的值 --%>
<%-- 包括当前用户名,及其权限列表 --%>
<h2>欢迎! <security:authentication property="name"/></h2>
<security:authentication property="authorities" var="authorities"/>

<ul>
    <c:forEach items="${authorities}" var="authority">
        <li>${authority.authority}</li>
    </c:forEach>
</ul>
<div>
    <form action="<c:url value="/hotel/list" />" method="GET">
        <input name="code" type="text"
               value="请输入酒店代码查询 如: shanghai"
               style="color: gray">
        <input type="submit" value="确定">
    </form>
</div>
<hr/>
<%-- 此处表示用户权限需要有roleAdmin才会加载这段JSP代码 --%>
<security:authorize ifAllGranted="${roleAdmin}">
    <a href="<c:url value="/hotel/add" />">添加酒店</a>&nbsp
</security:authorize>
<a href="<c:url value="/j_spring_security_logout" />">登出</a>
<br>
<c:forEach items="${hotel_list}" var="hotel">
    <table>
        <security:authorize ifAllGranted="${roleAdmin}">
            <tr>
                <td>ID</td>
                <td>${hotel.id}</td>
            </tr>
        </security:authorize>
        <tr>
            <td>Code</td>
            <td>${hotel.code}</td>
        </tr>
        <tr>
            <td>Name</td>
            <td>${hotel.name}</td>
        </tr>
        <tr>
            <td colspan="2"><a
                    href="<c:url value="/hotel/delete?id=${hotel.id}" />">Delete</a></td>
        </tr>
    </table>
    <hr/>
</c:forEach>
</body>
</html>

 

initVariables.jsp

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%--
  Created by IntelliJ IDEA.
  User: zhenwei.liu
  Date: 13-7-30
  Time: 下午10:56
  To change this template use File | Settings | File Templates.
--%>
<%-- 读取properties文件变量 --%>
<spring:eval expression="@jspPropsHolder.getProperty('role.admin')" var="roleAdmin"/>
<spring:eval expression="@jspPropsHolder.getProperty('role.user')" var="roleUser"/>
<spring:eval expression="@jspPropsHolder.getProperty('role.annoymous')" var="annoymous"/>

要实现jsp中读取properties文件变量,还需要配置

    <!-- JSP Properties Holder -->
    <util:properties id="jspPropsHolder" location="classpath:com/qunar/properties/authorities.properties" />
    <context:property-placeholder properties-ref="jspPropsHolder" />

 

Security依赖

        <!-- Spring Security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>

 

你可能感兴趣的:(Spring Security)