简体   繁体   English

Spring安全性hasPermission无效

[英]Spring security hasPermission is not working

I am trying to integrate Spring Security in my spring web application. 我试图在我的春季Web应用程序中集成Spring Security。 Basically I need to hide some menus based on user permission. 基本上我需要根据用户权限隐藏一些菜单。 Here is what I did. 这就是我做的。

I added below JARS in classpath. 我在classpath中添加了JARS。

spring-security-acl-4.0.2.RELEASE.jar
spring-security-config-4.0.2.RELEASE.jar
spring-security-core-4.0.2.RELEASE.jar
spring-security-taglibs-4.0.1.RELEASE.jar
spring-security-web-4.0.2.RELEASE.jar

Below are the entries in web.xml 以下是web.xml中的条目

<context-param>
    <param-name>log4jConfiguration</param-name>
    <param-value>/WEB-INF/web_log4j.xml</param-value>
</context-param>

<listener>
    <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
</listener>

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-root.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

I wrote a class CustomPermissionEvaluator like below. 我写了一个类CustomPermissionEvaluator,如下所示。

public class CustomPermissionEvaluator implements PermissionEvaluator{


@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
    HttpServletRequest request = (HttpServletRequest) targetDomainObject;
    Profile userProfile = (Profile) request.getSession().getAttribute("testprofile");
    if (userProfile.getPermissionMap().get(String.valueOf(permission)) != null) {
        return true;
    } else {
        return false;
    }
}

@Override
public boolean hasPermission(Authentication arg0, Serializable arg1,
        String arg2, Object arg3) {
    // TODO Auto-generated method stub
    return false;
}

} }

After this I wrote SecurityConfig file. 在此之后我写了SecurityConfig文件。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
public void configure(WebSecurity web) throws Exception {
    DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
    handler.setPermissionEvaluator(new CustomPermissionEvaluator());
    web.expressionHandler(handler);
}

} }

I have below entries in my spring-root.xml 我在spring-root.xml中有以下条目

<sec:global-method-security pre-post-annotations="enabled">
    <sec:expression-handler ref="expressionHandler" />
</sec:global-method-security>
<bean id="expressionHandler"
    class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
    <property name="permissionEvaluator" ref="permissionEvaluator" />
</bean>
<bean id="permissionEvaluator" class="main.java.com.config.CustomPermissionEvaluator" />

Now in my JSP file I am using below taglib. 现在在我的JSP文件中,我在taglib下面使用。

and below code 以下代码

<sec:authorize access="hasPermission('cadastra_categoria', #request)">      
                <div id="TEST">
                </div>
            </sec:authorize>

But it is not working. 但它没有用。 Any suggesation will be appreciated. 任何建议将不胜感激。

"hasPermission('cadastra_categoria', #request)" “hasPermission('cadastra_categoria',#request)”

Actually, valid call has to have arguments swapped, first one must be target domain object and second - permission: 实际上,有效调用必须交换参数,第一个必须是目标域对象,第二个 - 权限:

hasPermission(#request, 'cadastra_categoria')

I assume you also double-checked you've imported sec taglib to your JSP as required 我假设您还仔细检查了您是否已根据需要将sec taglib导入JSP

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

And finally as clarified in 2-nd part of this answer , define the following: 最后,如本答案的第二部分所述,请定义以下内容:

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AnnotationConfigDispatcherServletInitializer extends
    AbstractAnnotationConfigDispatcherServletInitializer {

  @Override
  protected Class<?>[] getRootConfigClasses() {
    return new Class[] {
      SecurityConfig.class //your SecurityConfig
    };
  }
}

to make sure configure(WebSecurity web) is called during your web application startup 确保在Web应用程序启动期间调用configure(WebSecurity web)

As i understand your question you have created CustomPermissionEvaluator class but you are not checking with your Authenticated user permission. 据我所知,您已经创建了CustomPermissionEvaluator类,但是您没有使用Authenticated用户权限进行检查。

I am directly writing the code CustomPermissionEvaluator for clear my point there might be any error: 我直接编写代码CustomPermissionEvaluator以清楚我的观点可能有任何错误:

public class CustomPermissionEvaluator implements PermissionEvaluator {

    public boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) {
        if ((auth == null) || (targetDomainObject == null) || !(permission instanceof String)){
            return false;
        }

        Profile userProfile = (Profile) request.getSession().getAttribute("testprofile");
        String targetType = userProfile.getPermissionMap().get(String.valueOf(permission));

        return hasPrivilege(auth, targetType, permission.toString().toUpperCase());
    }

    private boolean hasPrivilege(Authentication auth, String targetType, String permission) {
        for (GrantedAuthority grantedAuth : auth.getAuthorities()) {
            if (grantedAuth.getAuthority().startsWith(targetType)) {
                if (grantedAuth.getAuthority().contains(permission)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public boolean hasPermission(Authentication arg0, Serializable arg1, String arg2, Object arg3) {
        // TODO Auto-generated method stub
        return false;
    }
}

请尝试hasAnyRole并检查一次ie

<sec:authorize access="hasAnyRole('ROLE_NAME')"> TEST </sec:authorize>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring Security 具有集合权限<Object> - Spring Security hasPermission for Collection<Object> spring security中如何解释hasPermission? - How to interpret hasPermission in spring security? Spring Security中的hasPermission()不会调用CustomPermissionEvaluator - hasPermission() in Spring Security doesnt call the the CustomPermissionEvaluator 使用Spring Security&#39;hasPermission()&#39;对未经授权的REST服务请求返回JSON - Return JSON on unauthorized REST service request using Spring Security 'hasPermission()' Spring Security PermissionEvaluator:如何使用 object ID 实现 hasPermission 方法? - Spring Security PermissionEvaluator: how to implement hasPermission method with object ID? 在Spring Security中与hasPermission一起使用时,权限参数是否区分大小写? - Is the permission parameter case-sensitive when using with hasPermission in spring security? 为什么在Spring Security中的hasPermission检查中使用“ #post”而不是“ post” - Why use “#post” instead of “post” in hasPermission check in Spring Security Spring Security使用PreAuthorize中的hasPermission仅使用一个参数 - Spring security use hasPermission within PreAuthorize with only one parameter Spring Security对我不起作用 - Spring security not working for me 春季安全许可证全部不起作用 - spring security permitAll not working
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM