grep
grep

Reputation: 5623

How to write/check permisions of auth in spring

I have db like this:

Users <-> Roles -> Permissions

In Spring I log in with spring security - I don't check what role does user have. Everyone should be logged in.

<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>

Ok everything is well!

But know, I want to use @Secure or @Preauthorize annotation, in order to check if user have the permission or not. But how spring will get to know whether user have concrete permissions or not? Should the permissions written in somewhere?

In the other words, I want my controllers to be secured. If user have concrete permission, he/she should have access to controller, otherwise user should not. how should I do that?

Upvotes: 0

Views: 667

Answers (2)

holmis83
holmis83

Reputation: 16604

If you want to use hasPermission syntax with @PreAuthorize you need a permission evaluator. There are two built-in in Spring Security, deny-all and ACL. What you want is probably your own, implementing PermissionEvaluator interface.

Then put an instance of your permission evaluator in an expression handler:

@Autowired
private PermissionEvaluator permissionEvaluator;

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

To your security configuration:

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

Upvotes: 1

BurnetZhong
BurnetZhong

Reputation: 448

Spring Security offers annotations for controller authorization. Here is an exampl: http://www.mkyong.com/spring-security/spring-security-hello-world-annotation-example/

Also, I strongly recommend you using Shiro instead of Spring Security. In practice, I realized configuring Spring Security has been far more complex than its value. Please refer to http://shiro.apache.org

Upvotes: 1

Related Questions