SpringSecurity自定义登录页面和注销时遇到的问题

根据 上一篇 的项目和资源解决Security中自定义登录页面和使用自定义登录页面注销时遇到的问题,视频讲解可关注B站 狂神说Java

目录

  • 自定义登录页面
  • 使用自定义登录页面注销时出现404

自定义登录页面

在我们SecurityConfig类重写的方HttpSecurity法中添加新的方法

//授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
		//开启注销功能,注销成功后访问主页
        http.logout().logoutSuccessUrl("/");
        //开启记住我功能
        http.rememberMe();

        http.formLogin()
                //指定自定义登录页路径
                .loginPage("/toLogin")
                //指定自定义登录页form表单的请求路径
                .loginProcessingUrl("/formLogin");
    }

我们指定的 /toLogin 会来到我们的controller层,进一步去到我们自己的login.html
controller中的toLogin

 @RequestMapping("/toLogin")
    public String toLogin(){
        return "views/login";
  }

login.html中的 form

 <form th:action="@{/formLogin}" method="post">
   <div class="field">
          <label>Username</label>
          <div class="ui left icon input">
              <input type="text" placeholder="Username" name="username">
              <i class="user icon"></i>
          </div>
      </div>
      <div class="field">
          <label>Password</label>
          <div class="ui left icon input">
              <input type="password" name="password">
              <i class="lock icon"></i>
          </div>
      </div>
      <input type="submit" class="ui blue submit button"/>
  </form>

因为SpringSecurity默认为/login路径,我们要使用自己的路径,就需要配置loginProcessingUrl("/formLogin") (与form表单的action路径一致)

另外我们表单中的账户、密码中 name 属性需为 username 和 password 不然我的提交的信息无法通过SpringSecurity验证,若name属性不为是 username 和 password 就需要在http.formLogin() 方法中指定

 http.formLogin()
        //指定登录页路径
         .loginPage("/toLogin")
         //指定自定义form表单的请求路径
         .loginProcessingUrl("/formLogin")
         .usernameParameter("user")	
         .passwordParameter("paw");

这样我们就完成了登录页面的自定义
SpringSecurity自定义登录页面和注销时遇到的问题_第1张图片

使用自定义登录页面注销时出现404

SpringSecurity自定义登录页面和注销时遇到的问题_第2张图片使用自定义登录页面注销时出现404,这是因为SpringBoot默认开启了 CSRF 防止网站攻击

解决方法:将我们的注销请求方式改为 post 请求
                  或者我们可以在 configure(HttpSecurity http)方法中 关闭 csrf(会产生安全隐患)

 http.csrf().disable();

更详细的探究:分享好文章

你可能感兴趣的:(学习总结)