jhipster fine grain authorization, remove ROLE based authorization

六月ゝ 毕业季﹏ 提交于 2021-02-10 06:31:41

问题


I have been searching on how to remove the ROLE based authorization and replace it with fine grain authorization. What I meant by fine grain is All method has a @PreAuthorize("isAuthorize('GETCLIENT')") or directly @IsAuthorize("GETCLIENT"). If the user has GETCLIENT in Authorization List, then the method can be executed. Otherwise, the system give error message or just deny access. Any clue or information regarding how to do that is very much appreciated. Thank you.


回答1:


Like I said in the comment one quick and easy way to do this is to add your new custom authorities in the AuthoritiesConstants.java class. You have examples of how to do this here and here.

public final class AuthoritiesConstants {

    public static final String ADMIN = "ROLE_ADMIN";

    public static final String USER = "ROLE_USER";

    public static final String ANONYMOUS = "ROLE_ANONYMOUS";

    public static final String GETCLIENT = "ROLE_GETCLIENT"; // custom

    private AuthoritiesConstants() {
    }
}

Remember to insert the new role into your jhi_authority database table. You can assign new authorities to a user via the user management interface admin/user-management, it's possible the user needs to relog for the change to take effect.

Then in the method you want to secure just add:

    @GetMapping("/clients/{id}")
    @PreAuthorize("hasRole(\"" + AuthoritiesConstants.GETCLIENT + "\")")
    public ResponseEntity<ClientDTO> getClient(@PathVariable Long id) {
        log.debug("REST request to get Client : {}", id);
        Optional<ClientDTO> clientDTO = clientService.findOne(id);
        return ResponseUtil.wrapOrNotFound(clientDTO);
    }

I said @Secured before but in reality you should use @PreAuthorize since it is more powerful and lets you work with Spring Expression Language (SpEL).

The go to resource to understand how JHipster security works is here, but in reality it just follows the standard Spring Security guidelines (as with many other things) so the official documentation about Spring Security should apply too.

Also, if you find this is too simple or that it is breaking the default conventions I found this guide about custom privileges to be particularly great. It's a bit more work, but should work better since you separate authorities (roles) from privileges.



来源:https://stackoverflow.com/questions/60902534/jhipster-fine-grain-authorization-remove-role-based-authorization

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!