0

I am writing a small application using the stack Spring Boot + Spring Security + JavaFX. For Integration JavaFX with Spring Boot & Spring Security I used this source from Github: https://github.com/emorgado/javafx-springboot-springsecurity

How can I use Spring Security extras (like extras for Thymeleaf) in FXML files? For example: Thymeleaf -

<li class="nav-item" sec:authorize="hasRole('ROLE_ADMIN')">
  <a class="nav-link" th:href="@{/settings}">
     <p>Settings</p>
  </a>
</li>

FXML -

<Menu mnemonicParsing="false" text="Settings">
    <MenuItem mnemonicParsing="false" onAction="#mainSettingsAction" text="Main settings" />
</Menu>

Is there any way to use attributes like sec:authorize or tags <security> in FXML file?

2 Answers 2

1

I think you should make your own fxml compiler like e(fx)clipse FXML compiler.

but, You can use this trick.

in .fxml

<MenuItem fx:id="menuSettings" mnemonicParsing="false" onAction="#mainSettingsAction" text="Main settings" userData="ROLE_ADMIN"/>

in the controller.

@FXML private MenuItem menuSettings;

if(menuSettings != null && menuSettings.getUserData() != null) {
    if("ROLE_ADMIN".equals(menuSettings.getUserData().toString())) {
        menuSettings.getParentMenu().getItems().remove(menuSettings);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer! I tried what you propose to do, but it doesn’t work correctly. I used logger to get current User Role - log.info(settingsMenu.getUserData()); It returns ROLE_ADMIN when I authorize with admin privileges or just user privileges. So your code delete menuSettings for both users (for admin & for user)
May be I need to get current user Role from autowired AuthenticationManager. And then check if current user roleList contains ROLE_ADMIN ?
0

Many thanks to Charles Lee for help! I provide my solution to this problem:

@FXML private MenuItem settingsMenu;
    @FXML
    public void initialize(URL location, ResourceBundle resources) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Doctor currentUser = (Doctor) doctorService.findDoctorByDoctorUsername(authentication.getName());

    if(!currentUser.getRoles().contains(Role.ADMIN)) {
    settingsMenu.getParentMenu().getItems().remove(settingsMenu);
    }

    }

1 Comment

Sure. I just gave a hint. Of course, "ROLE_ADMIN" should not be hardcoded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.