Springsecurity在jsp中进行权限控制的踩坑记

    注:Springsecurity的版本是4.2.4.RELEASE.

    项目中有这样的需求,想让jsp页面的某些链接、按钮等只让高权限的用户看到,使用的是Springsecurity的jsp tag.

1、jsp页面

    如下List-1.1所示,想要达到的效果是只有当用户有角色role2时才能看到"高权限的用户可见!"这段内容。

    List-1.1

<%@ 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.1

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

3、xml配置    

    要设置expressionHandler,且将defaultRolePrefix设置为"",为什么呢?这要深入源码层。

    List-3.1

<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加上作为前缀来使用。

    我就是不知道这点,所以弄了半天发现没有生效,后来进入源码才明白的!

转载于:https://my.oschina.net/u/2518341/blog/2990997

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值