【发布时间】:2014-05-27 21:38:06
【问题描述】:
我正在设计一个带有 Grails 后端的单页应用程序。后端的某些服务需要身份验证,因此我尝试使用 Spring Security 插件和客户端 cookie 来管理它。
我已经尝试了所有方法,但似乎没有很多关于创建登录服务的信息,该服务采用用户名/密码参数集,并将会话设置为经过身份验证。这是我到目前为止所拥有的。
class LoginService {
def userDetailsService
def daoAuthenticationProvider
def login(String username, String password )
{
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
Authentication authentication =
new UsernamePasswordAuthenticationToken(username, password);
SecurityContextHolder.getContext().setAuthentication(authentication);
daoAuthenticationProvider.additionalAuthenticationChecks(
userDetails, authentication)
authentication.isAuthenticated()
}
}
我的错误想法是 UserDetailsService 从数据库中加载一个与相关用户名有关的对象。身份验证对象是我想使用的关于该 UserDetail 的方法。然后,daoAuthenticationProvider 检查详细信息和身份验证对象是否相互匹配(检查有效密码)。
这是我的服务测试,其中两个测试都因“错误凭据”而失败
def fixtureLoader
def grailsApplication
def loginService
def loginPerson
def setup() {
loginPerson = new Person();
loginPerson.username = "username"
loginPerson.password = "password"
loginPerson.email = "email"
loginPerson.save(flush: true, failOnError: true)
}
def cleanup() {
}
void "test correct login"() {
when:
def result = loginService.login(loginPerson.username,loginPerson.password)
then:
assert result == true
}
void "test incorrect login"() {
when:
def result = loginService.login(loginPerson.username,"computer")
then:
assert result == false
}
就身份验证中的事件顺序而言,我不确定我应该做什么。
非常感谢任何帮助。
【问题讨论】:
-
这种方法应该有效,或者应该接近。但是你不能用集成测试来测试它——Spring Security 被实现为一个 servlet 过滤器链,而那些在单元或集成测试中不活跃——请求和响应只是模拟。用功能测试试试吧。
标签: spring authentication grails groovy spring-security