spring security权限校验失败处理器和认证失败处理器怎么写

权限校验失败处理器

package com.lzy.security;

import cn.hutool.json.JSONUtil;
import com.lzy.common.lang.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 将响应的内容类型设置为JSON
        response.setContentType("application/json;charset=utf-8");
        // 设置响应状态码为403(Forbidden)权限不足
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        // 获取响应的输出流
        ServletOutputStream out = response.getOutputStream();
        // 创建一个包含异常消息的Result对象
        Result result = Result.fail(accessDeniedException.getMessage());
        // 将Result对象转换为JSON字符串,并写入输出流
        out.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));
        // 刷新输出流
        out.flush();
        // 关闭输出流
        out.close();
    }
}

认证失败处理器

package com.lzy.security;

import cn.hutool.json.JSONUtil;
import com.lzy.common.lang.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 将响应的内容类型设置为JSON
        response.setContentType("application/json;charset=utf-8");
        // 设置响应状态码为401未认证
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        // 获取响应的输出流
        ServletOutputStream out = response.getOutputStream();
        Result result = Result.fail("未登录或登录已过期,请重新登录");
        // 将Result对象转换为JSON字符串,并写入输出流
        out.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));
        // 刷新输出流
        out.flush();
        // 关闭输出流
        out.close();
    }
}

配置里引用,在异常处理器注释那里

package com.lzy.config;
 
import com.lzy.security.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级别的权限注解
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    LoginFailureHandler loginFailureHandler;
    @Autowired
    LoginSuccessHandler loginSuccessHandler;
    @Autowired
    CaptchaFilter captchaFilter;
    @Autowired
    JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    @Autowired
    JwtAccessDeniedHandler jwtAccessDeniedHandler;
    @Bean
    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        return new JwtAuthenticationFilter(authenticationManager());
    }


    private static final String[] URL_WHITELIST = {
            "/login",
            "/logout",
            "/captcha",
            "/favicon.ico", // 防止 favicon 请求被拦截
    };

    protected void configure(HttpSecurity http) throws Exception {

        //跨域配置
        http.cors().and().csrf().disable()
                //登录配置
                .formLogin()
                .successHandler(loginSuccessHandler).failureHandler(loginFailureHandler)
                //禁用session
                .and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                //配置拦截规则
                .and().authorizeRequests()
                //白名单
                .antMatchers(URL_WHITELIST).permitAll()
                //其他请求都需要认证
                .anyRequest().authenticated()
                //异常处理器
                .and().exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .accessDeniedHandler(jwtAccessDeniedHandler)
                //JWT验证过滤器
                .and().addFilter(jwtAuthenticationFilter())
                //配置自定义的过滤器
                .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class);

    }
 
}

Spring Security 6 中的认证失败处理器主要用于处理用户身份验证过程中出现的错误,例如密码错误、权限不足等。它允许你在用户尝试访问受保护资源时提供定制化的反馈信息。配置步骤如下: 1. **创建自定义的`AuthenticationFailureHandler`**: - 定义一个实现`AuthenticationFailureHandler`接口的类,比如`MyAuthenticationFailureHandler`。 ```java public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { // 这里编处理失败登录的逻辑,如发送错误消息到前端 } } ``` 2. **添加到全局安全过滤器链**: 在`WebSecurityConfigurerAdapter`中,使用`formLogin()`方法设置认证失败处理器: ```java @Autowired private MyAuthenticationFailureHandler authenticationFailureHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin() .failureHandler(authenticationFailureHandler); } ``` 3. **启用HTTP基本认证失败处理**: 如果需要处理基于HTTP基本认证失败,可以在`http`元素中指定`httpBasic()`: ```java http.httpBasic().authenticationEntryPoint(new CustomEntryPoint()); ``` 4. **处理异常详细程度**: 可以通过`AbstractAuthenticationProcessingFilter.setDefaultFailureResponse`设置默认的失败响应,或者在每个具体的过滤器中单独配置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值