Java17 --- SpringSecurity之前后端分离处理

目录

一、实现前后端分离

1.1、导入pom依赖

1.2、认证成功处理

1.3、认证失败处理

1.4、用户注销处理

1.5、请求未认证处理

1.6、跨域处理

1.7、用户认证信息处理

1.8、会话并发处理


一、实现前后端分离

1.1、导入pom依赖

XML 复制代码
<dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.40</version>
        </dependency>

1.2、认证成功处理

java 复制代码
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获取用户身份信息
        Object principal = authentication.getPrincipal();
        HashMap map = new HashMap<>();
        map.put("code",200);
        map.put("message","登录成功");
        map.put("data",principal);
        //将信息json化
        String jsonString = JSON.toJSONString(map);
        //返回json数据到前端
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(jsonString);
    }
}
java 复制代码
@Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests(
                authorize -> authorize
                        .anyRequest() //对所有请求开启授权保护
                        .authenticated() //已认证的请求会自动授权
               )
                .formLogin(
                        //Customizer.withDefaults()
                        form -> form.loginPage("/login")
                                .permitAll()//无需授权就能访问
                                .usernameParameter("name")
                                .passwordParameter("pass")
                                .successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理
                );//使用表单授权方式
                //.httpBasic(Customizer.withDefaults());//使用基本授权方式
        httpSecurity.csrf(csrf -> csrf.disable());//关闭csrf功能
        return httpSecurity.build();
    }

1.3、认证失败处理

java 复制代码
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        String localizedMessage = exception.getLocalizedMessage();
        HashMap map = new HashMap<>();
        map.put("code",400);
        map.put("message",localizedMessage);
        //将信息json化
        String jsonString = JSON.toJSONString(map);
        //返回json数据到前端
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(jsonString);
    }
}
java 复制代码
@Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests(
                authorize -> authorize
                        .anyRequest() //对所有请求开启授权保护
                        .authenticated() //已认证的请求会自动授权
               )
                .formLogin(
                        //Customizer.withDefaults()
                        form -> form.loginPage("/login")
                                .permitAll()//无需授权就能访问
                                .usernameParameter("name")
                                .passwordParameter("pass")
                                .successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理
                                .failureHandler(new MyAuthenticationFailureHandler())//认证失败的处理
                );//使用表单授权方式
                //.httpBasic(Customizer.withDefaults());//使用基本授权方式
        httpSecurity.csrf(csrf -> csrf.disable());//关闭csrf功能
        return httpSecurity.build();
    }

1.4、用户注销处理

java 复制代码
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        HashMap map = new HashMap<>();
        map.put("code",200);
        map.put("message","注销成功");
        //将信息json化
        String jsonString = JSON.toJSONString(map);
        //返回json数据到前端
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(jsonString);
    }
}
java 复制代码
@Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests(
                authorize -> authorize
                        .anyRequest() //对所有请求开启授权保护
                        .authenticated() //已认证的请求会自动授权
        );
        httpSecurity.formLogin(
                        //Customizer.withDefaults()//使用表单授权方式
                       //.httpBasic(Customizer.withDefaults());//使用基本授权方式
                form -> form.loginPage("/login")
                        .permitAll()//无需授权就能访问
                        .usernameParameter("name")
                        .passwordParameter("pass")
                        .successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理
                        .failureHandler(new MyAuthenticationFailureHandler())//认证失败的处理
        );
        httpSecurity.logout(logout ->
                logout.logoutSuccessHandler(new MyLogoutSuccessHandler())//用户注销成功处理
        );

        httpSecurity.csrf(
                csrf -> csrf
                        .disable()
        );//关闭csrf功能
        return httpSecurity.build();
    }

1.5、请求未认证处理

java 复制代码
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        String localizedMessage = authException.getLocalizedMessage();
        HashMap map = new HashMap<>();
        map.put("code",400);
        map.put("message",localizedMessage);
        //将信息json化
        String jsonString = JSON.toJSONString(map);
        //返回json数据到前端
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(jsonString);
    }
}
java 复制代码
@Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests(
                authorize -> authorize
                        .anyRequest() //对所有请求开启授权保护
                        .authenticated() //已认证的请求会自动授权
        );
        httpSecurity.formLogin(
                        //Customizer.withDefaults()//使用表单授权方式
                       //.httpBasic(Customizer.withDefaults());//使用基本授权方式
                form -> form.loginPage("/login")
                        .permitAll()//无需授权就能访问
                        .usernameParameter("name")
                        .passwordParameter("pass")
                        .successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理
                        .failureHandler(new MyAuthenticationFailureHandler())//认证失败的处理
        );
        httpSecurity.logout(logout ->
                logout.logoutSuccessHandler(new MyLogoutSuccessHandler())//用户注销成功处理
        );
        httpSecurity.exceptionHandling(exception ->
                exception.authenticationEntryPoint(new MyAuthenticationEntryPoint()));//请求未认证处理
        httpSecurity.csrf(
                csrf -> csrf.disable()
        );//关闭csrf功能
        return httpSecurity.build();
    }

1.6、跨域处理

java 复制代码
httpSecurity.cors(Customizer.withDefaults());//跨域处理

1.7、用户认证信息处理

java 复制代码
@RestController
public class IndexController {
    @GetMapping("/")
    public Map index(){
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        Object principal = authentication.getPrincipal();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        HashMap map = new HashMap<>();
        map.put("principal",principal);
        map.put("权限",authorities);
        return map;
    }
}

1.8、会话并发处理

java 复制代码
public class MySessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {

        HashMap map = new HashMap<>();
        map.put("code",400);
        map.put("message","账号已在其他地方登录");
        //将信息json化
        String jsonString = JSON.toJSONString(map);
        HttpServletResponse response = event.getResponse();
        //返回json数据到前端
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(jsonString);
    }
}
java 复制代码
 @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.sessionManagement(session ->
                session.maximumSessions(1)
                        .expiredSessionStrategy(new MySessionInformationExpiredStrategy())
        );//会话并发处理
        httpSecurity.cors(Customizer.withDefaults());//跨域处理
        httpSecurity.authorizeRequests(
                authorize -> authorize
                        .anyRequest() //对所有请求开启授权保护
                        .authenticated() //已认证的请求会自动授权
        );
        httpSecurity.formLogin(
                        //Customizer.withDefaults()//使用表单授权方式
                       //.httpBasic(Customizer.withDefaults());//使用基本授权方式
                form -> form.loginPage("/login")
                        .permitAll()//无需授权就能访问
                        .usernameParameter("name")
                        .passwordParameter("pass")
                        .successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理
                        .failureHandler(new MyAuthenticationFailureHandler())//认证失败的处理
        );
        httpSecurity.logout(logout ->
                logout.logoutSuccessHandler(new MyLogoutSuccessHandler())//用户注销成功处理
        );
        httpSecurity.exceptionHandling(exception ->
                exception.authenticationEntryPoint(new MyAuthenticationEntryPoint()));//请求未认证处理
        httpSecurity.csrf(
                csrf -> csrf.disable()
        );//关闭csrf功能
        return httpSecurity.build();
    }
相关推荐
豆豆15 分钟前
为什么用PageAdmin CMS建设网站?
服务器·开发语言·前端·php·软件构建
2401_8576176221 分钟前
SpringBoot校园资料平台:开发与部署指南
java·spring boot·后端
quokka5624 分钟前
Springboot 整合 logback 日志框架
java·spring boot·logback
计算机学姐30 分钟前
基于SpringBoot+Vue的在线投票系统
java·vue.js·spring boot·后端·学习·intellij-idea·mybatis
救救孩子把1 小时前
深入理解 Java 对象的内存布局
java
DY009J1 小时前
深度探索Kali Linux的精髓与实践应用
linux·运维·服务器
落落落sss1 小时前
MybatisPlus
android·java·开发语言·spring·tomcat·rabbitmq·mybatis
万物皆字节1 小时前
maven指定模块快速打包idea插件Quick Maven Package
java
夜雨翦春韭1 小时前
【代码随想录Day30】贪心算法Part04
java·数据结构·算法·leetcode·贪心算法
我行我素,向往自由1 小时前
速成java记录(上)
java·速成