Question

I have some Spring Controller methods that I had, at first, secured with the @Secured notation

@Secured("Role_Admin")
public void dummyMethod(HttpServletRequest request) ...

Which would recognize the role fine, or reject if the user did not have the role (as expected). However, I tried switching to use the @PreAuthorize annotation, and now EVERYTHING is getting denied.

@PreAuthorize("hasRole('Role_Admin')")
public void dummyMethod(HttpServletRequest request) ...

If I remove the @PreAuthorize annotation, and do something, say

request.isUserInRole("Role_Admin")

that will return true. If I leave in the annotation, and then check the user's roles in the access denied handler, I can see the 'Role_Admin' authority is granted to the user.

So I'm not exactly sure what roles/authorities the code behind @PreAuthorize is checking. Does anybody know what spring security classes I can check?

EDIT

I'm using Java to configure everything. So it looks like this:

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfigurator extends GlobalMethodSecurityConfiguration { ...

In my reply to an answer below, the reason I'm switching from @Secured is because it's not kicking off my AccessDeniedHandler. If I could force it to do so, I'd stick with it. @PreAuthorize does kick off the handler.

EDIT2

As pointed out by Andrei, I tried defining this in my configuration. It did not make a difference though.

@Bean
public SimpleMappingExceptionResolver resolver() {
    SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();

    resolver.setExcludedExceptions(AccessDeniedException.class);

    Properties mappings = new Properties();
    mappings.put("org.springframework.web.servlet.PageNotFound", "p404");
    mappings.put("org.springframework.dao.DataAccessException", "dataAccessFailure");
    mappings.put("org.springframework.transaction.TransactionException", "dataAccessFailure");

    resolver.setExceptionMappings(mappings);

    return resolver;
}
Was it helpful?

Solution

Why are you wanting to use @PreAuthorize as opposed to @Secured? I imagine that your @PreAuthorize is failing because you haven't set your http security to use expressions:

<http use-expressions="true">

I imagine if you do this then it won't matter which version you use. I seem to remember one of the Spring developers who posts on SO saying that @Secured is the preferred method because it is newer than @PreAuthorize or some such reason. I suspect that @Secured is more self-contained and doesn't interact with as many Spring components. If this doesn't work, let me know.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top