首页 文章

http安全性hasRole()方法如何工作

提问于
浏览
0

我在Spring中开发了一个RESTful API,它从数据库(MongoDB)中检索用户信息,并将该数据返回给使用此REST API的客户端 . 但在检索数据之前,REST API会检查用户是否是管理员 . Only the admin can perform GET operations to retrieve user info

所以在我的securityconfig.java类中我有这个:

http.authorizeRequests()
            .antMatchers("/users/get/**", "/users/get/**").hasRole("ADMIN");

http.httpBasic();

现在,用户都有自己的角色,一切都按预期工作,因为当我调用 curl adminusername:adminpassword@localhost:8080/users/get/AllUsers

我能够检索所有用户,因为用户名为 adminusername 的用户是管理员,并且他有权限 . 但是,如果我用非管理员用户名替换 adminusername ,我会收到拒绝访问错误 .

我的问题是,在@localhost之前是 adminusername:adminpassword 部分:8080 .... HTTP请求的标头?

我问的原因是因为我需要创建一个能够登录的客户端,验证他的凭据(用户名和密码),并将用户名和密码用作 session id ,以便客户端进行HTTP请求调用时登录后,用户名和密码将附加到标头,并由REST API处理 .

hasRole()的

http.authorizeRequests()
                .antMatchers("/users/get/**", "/users/get/**").hasRole("ADMIN");

在安全配置中依赖于_localhost之前的 username:password :8080 ....这与 spring 休息API的 @RequestHeader 相同吗?

1 回答

  • 0

    首先,Http Basic是一种通过标头发送用户凭据的方法 -

    var header = {'Authorization': 'Basic '+btoa(username+':'+password)} //javascript
    

    第二件事是用户的权限 . 您系统中的用户必须创建用户,并添加权限,例如:

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("mati").password("qwerty").roles("ADMIN", "USER").and()
                .withUser("mati2").password("qwerty").roles("USER");
    }
    

    这些用户成为后来的类 Principal 中的对象,这些对象具有其授予的权限(如"ROLE_USER"或"ROLE_ADMIN") .

    当你打电话的时候

    curl adminusername:adminpassword@localhost:8080/users/get/AllUsers
    

    Spring Security将检查正确的 Principal (使用给定的用户名并检查密码是否匹配),将其加载到 SecurityContext 并检查 Principal 是否具有权限"ROLE_ADMIN"( hasRole("ADMIN") ) . 我必须补充一点,这很棘手,我不记得确切,如果你是 hasRole("ADMIN")hasRole("ROLE_ADMIN") .

    我希望这能回答你的问题 .

相关问题