springSecurityService.isLoggedIn()在@MessageMapping函数内部返回fals



我正在尝试一个简单的聊天,需要用户登录才能使用。我已经完成了登录,可以在控制器中使用springSecurityService.isLoggedIn((检测它。但是,当在聊天处理程序中调用该函数时,它总是返回false。有问题的功能:

@MessageMapping("/sendchat")
@SendTo("/topic/chats")
protected String sendchat(String getrequest) {
log.info "nnpre login"
if(springSecurityService.isLoggedIn())
{
log.info "nn"+getrequest
//do other things if successful
}
else
{
log.info "nnnot logged in"
}
}

它将始终执行else语句,即使控制器的index((函数已正确检测到用户已登录。

这是因为"springSecurityService"仅适用于Controller操作方法,"spring-security核心插件"使用过滤器来设置安全上下文,然后springSecurityServices可以检索用户登录状态。

而在你的代码中,该方法是"受保护的",它是一个"websocket-plugin"约定,所以你应该根据插件文档进行安全保护,比如:

class ExampleController {
@ControllerMethod
@MessageMapping("/hello")
@PreAuthorize("hasRole('ROLE_USER')")
@SendTo("/topic/hello")
String hello(String world) {
return "hello from secured controller, ${world}!"
}
@ControllerMethod
@MessageExceptionHandler
@SendToUser(value = "/queue/errors", broadcast = false)
String handleException(Exception e) {
return "caught ${e.message}"
}
}

更多细节可参考"https://github.com/zyro23/grails-spring-websocket#securing-消息处理程序方法"。

最新更新