【问题标题】:Can't use Spring security /logout resource [closed]无法使用 Spring 安全/注销资源 [关闭]
【发布时间】:2021-03-16 16:47:51
【问题描述】:

我有一个 Spring Security 应用程序。当我尝试通过我的 Angular 前端注销时,我会收到 404(未找到)。

我已经尝试了许多 spring WebSecurityConfigurerAdapter 配置,但我得到了一个 404。我正在使用 POST 来提出我的请求。(见下文)

logout() {
    this.http.post('/logout', "").pipe(
      finalize(() => {
        this.app.authenticated.next(false);
      })
    ).subscribe();
  }

使用 Postman,我在尝试访问资源时收到 403(禁止)

【问题讨论】:

  • 请贴出导致错误的代码
  • 显示你的 Spring Security 配置。

标签: angular spring spring-security angular-httpclient


【解决方案1】:

其实你需要的只是添加一个注销成功处理程序

  @Component
public class LogoutSuccess implements LogoutSuccessHandler {

@Override
public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication)
        throws IOException, ServletException {
    if (authentication != null && authentication.getDetails() != null) {
        try {
            httpServletRequest.getSession().invalidate();
            // you can add more codes here when the user successfully logs
            // out,
            // such as updating the database for last active.
        } catch (Exception e) {
            e.printStackTrace();
            e = null;
        }
    }

    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

}

}

并将成功处理程序添加到您的安全配置中

http.authorizeRequests().anyRequest().authenticated().and().logout().logoutSuccessHandler(logoutSuccess).deleteCookies("JSESSIONID").invalidateHttpSession(false).permitAll();

或者你也可以试试这个:

 logout() {
    this.http.post('/logout').pipe(
      finalize(() => {
        this.app.authenticated.next(false);
      })
    ).subscribe();
  }

【讨论】:

  • 如果答案解决了您的问题,请投票。谢谢!
猜你喜欢
  • 2012-12-04
  • 1970-01-01
  • 2014-08-23
  • 2013-11-21
  • 2015-06-14
  • 1970-01-01
  • 2015-10-05
  • 2014-05-01
  • 2023-04-05
相关资源
最近更新 更多