2

here is my code looks like:

public class MyController {

@Value("${resource.clientId}") // this value is retreiving from vault
private String clientId;

 @PreAuthorize("isClient(#clientId)") //isClient a custom security method
 public String Mymethod(Authentication authentication){

 }
}

If I use the clientId as a arg of Mymethod, then it's working fine. But at the same time I am facing an issue like 'could not find the placeholder resource.clientId' due to vault APPROLE token expiry.

So decided to change the method arg to class level variable like above. But this @PreAuthorize [@PreAuthorize("isClient(#clientId)")] logic is not picking the clientid. Could anyone please share a suitable way to sort out this issue? Which expression do I need to use here to solve this?

Rafeek Muhammed
  • 133
  • 2
  • 3
  • 13
  • Let me check if I understand correctly: You want Spring EL to evaluate static variable? – Daniel Jacob May 21 '20 at 16:58
  • @DanielJacob - I would like to pass the clientId (from class level variable) value as a parameter of isClient() custom security method. What's the best way to do (using expressions or any other way) that without any issues. I tried different ways I am getting NullPointer / failed expression types of issues. – Rafeek Muhammed May 22 '20 at 10:06
  • @DanielJacob - "Let me check if I understand correctly: You want Spring EL to evaluate static variable " - pls share the expression if that solves my issue. - Thanks – Rafeek Muhammed May 22 '20 at 13:25
  • Is it an instance variable or is it a static variable? – Daniel Jacob May 22 '20 at 15:49
  • @Daiel Jacob - Can I use instance variable, currently I used static variable (as mentioned in answer section), but getting sonar issues because static variable should be private and final. If I put private, clientid is not getting and throwing a failed evaluate expression. – Rafeek Muhammed May 23 '20 at 14:41

2 Answers2

1

Finally, I found a solution to do this - I am not sure is there any better solutions than this.

public class MyController {

  public static String CLIENT_ID;

  @Value("${resource.clientId}") // this value is retrieving from vault
  public void setClientId(String clientId) {
      CLIENT_ID = clientId;
  }

  @PreAuthorize("isClient({T(com.test.MyController).CLIENT_ID})") //isClient a custom security method
  public String Mymethod(Authentication authentication){

  }

}

Inject the vault value to a static variable using non static method and finally pass that static variable to @PreAuthorize custom method. I hope, this would be helpful for others too..

Rafeek Muhammed
  • 133
  • 2
  • 3
  • 13
0

Alternative answer would be to create a @Component as described in this issue:

https://stackoverflow.com/a/61080418/2489730

@Component("Roles")
public final class RoleContainer {
  public static final String Admin = "Admin";
}
@PreAuthorize("hasRole(@Roles.Admin)")
Beast
  • 115
  • 16