【问题标题】:Grails Spring-Security ConfustionGrails Spring-Security 混乱
【发布时间】: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()
  }
  }

我的错误想法是 UserDetailsS​​ervice 从数据库中加载一个与相关用户名有关的对象。身份验证对象是我想使用的关于该 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


【解决方案1】:
  • 如果您想手动登录用户,请将您的登录服务方法更改为使用 authenticationManager:

class LoginService {
    def authenticationManager

    def login(String username, String password ) {
        Authentication preAuthentication = new UsernamePasswordAuthenticationToken(username, password)
        def authentication = authenticationManager.authenticate(preAuthentication)
        SecurityContextHolder.getContext().setAuthentication(authentication)
        authentication.isAuthenticated()
    }
}
  • 在您的集成测试“测试正确登录”中,传递字符串“密码”而不是 loginPerson.password(以防您的密码被加密)

  • 在“测试不正确登录”中,将 'assert result == false' 替换为 'thrown(BadCredentialsException)'(此处实际预计会出现异常)

【讨论】:

    猜你喜欢
    • 2017-05-22
    • 2019-05-09
    • 2012-02-19
    • 2012-09-09
    • 1970-01-01
    • 2016-05-24
    • 2015-10-20
    • 1970-01-01
    • 2015-05-04
    相关资源
    最近更新 更多