spring - 如何使用Spring Security在代码中获取用户的授权凭据?

标签 spring authentication spring-security crud

我想做的是构建 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/

相关文章:

java - Spring阻止用户通过浏览器和ajax访问url

java - jersey-spring3 (2.25.1) 在 jetty-9.3.3 中产生 "Failed startup of context"错误

java - 调用依赖微服务

node.js - 如何使用 Azure AD 实现身份验证和授权 Nodejs Azure Functions 应用程序

php - 没有数据库的简单登录脚本

Spring security login-processing-url 抛出 405 请求方法 POST 不支持

java - 仅使用 Spring Security 为某些请求设置多种身份验证方法

mysql - 为什么关联集合包含空值? (Hibernate, Annotation, Spring)

spring - Noarg构造函数未创建

authentication - Django Rest Framework session 与 token 认证