The correct way to determine the required permissions in spring secure access failed

I have an application in which a user can have several roles / permissions. Whenever a user encounters a URL that is denied access based on @Secured ("role") annotations, I need to know why access is denied in the denial handler (or actually the role needed to access the resource) so I I can redirect the user to the corresponding page.

The parameters passed to the access denial handler do not contain such information.

I could create a custom selector function that will throw custom exceptions for which I could create custom error pages in web.xml, but somehow this doesn't seem to be the right approach to this situation.

What is the best approach here?

+4
source share
1 answer

In the end, I created a user access solution manager similar to the AccessManagement solution manager:

public class ConfigAttributesIncludedInExceptionAffirmativeBasedAccessDecisionManager extends AbstractAccessDecisionManager 

Inside the code is the same as AffirmativeBased code (in any case, a small class), and instead of throwing an AccessDeniedException, I throw a custom AccessDeniedException.

 throw new AccessDeniedExceptionWithConfigAttributes(messages.getMessage("AbstractAccessDecisionManager.accessDenied", "Access is denied"), configAttributes); 

An optional exception that excludes access simply extends the AccessDeniedException class and has a property called configAttributes.

 public class AccessDeniedExceptionWithConfigAttributes extends AccessDeniedException { private static final long serialVersionUID = 8733424338864969263L; private Collection<ConfigAttribute> configAttributes; public AccessDeniedExceptionWithConfigAttributes (String msg) { super(msg); } public AccessDeniedExceptionWithConfigAttributes (String msg, Throwable t) { super(msg, t); } public AccessDeniedExceptionWithConfigAttributes (String msg, Collection<ConfigAttribute> configAttributes) { super(msg); this.setConfigAttributes(configAttributes); } public Collection<ConfigAttribute> getConfigAttributes() { return configAttributes; } public void setConfigAttributes(Collection<ConfigAttribute> configAttributes) { this.configAttributes = configAttributes; } 

}

From there, I can simply check my AccessDeniedHandler class to see if the AccessDeniedException is an instance of my custom exception class, and if so, apply whatever logic I need.

 if(ade instanceof AccessDeniedExceptionWithConfigAttributes ) { AccessDeniedExceptionWithConfigAttributes adeca = (AccessDeniedExceptionWithConfigAttributes ) ade; ... } 

It works exactly the way I want it. However, if this is not the right way to do this, I would like to hear it.

0
source

Source: https://habr.com/ru/post/1499668/


All Articles