我想建立用于图书管理(获取,添加,删除,更新图书)的管理门户。因此,我从登录/注销功能开始;登录部分的工作原理很吸引人,但我面临注销问题。当我注销时,管理门户使会话保持活动状态,并且不会终止该会话,并且我在日志中无法获得任何证明我这个问题的错误。
下面的代码可以响应注销请求:
@RequestMapping(value = "/user/logout", method = RequestMethod.POST)
public ResponseEntity logout(HttpServletRequest request, HttpServletResponse response) {
SecurityContextHolder.clearContext();
return new ResponseEntity("Logout Successful !", HttpStatus.OK);
}
在客户端中,我使用Angular向我的本地服务器发送发布请求。在注销服务下方:
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;
}
)
}
负责会话检查的服务如下:
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 常数是一种身份验证方案,其中包含存储在浏览器本地存储中的编码的用户名/密码组合。
有关我们如何将凭据发送到服务器的以下其他信息:
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);
}
)
}
请给予任何帮助,我们将不胜感激。预先感谢您解决此问题
答案 0 :(得分:1)
Spring Security开箱即用地支持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();
}
...
}
假设您的应用是通过/logout
端口在http://localhost:8080/logout
上启动的,然后可以通过POST
方法在localhost
上访问8080
方法。
有关更多详细信息,Spring Security doc