如何在Spring安全性的代码中获取用户的授权凭证?

Ale*_*lex 7 authentication spring crud spring-security

我要做的是构建CRUD REST服务.它将维护用户和他们的记录数据库.我想允许用户只能访问自己的记录.我使用Spring Security进行身份验证,并使用Bcrypt存储用户密码.我现在可以理解我的spring-security.xml如下:

<security:http auto-config='true'>
    <security:intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
    <security:http-basic />
</security:http>

<security:authentication-manager>
    <security:authentication-provider>
    <authentication-provider>
        <password-encoder ref="encoder" />
        <jdbc-user-service data-source-ref="dataSource"
            users-by-username-query="select username,password, enabled from users where username=?"
            authorities-by-username-query="select username, role from user_roles where username =?" />
    </authentication-provider>
    </security:authentication-provider>
</security:authentication-manager>
Run Code Online (Sandbox Code Playgroud)

但是对于服务的进一步工作,我需要确切知道哪些用户已被授权.那我该怎么办呢?对于相关问题,有办法绕过主流用户在数据库中的角色,因为没有更多的角色计划.

hol*_*s83 16

简单.

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();
Object credentials = auth.getCredentials();
Run Code Online (Sandbox Code Playgroud)

要访问凭据(即密码),您需要设置erase-credentialsfalse:

<security:authentication-manager erase-credentials="false">
  ...
</security:authentication-manager>
Run Code Online (Sandbox Code Playgroud)

或者,如果通过注释进行配置,则:

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.eraseCredentials(false);
    /* configure user-service, password-encoder etc ... */
}
Run Code Online (Sandbox Code Playgroud)