SpringSecurity注销设置的方法

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,会跳出注销页面,点击“注销”按钮,会返回到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 跨站请求保护
    }
}

测试

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • 基于spring security实现登录注销功能过程解析

    这篇文章主要介绍了基于spring security实现登录注销功能过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.引入maven依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependenc

  • Spring Cloud下OAUTH2注销的实现示例

    接上文Spring Cloud下基于OAUTH2认证授权的实现,我们将基于Spring Cloud实现OAUTH2的注销功能. 1 增加自定义注销Endpoint 所谓注销只需将access_token和refresh_token失效即可,我们模仿org.springframework.security.oauth2.provider.endpoint.TokenEndpoint写一个使access_token和refresh_token失效的Endpoint: @FrameworkEndpoi

  • 详解springboot springsecuroty中的注销和权限控制问题

    目录 1账户注销 1.1在SecurityConfig中加入开启注销功能的代码 1.2在index.html添加注销的按钮 1.3启动项目测试 2权限控制 2.1导入springsecurity和thymeleaf的整合依赖 2.2springboot版本降级 2.3引入约束 2.4修改页面代码 2.5重启程序测试 承接:springboot-springsecuroty:用户认证和授权 1 账户注销 1.1 在SecurityConfig中加入开启注销功能的代码 src/main/java/c

  • SpringBoot使用Spring Security实现登录注销功能

    1.首先看下我的项目结构 我们逐个讲解 /** * 用户登录配置类 * @author Administrator * */ public class AdminUserDateils implements UserDetails { private static final long serialVersionUID = -1546619839676530441L; private transient YCAdmin yCAdmin; public AdminUserDateils() { }

  • Java Spring Security认证与授权及注销和权限控制篇综合解析

    Spring Security简介: Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,它可以实现强大的Web安全控制,对于安全控制,我们只需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理! 记住几个类: WebSecurityConfigurerAdapter:自定义Security策略 AuthenticationManagerBuilder:自定义认证策略

  • SpringBoot--- SpringSecurity进行注销权限控制的配置方法

    环境 IDEA :2020.1 Maven:3.5.6 SpringBoot: 2.0.9 (与此前整合的版本2.3.3 不同,版本适配问题,为配合使用降级) 1.注销 这里也有一个前提问题需要注意,我们登录操作都是在开启防跨域攻击的环境下进行的. 毫无疑问,注销也是在这样的情况下进行的. 登录时我们提交表单,采用 POST 方法传输,通过使用 Thymeleaf 在 form 表单添加 th:action 元素,Thymeleaf 会自动为我们添加 _csrf 元素. 同样注销操作也是要带有

  • SpringSecurity注销设置的方法

    Spring Security中也提供了默认的注销配置,在开发时也可以按照自己需求对注销进行个性化定制 开启注销 默认开启 package com.example.config; import com.example.handler.MyAuthenticationFailureHandler; import com.example.handler.MyAuthenticationSuccessHandler; import org.springframework.context.annotat

  • JavaScript 控制字体大小设置的方法

    在做公司的官网的时候,新闻内页会有一个让浏览者自己调整文字大小的功能,因此在这个空闲时间,把这个功能整理下来: function setFontSize (id,content,params){ var oTarget = document.getElementById(id), content = document.getElementById(content), size = params.size || 14, maxSize = params.maxSize || 20, step =

  • PHP中设置时区方法小结

    找到原因后,在网上搜索到了一些关于PHP的时区设置方法: 1.修改php.ini,在php.ini中找到data.timezone =去掉它前面的;号,然后设置data.timezone = "Asia/Shanghai";即可. 2.在程序PHP 5以上版本的程序代码中使用函数ini_set('date.timezone','Asia/Shanghai');或者date_default_timezone_set('Asia/Shanghai'); 一些常用的时区标识符说明: Asia

  • Android实现手机振动设置的方法

    本文实例讲述了Android实现手机振动设置的方法.分享给大家供大家参考.具体如下: main.xml布局文件: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" androi

  • 跨浏览器的设置innerHTML方法

    Ajax是个好东西,但使用起来却不是那么方便.问题总结如下: 在各种浏览器上的创建方式和使用方法不一致  各个浏览器对响应的缓存策略有所不同  浏览器存在跨域获取限制  前两个问题可以通过封装 XMLHTTPRequest 对象来解决,第三个问题的解决方法有很多中,兼容性和移植性比较好的就是在本域服务器上放置一个中转 proxy .Modello.ajax 就是提供这套解决方案的工具集. 安装 下载 Modello 和 Mdello.ajax  解压并将 modello.js, modello.

  • Android编程实现TextView字体颜色设置的方法小结

    本文实例讲述了Android编程实现TextView字体颜色设置的方法.分享给大家供大家参考,具体如下: 对于setTextView(int a)这里的a是传进去颜色的值.例如,红色0xff0000是指0xff0000如何直接传入R.color.red是没有办法设置颜色的,只有通过文章中的第三种方法先拿到资源的颜色值再传进去. 复制代码 代码如下: tv.setTextColor(this.getResources().getColor(R.color.red)); 关键字: android t

  • 通过js动态创建标签,并设置属性方法

    当我们在写jsp页面时,往往会遇到这种情况:从后台获取的数据个数不确定,此时在前端写jsp页面时也就不确定怎么设计了.这个时候就需要通过js动态创建标签: 1.创建某个标签:如下在body中创建一个div的事例: <script> function fun(){ var frameDiv = document.createElement("div");//创建一个标签 var bodyFa = document.getElementById("bodyid&quo

  • Python3 关于pycharm自动导入包快捷设置的方法

    正常开发的时候,我们都手动去写要引入到包,有过java开发的同事,用过快捷键ctrl + alt + o 会自动引入所有的依赖包,pycharm也有这样的设置,看看怎么设置吧. 设置快捷键,默认ctrl + 空格,win的用户会和切换中文快捷键冲突,这里我设置的shift +1 用的时候,shift + 1 ,按两下1看看效果. 以上这篇Python3 关于pycharm自动导入包快捷设置的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

  • pycharm重置设置,恢复默认设置的方法

    window 系统 找到下方目录-->删除. 再重新打开pycharm # Windows Vista, 7, 8, 10: <SYSTEM DRIVE>\Users\<USER ACCOUNT NAME>\.<PRODUCT><VERSION> 例:C:\Users\Administrator\.PyCharm2018.1 # Windows XP: <SYSTEM DRIVE>\Documents and Settings\<US

  • Layui 导航默认展开和菜单栏选中高亮设置的方法

    如下所示: <ul class="layui-nav layui-nav-tree custom-nav-tree" lay-filter="kitNavbar" kit-navbar> <c:if test="${title_sys eq '内容管理' }"> <li class="layui-nav-item index1 layui-nav-itemed"><a href=&qu

随机推荐