【问题标题】:How to get user's authorization credentials in code with spring security?如何使用 Spring Security 在代码中获取用户的授权凭据?
【发布时间】:2015-08-05 09:18:32
【问题描述】:

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

但对于服务的进一步工作,我需要确切知道哪个用户已获得授权。那我怎么能这样做呢?对于相关问题,有办法绕过在数据库中主线用户的角色,因为没有更多的角色计划。

【问题讨论】:

标签: spring authentication spring-security crud


【解决方案1】:

简单。

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 ... */
}

【讨论】:

  • @Jason 带有 Spring Security 配置的文件。
  • 我的困惑是因为我使用的是 Grails,而不是 Spring Framework。 Grails 构建在 Spring Framework 之上并使用 Spring Security。擦除凭据进入 grails-app/conf/Config.groovy 并且不是 XML;该行显示grails.plugin.springsecurity.providerManager.eraseCredentialsAfterAuthentication = false
  • 我做了上述事情,但仍然收到空的凭据,有什么建议吗?
  • 我自己想出了 auth.getCredentials() 部分。在我的配置方法中,我指定了 httpSecurity.antMatchers("/admin/*").hasRole(UserDto.RoleEnum.ADMIN.toString()) 但我看不到它在代码中的哪个位置强制执行此操作。我怀疑我需要做一些进一步的配置,但我不确定在哪里。
猜你喜欢
  • 1970-01-01
  • 2019-12-09
  • 2019-01-13
  • 2015-10-21
  • 1970-01-01
  • 2014-11-09
  • 2013-07-07
  • 2013-05-18
  • 2019-01-07
相关资源
最近更新 更多