【问题标题】:Spring Security doesn't save authenticationSpring Security 不保存身份验证
【发布时间】:2016-06-18 16:59:23
【问题描述】:

我遇到以下问题: 我想访问SecurityContextHolder.getContext().getAuthentication中的Authentication对象

我用来保存用户身份验证的代码如下; SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(username, password));

我的使用方法如下;

我使用localhost:8080/api/login/<username>/<password>发送请求

之后我想使用localhost:8080/api/messages检索登录用户的消息列表

当我打印出 Authentication 对象时,它总是返回一个匿名用户,尽管我在我的登录方法中设置了 Authentication 对象。

【问题讨论】:

  • 您是否在同一个线程中设置和获取身份验证? SecurityContextHolder “将给定的 SecurityContext 与当前执行线程相关联”
  • 不,我不是,但 Spring Security 不应该保存登录的人吗?否则,每次有人提出请求时,我都需要对用户进行身份验证。
  • 是的,但是 Spring Security 应该自动执行此操作,而无需您手动注册 AuthenticationToken。我建议您查看一些在线教程。
  • 我正在使用使用 RestController 的自定义登录方法。那么本地的做法是什么?

标签: spring-mvc authentication spring-security spring-restcontroller


【解决方案1】:

如果您想手动验证用户,如下所示:

创建令牌:

Authentication authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());

验证:

SecurityContextHolder.getContext().setAuthentication(authentication);

【讨论】:

  • 我已经在使用它了,当我尝试检索身份验证时,它返回一个匿名用户(当我进行另一个 REST 调用时)
猜你喜欢
  • 2018-11-23
  • 2022-01-15
  • 2014-02-26
  • 2011-11-14
  • 2014-02-01
  • 2017-03-08
  • 2013-01-15
  • 2019-08-25
  • 2013-10-30
相关资源
最近更新 更多