1. 程式人生 > >Springboot整合Security設定defaultSuccessUrl()不起作用問題

Springboot整合Security設定defaultSuccessUrl()不起作用問題

一直做移動端,想學一下Web,然後選擇了Springboot!

這2天學習如何使用Security,遇到了一個坑,坑了我2天,跟題目一樣,defaultSuccessUrl()無論怎麼設定都不起作用,登入成功後都會跳轉到"/",如果沒有“/”路由就會提示404找不到路徑。

這個是如題描述錯誤的程式碼:

http.formLogin()
        .loginPage("/admin/login").permitAll()
        .failureUrl("/admin/login?error")
        .defaultSuccessUrl("/admin/index")
        .successHandler(new 
LoginSuccessHandler())
.and() .authorizeRequests() .anyRequest().authenticated() .and() .csrf().requireCsrfProtectionMatcher(csrfSecurityRequestMatcher()) .and() .logout().permitAll();

注意上面紅色的2行程式碼!

解決:

調整一下

successHandler(new LoginSuccessHandler())
的位置,如下:
http.formLogin()
        .successHandler(new LoginSuccessHandler())
        .loginPage("/admin/login").permitAll()
        .failureUrl("/admin/login?error")
        .defaultSuccessUrl("/admin/index")
        .and()
        .authorizeRequests()
        .anyRequest().authenticated()
        .and()
        .csrf().requireCsrfProtectionMatcher(csrfSecurityRequestMatcher())
        .and()
        .logout().permitAll();
最後重啟專案,就算使用devtools也要重啟。