Java 8/Spring constants in PreAuthorize annotation

Thanks to oli37 I have implemented this logic in a following way:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

    private DefaultMethodSecurityExpressionHandler defaultMethodExpressionHandler = new DefaultMethodSecurityExpressionHandler();

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        return defaultMethodExpressionHandler;
    }

    public class DefaultMethodSecurityExpressionHandler extends org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler {

        @Override
        public StandardEvaluationContext createEvaluationContextInternal(final Authentication auth, final MethodInvocation mi) {
            StandardEvaluationContext standardEvaluationContext = super.createEvaluationContextInternal(auth, mi);
            ((StandardTypeLocator) standardEvaluationContext.getTypeLocator()).registerImport(Permission.class.getPackage().getName());
            return standardEvaluationContext;
        }
    }

}


    @PreAuthorize("hasAuthority(T(Permission).APPEND_DECISION)")
    @RequestMapping(value = "/{decisionId}/decisions", method = RequestMethod.PUT)
    public DecisionResponse appendDecisionToParent(@PathVariable @NotNull @DecimalMin("0") Long decisionId, @Valid @RequestBody AppendDecisionRequest decisionRequest) {
    ...
        return new DecisionResponse(decision);
    }

I thing the good way is not to mixed both

You can have constants

public static final String ROLE_ADMIN = "auth_app_admin";

and have that other side

@PreAuthorize("hasRole(\"" + Constants.ROLE_ADMIN + "\")")

this is much clear


Here is a simple approach to defining authorities in a single place that doesn't require any in-depth Spring Security config.

public class Authority {
    public class Plan{
        public static final String MANAGE = "hasAuthority('PLAN_MANAGE')";
        public static final String APPROVE = "hasAuthority('PLAN_APPROVE')";
        public static final String VIEW = "hasAuthority('PLAN_VIEW')";
    }
}

Securing services...

public interface PlanApprovalService {

    @PreAuthorize(Authority.Plan.APPROVE)
        ApprovalInfo approvePlan(Long planId);

    }
}