亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使 Spring Boot MVC 應用程序中的會話(注銷)無效

使 Spring Boot MVC 應用程序中的會話(注銷)無效

搖曳的薔薇 2023-05-10 13:29:49
我正在嘗試最簡單的登錄和注銷方式Spring MVC。我是 .NET 專家,當我記得我ASP.NET很快就實現了會話身份驗證?,F在,我必須使用Spring MVC,我面臨的問題是我在我的logout方法中得到了不同的會話對象,所以我不能取消它。我在login方法中創建會話屬性,我使用邏輯的地方在我的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);    }我可以登錄并且用戶保存在會話中。但是,當我注銷時,我仍然可以訪問我的產品頁面,這意味著該會話未被清除。如果那很重要,我正在使用create-react-app端口上的前端在 craeted 上使用 React 應用程序localhost:3000,并且我的服務器已打開localhost:8080。
查看完整描述

1 回答

?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

在您的配置類(實現)中使用 spring 安全約束和注銷配置WebSecurityConfigurerAdapter:


@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")


    }

    ...

    ...

    ...    

}


查看完整回答
反對 回復 2023-05-10
  • 1 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號