无法使用 spring 安全性 5 注销

Cannot logout using spring security 5

我想为图书管理构建管理门户(获取、添加、删除、更新图书)。所以我从 login/logout 功能开始;登录部分就像一个魅力,但我面临注销问题。当我注销时,管理门户使会话保持活动状态并且不会终止它,并且我在日志中找不到任何错误来证明我这个问题。

下面是响应 post 注销请求的一段代码:

@RequestMapping(value = "/user/logout", method = RequestMethod.POST)
    public ResponseEntity logout(HttpServletRequest request, HttpServletResponse response) {
        SecurityContextHolder.clearContext();

        return new ResponseEntity("Logout Successful !", HttpStatus.OK);
    }

在客户端中,我使用 Angular 发送 post 请求到本地 server.Below 注销服务:

logout(){
    let url="http://localhost:8090/user/logout";
    const xToken = localStorage.getItem('xAuthToken');
    let headers=new Headers({
      'x-auth-token':xToken,
    });

    return this.http.post(url,{headers:headers});
  }

xToken 变量从本地浏览器存储中获取会话的令牌。

每次我们在登录组件的 ngOnInit 中检查会话是否保持活动状态:

ngOnInit() {
    this.login.checkSession().subscribe(
      res=>{
        this.loggedIn=true;
      },
      err=>{
        console.log(err);
        this.loggedIn=false;
      }
    )
  }

负责session校验的服务详述如下:

checkSession(){
    let url="http://localhost:8090/checkSession";
    const xToken = localStorage.getItem('xAuthToken');
    const basicHeader = 'Basic ' + localStorage.getItem('credentials');
    let headers=new Headers({
      'x-auth-token':xToken,
      'Authorization':basicHeader
    });

    return this.http.get(url,{headers:headers});
  }

为了检查会话,我们请求服务器:

@RequestMapping("/checkSession")
    public ResponseEntity checkSession() {
        System.out.print("Session Active !");
        return new ResponseEntity("Session Active !", HttpStatus.OK);
    }

basicHeader 常量是一种身份验证方案,其中包含存储在浏览器本地存储中的编码 username/password 组合。

有关我们如何向服务器发送凭据的更多信息:

onSubmit(){
    this.login.sendCredentials(this.credentials.username,this.credentials.password).subscribe(
        res=>{
          console.log(res);
          localStorage.setItem('xAuthToken', res.json().token);
          this.loggedIn=true;
          const encodedCredentials = btoa(this.credentials.username + ':' + this.credentials.password);
          localStorage.setItem("credentials",encodedCredentials);
          location.reload();
        },err=>{
          console.log(err);
        }
    )
  }

非常感谢您的帮助。预先感谢您解决此问题

开箱即用的 Spring 安全性支持 logout 功能,它只需要一些配置:

@EnableWebSecurity
@Configuration
public class SecurityConf extends WebSecurityConfigurerAdapter {

   @Override
   public void configure(HttpSecurity http) {

       http
           .httpBasic().and() // HTTP Basic authorization or whichever
           .authorizeRequests()
           .antMatchers(...).permitAll()
           .anyRequest().authenticated().and()
           ...
           .logout();
   }

   ...
}

然后可以通过 POST 方法在 http://localhost:8080/logout 访问 /logout 方法,假设您的应用程序是通过 8080 端口在 localhost 上启动的。

更多详情Spring Security doc