3

I have some problem. I use spring security for my application, and when i marked method annotation @Secured("ROLE_ADMIN"),it does not work.

@Secured("ROLE_ADMIN")
@RequestMapping(value = "/greeting",produces = "application/json")
public @ResponseBody List<UserEntity> greeting() {
    return userService.getAllCurrentUsers();
}

This security-config.xml

<global-method-security secured-annotations="enabled" pre-post-annotations="enabled"/>

<http pattern="/resources/**" security="none"/>
<http pattern="/loginSecurity" security="none"/>
<http pattern="/favicon.ico" security="none" />
<http use-expressions="true">
    <intercept-url pattern="/**" access="hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')"/>
    <form-login login-page="/loginSecurity" default-target-url="/workspace"/>
</http>

<authentication-manager>
    <authentication-provider>
        <password-encoder hash="bcrypt" />
        <jdbc-user-service data-source-ref="dataSource"
                           authorities-by-username-query="SELECT userentity.username , roleentity.role_name from userentity
                                                    JOIN userentity_roleentity ON userentity.userid = userentity_roleentity.userlist_userid
                                                    JOIN roleentity ON userentity_roleentity.rolelist_role_name = roleentity.role_name
                                                    WHERE userentity.username = ?"
                           users-by-username-query="SELECT username,pwd,enable FROM userentity where username = ?"/>
    </authentication-provider>
</authentication-manager>

The authentication works. Roles in the database are correct. This code also works.

sec:authorize access="hasRole('ROLE_ADMIN')">
<button onclick="loadHeadRef('workspace','settings')">
  <img src='<spring:url value="/resources/image/settings.png"/>' alt="">Settings</button>
</sec:authorize>
Denis Markov
  • 309
  • 4
  • 12
  • 1
    possible duplicate of [@Secured does not work in controller, but intercept-url seems to be working fine](http://stackoverflow.com/questions/6651119/secured-does-not-work-in-controller-but-intercept-url-seems-to-be-working-fine) – M. Deinum Mar 02 '15 at 13:54

1 Answers1

2

Try using @PreAuthorize

@PreAuthorize("hasAnyRole('ROLE_USER','ROLE_ADMIN','ROLE_APPROVAL_PENDING')")

in the spring-servlet.xml put the following

<security:global-method-security
        pre-post-annotations="enabled" secured-annotations="enabled" />
    <mvc:annotation-driven />
LynAs
  • 6,407
  • 14
  • 48
  • 83