一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

SpringSecurity注销设置代码方法

时间:2022-09-06 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下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




    
    注销


    

注销

修改配置信息

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 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 跨站请求保护
    }
}

测试

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

热门栏目