Springsecurity在jsp中進行權限控制的踩坑記

    注:Springsecurity的版本是4.2.4.RELEASE.html

    項目中有這樣的需求,想讓jsp頁面的某些連接、按鈕等只讓高權限的用戶看到,使用的是Springsecurity的jsp tag.java

一、jsp頁面

    以下List-1.1所示,想要達到的效果是隻有當用戶有角色role2時才能看到"高權限的用戶可見!"這段內容。web

    List-1.1spring

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<html>
<head>
    <title>xxx</title>
</head>
<body>

<sec:authorize access="hasRole('role2')">
    高權限的用戶可見!
</sec:authorize>

.......

2、項目中要引入jsp tag的依賴

    List-2.1express

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-taglibs</artifactId>
    <version>4.2.4.RELEASE</version>
</dependency>

3、xml配置    

    要設置expressionHandler,且將defaultRolePrefix設置爲"",爲何呢?這要深刻源碼層。jsp

    List-3.1spa

<security:http entry-point-ref="xx" use-expressions="true">
    ...
    <security:expression-handler ref="expressionHandler"/>
    ...
</security:http>

<bean id="expressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler">
    <!--有意的設置爲""-->
    <property name="defaultRolePrefix" value=""/>
</bean>
...

    DefaultWebSecurityExpressionHandler中,defaultRolePrefix的值是ROLE_,若是defaultRolePrefix的值不爲null或者"",那麼SecurityExpressionRoot的方法getRoleWithDefaultPrefix中,會把defaultRolePreix加上做爲前綴來使用。code

    我就是不知道這點,因此弄了半天發現沒有生效,後來進入源碼才明白的!xml

相關文章
相關標籤/搜索