【问题标题】:How to write/check permisions of auth in spring如何在春季编写/检查身份验证权限
【发布时间】:2015-01-10 17:15:51
【问题描述】:

我有这样的数据库:

Users <-> Roles -> Permissions

在 Spring 中,我使用 spring security 登录 - 我不检查用户具有什么角色。每个人都应该登录。

<authentication-manager alias="authenticationManager">
    <authentication-provider>
       <password-encoder  hash="bcrypt"/>
        <jdbc-user-service data-source-ref="dataSource"
            users-by-username-query="select NAME, PASSWORD, 1 as enabled from USERS 
                                     where NAME=?"
            authorities-by-username-query="SELECT * FROM USERS u JOIN USERS_MTM_ROLES uur
                                            ON u.ID=uur.ROLE_ID join USER_ROLES ur 
                                            on  ur.id=uur.role_id  where NAME=?" />
    </authentication-provider>

<http auto-config="true" use-expressions="true">
    <intercept-url pattern="/admin**" />
    <form-login login-page="/login" default-target-url="/admin"
        authentication-failure-url="/login?error" username-parameter="NAME"
        password-parameter="PASSWORD"  />
    <logout logout-success-url="/login?logout" />
</http>

好的,一切都很好!

但是知道,我想使用@Secure 或@Preauthorize 注释,以检查用户是否有权限。但是 spring 将如何知道用户是否有具体的权限呢?权限应该写在某处吗?

换句话说,我希望我的控制器是安全的。如果用户有具体权限,他/她应该可以访问控制器,否则用户不应该。我该怎么做?

【问题讨论】:

    标签: java spring spring-mvc spring-security aspectj


    【解决方案1】:

    Spring Security 为控制器授权提供注解。这是一个例子: http://www.mkyong.com/spring-security/spring-security-hello-world-annotation-example/

    另外,我强烈建议您使用 Shiro 而不是 Spring Security。在实践中,我意识到配置 Spring Security 远比它的价值复杂得多。请参考http://shiro.apache.org

    【讨论】:

    • 我的问题是另一个。我只有关于权限的具体问题。
    【解决方案2】:

    如果您想将hasPermission 语法与@PreAuthorize 一起使用,您需要一个权限评估器。 Spring Security 内置了两个,deny-all 和 ACL。你想要的可能是你自己的,实现PermissionEvaluator 接口。

    然后将您的权限评估器的实例放入表达式处理程序中:

    @Autowired
    private PermissionEvaluator permissionEvaluator;
    
    @Bean
    public DefaultMethodSecurityExpressionHandler expressionHandler() {
        DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
        handler.setPermissionEvaluator(permissionEvaluator);
        return handler;
    }
    

    到您的安全配置:

    <global-method-security pre-post-annotations="enabled" secured-annotations="enabled">
      <expression-handler ref="expressionHandler" />
    </global-method-security>
    

    【讨论】:

      猜你喜欢
      • 2022-07-22
      • 1970-01-01
      • 2014-05-22
      • 2015-12-16
      • 2023-03-24
      • 2022-01-11
      • 2021-03-10
      • 2020-04-08
      • 2013-02-24
      相关资源
      最近更新 更多