我想做的是构建 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>
但是为了进一步执行该服务,我需要确切地知道哪个用户已获得授权。那么我该怎么做呢?对于相关问题,由于没有计划更多的角色,因此有办法绕过数据库中的主线用户角色。
最佳答案
简单。
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();
Object credentials = auth.getCredentials();
要访问凭据,即密码,您需要将erase-credentials
设置为false
:
<security:authentication-manager erase-credentials="false">
...
</security:authentication-manager>
或者如果通过注释配置则:
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.eraseCredentials(false);
/* configure user-service, password-encoder etc ... */
}
关于spring - 如何使用Spring Security在代码中获取用户的授权凭据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30412138/