【问题标题】:Using password from spring security to authenticate REST call使用来自 Spring Security 的密码来验证 REST 调用
【发布时间】:2016-08-12 16:13:41
【问题描述】:
我有一个 Spring Boot Web 应用程序,该应用程序具有与 LDAP 身份验证集成的 Spring Security。此 Web 应用程序在内部进行 REST 调用。这些 REST 调用具有用户名密码身份验证。这个用户名-密码与 spring security 使用的相同。无论如何我可以获得由spring security认证的用户名密码,以便在REST调用中使用。如果不是这样,有没有其他方法可以做到这一点。
提前致谢。
【问题讨论】:
标签:
java
spring-mvc
authentication
spring-security
spring-boot
【解决方案1】:
Spring Security 是根据安全属性中的规则执行的。
这意味着你只需要启用spring-security,唯一的问题是如果没有授权它会进入一个Restful客户端无法理解的Not Authorized Page。但是,如果 Restful 客户端已经过身份验证并被授予有效会话,那么它将能够通过 Security_check 并访问受保护的页面。
我猜 Spring 安全性就像 AOP 一样工作,所以每个受保护的页面都有一个 Security_check 横切,只有在身份验证存在时才允许访问该页面。
【解决方案2】:
无论如何,我解决了编写自定义 AuthenticationProvider 的问题,它将执行 LDAP 身份验证并为将来的 REST 调用获取用户名密码。
【解决方案3】:
我认为有一个很好的方法适合你的情况。
默认情况下,Spring Security 不会在进行身份验证后将密码存储在内存中,因此您需要更改它。使用 Java 配置,添加 configure(AuthenticationManagerBuilder) 方法:
auth.eraseCredentials(false);
然后你可以得到当前用户的用户名和密码:
String username = SecurityContextHolder.getContext().getAuthentication().getName();
Object rawPassword = SecurityContextHolder.getContext().getAuthentication().getCredentials();