[英]Invalidate session (logout) in Spring Boot MVC app
我正在嘗試在Spring MVC
中登錄和注銷的最簡單方法。 我是 .NET 人,當我記得我立即在ASP.NET
中實現了會話身份驗證。 現在,我必須使用Spring MVC
,我面臨的問題是我在logout
方法中獲得了不同的會話對象,因此我無法對其進行無效化。 我在login
方法中創建 session 屬性,我使用邏輯的地方在我的ProductsController
。 這是代碼:
登錄方式:
@PostMapping
@RequestMapping(value = {"login"},method = RequestMethod.POST)
public ResponseEntity Login(@RequestBody @Valid LoginModel user, HttpServletRequest request,HttpSession session){
List<User> userFromDb=service.findByEmailAndPassword(user.getEmail(),user.getPassword());
if(!userFromDb.isEmpty()){
session.setAttribute("loggedInUser", user );
return new ResponseEntity(HttpStatus.OK);
}
return new ResponseEntity(HttpStatus.UNAUTHORIZED);
}
登出方法:
@GetMapping
@RequestMapping(value = {"logout"},method = RequestMethod.GET)
public ResponseEntity Logout(HttpServletRequest request, SessionStatus
status,HttpSession session, HttpServletResponse response){
session.invalidate();
// request.getSession(true).removeAttribute("loggedInUser");
//
// request.getSession(true).invalidate();
Cookie[] cookies = request.getCookies();
if(cookies!=null) {
for (Cookie cookie : cookies) {
cookie.setMaxAge(0);
cookie.setValue(null);
cookie.setPath("/");
response.addCookie(cookie);
}
}
return new ResponseEntity(HttpStatus.OK);
}
產品控制器:
RequestMapping(value = {"","/"},method = RequestMethod.GET)
@GetMapping
public ResponseEntity Products(HttpServletRequest request, HttpSession session){
if(session==null || session.getAttribute("loggedInUser")==null){
return new ResponseEntity(HttpStatus.UNAUTHORIZED);
}
List<Product> products= service.getAll();
return new ResponseEntity(products,HttpStatus.OK);
}
我可以登錄並且用戶保存在會話中。 但是,當我注銷時,我仍然可以訪問我的產品頁面,這意味着該會話沒有被清除。
如果這很重要,我將在端口localhost:3000
上使用create-react-app
前端在 craeted 上使用 react app,而我的服務器在localhost:8080
。
在WebSecurityConfigurerAdapter
配置類(實現)中使用 spring 安全約束和注銷配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
.
...
...
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/login*").permitAll()
.anyRequest().authenticated()
.anyRequest().authenticated()
....
.
.
.and()
.logout()
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
}
...
...
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.