SpringSecurity基本配置

在com.example下新建包config

config包中新建java类SecurityConfiguration

@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
            return http
                    .authorizeHttpRequests(conf->conf
                            .requestMatchers(("/api/auth/**")).permitAll()
                            .anyRequest().authenticated())
                    .formLogin(conf->conf
                            .loginProcessingUrl("/api/auth/login")
                            .failureHandler(this::onAuthenticationFailure)
                            .successHandler(this::onAuthenticationSuccess))
                    .logout(conf->conf
                            .logoutUrl("/api/auth/logout")
                            .logoutSuccessHandler(this::onLogoutSuccess))
                    .csrf(AbstractHttpConfigurer::disable)
                    .sessionManagement(conf->conf
                            .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                    .build();
    }
  1. SecurityFilterChain Bean:这个 Bean 配置了一系列的安全过滤器链,用于处理不同类型的请求。它定义了请求授权、登录、注销、CSRF 防护和会话管理等规则。

  2. authorizeHttpRequests 方法:这里配置了请求的授权规则。/api/auth/** 路径的请求被允许,而其他请求需要进行身份验证(authenticated)。

  3. formLogin 方法:这里配置了表单登录的相关设置。loginProcessingUrl 定义了登录请求的 URL,failureHandlersuccessHandler 定义了登录失败和成功的处理器。

  4. logout 方法:这里配置了注销相关的设置。logoutUrl 定义了注销请求的 URL,logoutSuccessHandler 定义了注销成功的处理器。

  5. csrf 方法:通过 AbstractHttpConfigurer::disable 禁用了 CSRF(跨站请求伪造)防护。

  6. sessionManagement 方法:这里配置了会话管理策略,将会话策略设置为 STATELESS,表示无状态的会话管理,通常用于 RESTful API,不保存会话状态。


在所有的config类上要添加@Configuration注解,由于忘记添加导致了大量的报错难以排查。

显然,我们不能将字符串直接返回给前端,因此编写类返回json格式进行交互,在entity包下编写RestBean:

package com.example.entity;

import com.alibaba.fastjson2.*;

public record RestBean<T>(int code, T data, String message) {


    public static <T> RestBean<T> success(T data) {
        return new RestBean<>(200, data, "Success");
    }

    public static <T> RestBean<T> success() {
        return success(null);
    }

    public String asJsonString() {
        return  JSONObject.toJSONString(this,JSONWriter.Feature.WriteNulls);
    }


}

import com.alibaba.fastjson2.*;此处导包如果仅仅导入JSONObject和JSON会报找不到toJSONString的错误,原因未知

登陆后对应的处理方法:

public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
这里返回的是json
        response.getWriter().write(RestBean.success().asJsonString());
        System.out.println(RestBean.success().asJsonString());
    }


    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        response.getWriter().write("Failed");
        System.out.println("failed");

    }

    public void onLogoutSuccess(HttpServletRequest request,
                                HttpServletResponse response,
                                Authentication authentication) throws IOException, ServletException {


    }

此时如果返回信息中包含中文,会导致乱码,需要对编码格式进行更改:

        response.setContentType("application/json;charset=utf-8");

对请求失败进行同样的设置:

 public static <T> RestBean<T> failure(int code,String message) {
        return new RestBean<>(code ,null,message);
    }
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(RestBean.failure(401,exception.getMessage()).asJsonString());
        System.out.println("failed");

    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

湿物男

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值