Custom annotation does not work in method - java

I created annotation to check permissions on the APIs. Annotation worked when placed in class or method. But when I use it for both class and method at the same time, the annotation placed on the method is ignored
Here is an example:
#RestController
#RequestMapping("/user")
#CustomAnnotation(permission="manageUser")
public class UserController {
#CustomAnnotation(permission="updateUser")
#PutMapping("/{id}")
public UserDto getUser(HttpServletRequest request) {
...
}
}
Now #CustomAnnotation(permission="updateUser") in the getUser() method will be ignored and only execute annation in class UserController
My custom code
#Target(value = {ElementType.METHOD, ElementType.TYPE})
#Retention(value = RetentionPolicy.RUNTIME)
#Inherited
#Documented
public #interface CustomAuthorize {
public String permission() default "";
public String attribute() default "";
}
#Aspect
#Component
public class CustomAnnotationAspect {
#Autowired
CustomAuthorizationImpl authBean;
#Pointcut("#annotation(customAuthorize) || #within(customAuthorize)")
public void pointcutForCustomAnnotation(CustomAuthorize customAuthorize) {
// Do nothing.
}
#Around("pointcutForCustomAnnotation(customAuthorize)")
public Object customAspect(ProceedingJoinPoint pjp, CustomAuthorize customAuthorize) throws Throwable {
if (Objects.isNull(customAuthorize)) {
System.out.println("Call from method");
// Check permission
return pjp.proceed();
}
System.out.println("Call from class");
ExpressionParser elParser = new SpelExpressionParser();
if (!customAuthorize.permission().isBlank()) {
// check permission
}
return pjp.proceed();
}
}

Related

Can I set value from custom annotation to #PreAuthorize in Spring

I have created an annotation called #AllowAccessTo as follows,
#Target({ElementType.METHOD, ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
#PreAuthorize("hasAnyAuthority(#authorityService.getPrivilege(need to inject value form allowaccess annotation))")
public #interface AllowAccessTo {
String value() default "";
}
In my Rest Controller, I have annotated that custom annotation.
#RestController
#RequestMapping("/api")
public class FooEndpoint {
#GetMapping("/students")
#AllowAccessTo("GET_ALL_STUDENT")
public List<Student> getAllStudents() {
return students;
}
}
What I want to do is, I need to inject that "GET_ALL_STUDENT" value to
#authorityService.getPrivilege({{value from custom annotation}})
#PreAuthorize("hasAnyAuthority(#authorityService.getPrivilege(value form AllowAccessTo annotation))")
This is how I solve this.
#Target({ElementType.METHOD, ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
#PreAuthorize("#securityHandler.check")
public #interface AllowAccessTo {
String value() default "";
}
#Service("securityHandler")
#Slf4j
public class SecurityHandler {
#Autowired
private HttpServletRequest httpServletRequest;
public boolean check() {
try {
log.debug("checking permission based on jwt");
List < KseRoleDto > kseRoles = new ArrayList < > ();
String accessCode = checkAllowAccess();
// check permission with access code
if (hasPermission) {
return true;
} else {
return false;
}
} catch (Exception e) {
log.error("permission not matched and exception occurred", e);
return false;
}
}
public String checkAllowAccess() {
HandlerMethod attribute = (HandlerMethod) httpServletRequest.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE);
GrantEndpoint methodAnnotation = attribute.getMethodAnnotation(GrantEndpoint.class);
return methodAnnotation.value();
}
}

How to dynamically disable specific API in spring?

I have a flag DISABLE_FLAG and I want to use it to control multiple specific APIs in different controllers.
#RestController
public final class Controller1 {
#RequestMapping(value = "/foo1", method = RequestMethod.POST)
public String foo1()
}
#RestController
public final class Controller2 {
#RequestMapping(value = "/foo2", method = RequestMethod.POST)
public String foo2()
}
I can use an interceptor to handle all the urls. Is there a easy way to do that like annotation?
You could use AOP to do something like that.
Create your own annotation...
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface Maybe { }
and corresponding aspect...
#Aspect
public class MaybeAspect {
#Pointcut("#annotation(com.example.Maybe)")
public void callMeMaybe() {}
#Around("callMeMaybe()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
// do your logic here..
if(DISABLE_FOO) {
// do nothing ? throw exception?
// return null;
throw new IllegalStateException();
} else {
// process the request normally
return joinPoint.proceed();
}
}
}
I don't think there is direct way to disable a constructed request mapping but We can disable API in many ways with some condition.
Here is the 2 ways disabling by spring profile or JVM properties.
public class SampleController {
#Autowired
Environment env;
#RequestMapping(value = "/foo", method = RequestMethod.POST)
public String foo(HttpServletResponse response) {
// Using profile
if (env.acceptsProfiles("staging")) {
response.setStatus(404);
return "";
}
// Using JVM options
if("true".equals(System.getProperty("DISABLE_FOO"))) {
response.setStatus(404);
return "";
}
return "";
}
}
If you are thinking futuristic solution using cloud config is the best approach. https://spring.io/guides/gs/centralized-configuration/
Using Conditional components
This allows to build bean with conditions, if the condition failed on startup, the entire component will never be built. Group all your optional request mapping to new controller and add conditional annotation
#Conditional(ConditionalController.class)
public class SampleController {
#Autowired
Environment env;
#RequestMapping(value = "/foo", method = RequestMethod.POST)
public String foo(HttpServletResponse response) {
return "";
}
public static class ConditionalController implements Condition {
#Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().acceptsProfiles("staging"); // Or whatever condition
}
}
}
You can solve this with annotations by utilizing spring profiles. You define two profiles one for enabled flag and another profile for the disabled flag. Your example would look like this:
#Profile("DISABLED_FLAG")
#RestController
public final class Controller1 {
#RequestMapping(value = "/foo1", method = RequestMethod.POST)
public String foo1()
}
#Profile("ENABLED_FLAG")
#RestController
public final class Controller2 {
#RequestMapping(value = "/foo2", method = RequestMethod.POST)
public String foo2()
}
Here is the link to the spring framework documentation for this feature: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Profile.html
I did it as follows :
#Retention(RUNTIME)
#Target(ElementType.METHOD)
public #interface DisableApiControl {
}
This class is my customization statement. After could use AOP :
for AbstractBaseServiceImpl :
public abstract class AbstractBaseServiceImpl {
private static boolean disableCheck = false;
public void setDisableChecker(boolean checkParameter) {
disableCheck = checkParameter;
}
public boolean getDisableChecker() {
return disableCheck;
}
}
NOTE : The above class has been prepared to provide a dynamic structure.
#Aspect
#Component
public class DisableApiControlAspect extends AbstractBaseServiceImpl {
#Autowired
private HttpServletResponse httpServletResponse;
#Pointcut(" #annotation(disableMe)")
protected void disabledMethods(DisableApiControl disableMe) {
// comment line
}
#Around("disabledMethods(disableMe)")
public Object dontRun(ProceedingJoinPoint joinPoint, DisableApiControl disableMe) throws Throwable {
if (getDisableChecker()) {
httpServletResponse.sendError(HttpStatus.NOT_FOUND.value(), "Not found");
return null;
} else {
return joinPoint.proceed();
}
}
}
checker parameter added global at this point. The rest will be easier when the value is given as true / false when needed.
#GetMapping("/map")
#DisableApiControl
public List<?> stateMachineFindMap() {
return new ArrayList<>;
}

#AroundInvoke does not work when attribute supplied

I have following classes.
#Inherited
#InterceptorBinding
#Retention(RUNTIME)
#Target({ TYPE, METHOD })
public #interface MyLogger {
public boolean skipParams() default true;
}
#MyLogger
#Interceptor
public class MyInterceptor {
#AroundInvoke
public Object logMethod(InvocationContext joinPoint) throws Exception {
// Some log statements here
}
}
public class MyClass {
#MyLogger()
void test1(){
// some code
}
#MyLogger(skipParams = true)
void test2(){
// some code
}
#MyLogger(skipParams = false)
void test3(){
// some code
}
}
#AroundInvoke does not work when attribute supplied.
logMethod() gets called for test1(), but not for test2() and test3().

How to get #PathVariable value for custom annotation?

I have a controller:
#Authorised(id = "{personId}")
#RequestMapping(value = {"{personId}"}, method = GET)
public void test(#PathVariable PersonId personId) {
System.out.println(personId); //gets personId
}
Annotation:
#Target({ElementType.METHOD})
#Retention(RetentionPolicy.RUNTIME)
#Documented
public #interface Authorised {
String id() default "";
}
Pointcut:
#Pointcut("#annotation(Authorised)")
private void AuthorisedMethod() {}
And the method that has to get {personId} value not string "{personId}":
#Before("AuthorisedMethod()")
public void checkIfIsCurrentlyAuthenticated(JoinPoint joinPoint) throws NoSuchMethodException {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getMethod().getName();
Class<?>[] parameterTypes = signature.getMethod().getParameterTypes();
Parameter[] parameters = signature.getMethod().getParameters();
Authorised annotations = joinPoint.getTarget().getClass().getMethod(methodName, parameterTypes).getAnnotation(Authorised.class);
String id = annotations.id();
System.out.println(id); // prints: "{personId}"
// do the chekcing
throw new UnauthenticatedUserException();
}
Can it be achieved and how?
UPDATE: But what if method argument parameter number don't match with the pointcut args()? I mean that what if specific method has parameter #PathVariable PersonId personId and few more, but poincut needs to know only PersonId personId?
Like #statut said you have to write args() like that: args(personId,..)
You can modify #Before() annotation to have PersonId value and pass this value to aspect, for example
#Before("AuthorisedMethod() && args(personId)")
public void checkIfIsCurrentlyAuthenticated(JoinPoint joinPoint, PersonId personId) throws NoSuchMethodException {}
To test it I had the following Aspect:
#Aspect
#Component
public class SomeAspect {
#Pointcut("#annotation(Authorised)")
private void AuthorisedMethod() {
}
#Before("AuthorisedMethod() && args(personId)")
public void checkIfIsCurrentlyAuthenticated(JoinPoint joinPoint, PersonId personId) throws NoSuchMethodException {
System.out.println("aspect " + personId.getId());
}
}
Configuration class:
#Configuration
#ComponentScan(basePackages = {"test"})
#EnableAspectJAutoProxy(proxyTargetClass = true)
public class Config {
}
Test component:
#Component
public class Test {
#Authorised(id = "{personId}")
public void test(PersonId personId) {
System.out.println("component " + personId.getId()); //gets personId
}
}
And testNG's runner:
#ContextConfiguration(classes = Config.class)
public class TestRunner extends AbstractTestNGSpringContextTests {
#Autowired
test.Test test;
#Test
public void testName() {
test.test(new PersonId("id"));
}
}
When I run it, I get printed "aspect id" from aspect and "component id" from invoked method.
You can also get the value of the PathVariable in RequestMapping URL using HandlerInterceptor if that is possible for you.
Write a Handler class that intercepts this Request.
public class AuthorisedHandler extends HandlerInterceptorAdapter {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if (!isResourceHandler(handler) && (handler instanceof HandlerMethod)) {
HandlerMethod hm = (HandlerMethod) handler;
Method method = hm.getMethod();
Authorised authAnnotation = method.getAnnotation(Authorised.class);
if (authAnnotation != null) {
String personId = getPersonId(request);
//Do all your validations Here
}
}
return true;
}
#SuppressWarnings("rawtypes")
private String getPersonId(HttpServletRequest request) throws IOException {
String personId = request.getParameter("personId");
if(personId == null || personId.equals("")){
Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
personId = (String) pathVariables.get("personId");
}
return personId;
}
private boolean isResourceHandler(Object handler) {
return handler instanceof ResourceHttpRequestHandler;
}
}
And you must configure this Handler bean in spring config xml or Spring Java Config.
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.**.AuthorisedHandler" />
</mvc:interceptor>
</mvc:interceptors>
Now, all the requests will go through this Interceptor. Only which are annotated with #Authorised will go through.

pass result of annotation work to annotated method

Annotation:
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
public #interface Multipart {
Class acceptClass();
}
Annotated method:
#Multipart (acceptClass = SomeClass.class)
public void someMethod(SomeClass a){
//do stuff..
}
MultipartAspect:
#Aspect
public class MultipartAspect {
#Autowired(required=true)
private HttpServletRequest request;
#Pointcut(value = "#annotation(Multipart)", argNames = "multipart")
public void before(JoinPoint jp, Multipart multipart) {}
#Before("before()")
public SomeClass doStuffBeforeThing() {
SomeClass sc = new SomeClass(); //object of passed class
//do something..
return sc; //return this to annotated method(somemethod)
}
}
I want before method works execute annotation, create object of passed class(SomeClass) and the pass object of this class to annotated method. Could I do this?
You should use #Around advice instead of #Before.

Categories

Resources