SpringSecurity注销设置的方法

作者:搞钱自律 时间:2023-08-05 20:46:15 

Spring Security中也提供了默认的注销配置,在开发时也可以按照自己需求对注销进行个性化定制

开启注销 默认开启

package com.example.config;

import com.example.handler.MyAuthenticationFailureHandler;
import com.example.handler.MyAuthenticationSuccessHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {

        //【注意事项】放行资源要放在前面,认证的放在后面
        http.authorizeRequests()
                .mvcMatchers("/index").permitAll() //代表放行index的所有请求
                .mvcMatchers("/loginHtml").permitAll() //放行loginHtml请求
                .anyRequest().authenticated()//代表其他请求需要认证
                .and()
                .formLogin()//表示其他需要认证的请求通过表单认证
                //loginPage 一旦你自定义了这个登录页面,那你必须要明确告诉SpringSecurity日后哪个url处理你的登录请求
                .loginPage("/loginHtml")//用来指定自定义登录界面,不使用SpringSecurity默认登录界面  注意:一旦自定义登录页面,必须指定登录url
                //loginProcessingUrl  这个doLogin请求本身是没有的,因为我们只需要明确告诉SpringSecurity,日后只要前端发起的是一个doLogin这样的请求,
                //那SpringSecurity应该把你username和password给捕获到
                .loginProcessingUrl("/doLogin")//指定处理登录的请求url
                .usernameParameter("uname") //指定登录界面用户名文本框的name值,如果没有指定,默认属性名必须为username
                .passwordParameter("passwd")//指定登录界面密码密码框的name值,如果没有指定,默认属性名必须为password
//                .successForwardUrl("/index")//认证成功 forward 跳转路径,forward代表服务器内部的跳转之后,地址栏不变 始终在认证成功之后跳转到指定请求
//                .defaultSuccessUrl("/index")//认证成功 之后跳转,重定向 redirect 跳转后,地址会发生改变  根据上一保存请求进行成功跳转
                .successHandler(new MyAuthenticationSuccessHandler()) //认证成功时处理  前后端分离解决方案
//                .failureForwardUrl("/loginHtml")//认证失败之后 forward 跳转
//                .failureUrl("/login.html")//认证失败之后  redirect 跳转
                .failureHandler(new MyAuthenticationFailureHandler())//用来自定义认证失败之后处理  前后端分离解决方案
                .and()
                .logout()
                .logoutUrl("/logout") //指定注销登录url  默认请求方式必须:GET
                .invalidateHttpSession(true) //会话失效 默认值为true,可不写
                .clearAuthentication(true) //清除认证标记 默认值为true,可不写
                .logoutSuccessUrl("/loginHtml") //注销成功之后跳转页面
                .and()
                .csrf().disable(); //禁止csrf 跨站请求保护
    }
}
  • 通过logout()方法开启注销配置

  • logoutUrl指定退出登录请求地址,默认是GET请求,路径为/logout

  • invalidateHttpSession 退出时是否是session失效,默认值为true

  • clearAuthentication 退出时是否清除认证信息,默认值为true

  • logoutSuccessUrl 退出登录时跳转地址

测试

先访问http://localhost:8080/hello,会自动跳转到http://localhost:8080/loginHtml登录界面,输入用户名和密码,地址栏会变化为:http://localhost:8080/doLogin,然后重新访问http://localhost:8080/hello,此时可以看到hello的数据,表示登录认证成功然后访问http://localhost:8080/logout,会自动跳转到http://localhost:8080/loginHtml登录页面,然后在访问http://localhost:8080/hello,发现会跳转到http://localhost:8080/loginHtml登录界面,表示后端认定你未登录了,需要你登录认证

配置多个注销登录请求

如果项目中也有需要,开发者还可以配置多个注销登录的请求,同时还可以指定请求的方法

新增退出controller

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LogoutController {

    @RequestMapping("/logoutHtml")
    public String logout(){
        return "logout";
    }
}

新增退出界面

logout.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org/" lang="en">
<head>
    <meta charset="UTF-8">
    <title>注销</title>
</head>
<body>
    <h1>注销</h1>
    <form th:action="@{/bb}" method="post">
        <input type="submit" value="注销">
    </form>
</body>
</html>

修改配置信息

package com.example.config;

import com.example.handler.MyAuthenticationFailureHandler;
import com.example.handler.MyAuthenticationSuccessHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {

        //【注意事项】放行资源要放在前面,认证的放在后面
        http.authorizeRequests()
                .mvcMatchers("/index").permitAll() //代表放行index的所有请求
                .mvcMatchers("/loginHtml").permitAll() //放行loginHtml请求
                .anyRequest().authenticated()//代表其他请求需要认证
                .and()
                .formLogin()//表示其他需要认证的请求通过表单认证
                //loginPage 一旦你自定义了这个登录页面,那你必须要明确告诉SpringSecurity日后哪个url处理你的登录请求
                .loginPage("/loginHtml")//用来指定自定义登录界面,不使用SpringSecurity默认登录界面  注意:一旦自定义登录页面,必须指定登录url
                //loginProcessingUrl  这个doLogin请求本身是没有的,因为我们只需要明确告诉SpringSecurity,日后只要前端发起的是一个doLogin这样的请求,
                //那SpringSecurity应该把你username和password给捕获到
                .loginProcessingUrl("/doLogin")//指定处理登录的请求url
                .usernameParameter("uname") //指定登录界面用户名文本框的name值,如果没有指定,默认属性名必须为username
                .passwordParameter("passwd")//指定登录界面密码密码框的name值,如果没有指定,默认属性名必须为password
//                .successForwardUrl("/index")//认证成功 forward 跳转路径,forward代表服务器内部的跳转之后,地址栏不变 始终在认证成功之后跳转到指定请求
//                .defaultSuccessUrl("/index")//认证成功 之后跳转,重定向 redirect 跳转后,地址会发生改变  根据上一保存请求进行成功跳转
                .successHandler(new MyAuthenticationSuccessHandler()) //认证成功时处理  前后端分离解决方案
//                .failureForwardUrl("/loginHtml")//认证失败之后 forward 跳转
//                .failureUrl("/login.html")//认证失败之后  redirect 跳转
                .failureHandler(new MyAuthenticationFailureHandler())//用来自定义认证失败之后处理  前后端分离解决方案
                .and()
                .logout()
//                .logoutUrl("/logout") //指定注销登录url  默认请求方式必须:GET
                .logoutRequestMatcher(new OrRequestMatcher(
                        new AntPathRequestMatcher("/aa","GET"),
                        new AntPathRequestMatcher("/bb","POST")
                        )
                )
                .invalidateHttpSession(true) //会话失效 默认值为true,可不写
                .clearAuthentication(true) //清除认证标记 默认值为true,可不写
                .logoutSuccessUrl("/loginHtml") //注销成功之后跳转页面
                .and()
                .csrf().disable(); //禁止csrf 跨站请求保护
    }
}

测试

GET /aa 跟上面测试方法一样

POST /bb

先访问http://localhost:8080/hello,会自动跳转到http://localhost:8080/loginHtml登录界面,输入用户名和密码,地址栏会变化为:http://localhost:8080/doLogin,然后重新访问http://localhost:8080/hello,此时可以看到hello的数据,表示登录认证成功然后访问http://localhost:8080/logoutHtml,会跳出注销页面,点击&ldquo;注销&rdquo;按钮,会返回到http://localhost:8080/loginHtml登录界面,再重新访问http://localhost:8080/hello,发现会跳转到http://localhost:8080/loginHtml登录界面,表示注销成功,需要重新登录。

前后端分离注销配置

如果是前后端分离开发,注销成功之后就不需要页面跳转了,只需要将注销成功的信息返回前端即可,此时我们可以通过自定义LogoutSuccessHandler实现来返回内容注销之后信息

添加handler

package com.example.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义注销成功之后处理
 */
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        Map<String,Object> result = new HashMap<>();
        result.put("msg","注销成功,当前认证对象为:"+authentication);
        result.put("status",200);
        result.put("authentication",authentication);
        response.setContentType("application/json;charset=UTF-8");
        String s = new ObjectMapper().writeValueAsString(result);
        response.getWriter().println(s);
    }
}

修改配置信息

logoutSuccessHandler

package com.example.config;

import com.example.handler.MyAuthenticationFailureHandler;
import com.example.handler.MyAuthenticationSuccessHandler;
import com.example.handler.MyLogoutSuccessHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {

        //【注意事项】放行资源要放在前面,认证的放在后面
        http.authorizeRequests()
                .mvcMatchers("/index").permitAll() //代表放行index的所有请求
                .mvcMatchers("/loginHtml").permitAll() //放行loginHtml请求
                .anyRequest().authenticated()//代表其他请求需要认证
                .and()
                .formLogin()//表示其他需要认证的请求通过表单认证
                //loginPage 一旦你自定义了这个登录页面,那你必须要明确告诉SpringSecurity日后哪个url处理你的登录请求
                .loginPage("/loginHtml")//用来指定自定义登录界面,不使用SpringSecurity默认登录界面  注意:一旦自定义登录页面,必须指定登录url
                //loginProcessingUrl  这个doLogin请求本身是没有的,因为我们只需要明确告诉SpringSecurity,日后只要前端发起的是一个doLogin这样的请求,
                //那SpringSecurity应该把你username和password给捕获到
                .loginProcessingUrl("/doLogin")//指定处理登录的请求url
                .usernameParameter("uname") //指定登录界面用户名文本框的name值,如果没有指定,默认属性名必须为username
                .passwordParameter("passwd")//指定登录界面密码密码框的name值,如果没有指定,默认属性名必须为password
//                .successForwardUrl("/index")//认证成功 forward 跳转路径,forward代表服务器内部的跳转之后,地址栏不变 始终在认证成功之后跳转到指定请求
//                .defaultSuccessUrl("/index")//认证成功 之后跳转,重定向 redirect 跳转后,地址会发生改变  根据上一保存请求进行成功跳转
                .successHandler(new MyAuthenticationSuccessHandler()) //认证成功时处理  前后端分离解决方案
//                .failureForwardUrl("/loginHtml")//认证失败之后 forward 跳转
//                .failureUrl("/login.html")//认证失败之后  redirect 跳转
                .failureHandler(new MyAuthenticationFailureHandler())//用来自定义认证失败之后处理  前后端分离解决方案
                .and()
                .logout()
//                .logoutUrl("/logout") //指定注销登录url  默认请求方式必须:GET
                .logoutRequestMatcher(new OrRequestMatcher(
                        new AntPathRequestMatcher("/aa","GET"),
                        new AntPathRequestMatcher("/bb","POST")
                        )
                )
                .invalidateHttpSession(true) //会话失效 默认值为true,可不写
                .clearAuthentication(true) //清除认证标记 默认值为true,可不写
//                .logoutSuccessUrl("/loginHtml") //注销成功之后跳转页面
                .logoutSuccessHandler(new MyLogoutSuccessHandler()) //注销成功之后处理  前后端分离解决方案
                .and()
                .csrf().disable(); //禁止csrf 跨站请求保护
    }
}

测试

跟第一个测试方法是一样的

SpringSecurity注销设置的方法

来源:https://blog.csdn.net/weixin_43472934/article/details/124566778

标签:SpringSecurity,注销
0
投稿

猜你喜欢

  • 使用EasyPoi轻松导入导出Excel文档的方法示例

    2023-12-26 11:47:56
  • Java8实现对List<Integer>的求和

    2023-12-08 07:03:51
  • Android编程下拉菜单spinner用法小结(附2则示例)

    2022-11-02 20:25:45
  • Java注解@Transactional事务类内调用不生效问题及解决办法

    2022-04-03 18:42:06
  • C# Linq延迟查询的执行实例代码

    2023-04-24 05:34:59
  • java生成图片验证码功能

    2023-06-27 00:31:55
  • C#中使用UDP通信的示例

    2022-11-19 21:09:07
  • C#利用ZXing.Net生成条形码和二维码

    2023-11-04 00:36:02
  • 5分钟快速实现Android爆炸破碎酷炫动画特效的示例

    2022-11-27 11:46:54
  • Springboot WebJar打包及使用实现流程解析

    2023-06-21 22:08:00
  • 关于mybatis遇到Integer类型的参数时动态sql需要注意条件

    2021-10-13 04:59:39
  • springboot集成spring cache缓存示例代码

    2021-10-20 07:57:54
  • Android实现腾讯新闻的新闻类别导航效果

    2023-07-29 04:17:46
  • 详解Android如何实现阴影效果

    2022-04-14 13:11:16
  • Zookeeper事务日志预分配空间解读

    2022-03-16 22:36:49
  • ReactNative Alert详解及实例代码

    2022-07-04 15:02:46
  • C#通过WIN32 API实现嵌入程序窗体

    2021-08-13 04:53:10
  • Android多线程学习实例详解

    2022-02-17 19:00:56
  • 详解JVM之运行时常量池

    2022-08-04 03:41:03
  • Java如何实现单链表的增删改查

    2021-09-19 09:49:25
  • asp之家 软件编程 m.aspxhome.com