SpringSecurity从0到1搭建详细教程四——自定义认证失败处理与跨域问题

        我们还希望在认证失败或者是授权失败的情况下也能和我们的接口一样返回相同结构的json,这样可以让前端能对响应进行统一的处理。要实现这个功能我们需要知道SpringSecurity的异常处理机制。

        在SpringSecurity中,如果我们在认证或者授权的过程中出现了异常会被ExceptionTranslationFilter捕获到。在ExceptionTranslationFilter中会去判断是认证失败还是授权失败出现的异常。

如果是认证过程中出现的异常会被封装成AuthenticationException然后调用AuthenticationEntryPoint对象的方法去进行异常处理。

自定义实现类 AuthenticationEntryPointImpl

package org.example.exception;

import com.alibaba.fastjson.JSON;
import org.example.result.ResponseResult;
import org.example.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 如果我们在认证或者授权的过程中出现了异常会被ExceptionTranslationFilter捕获到。
 * 在ExceptionTranslationFilter中会去判断是认证失败还是授权失败出现的异常。
 * 如果是认证过程中出现的异常会被封装成AuthenticationException
 * 然后调用AuthenticationEntryPoint对象的方法去进行异常处理。
 */

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException, ServletException {

        ResponseResult result =
                new ResponseResult<>(HttpStatus.UNAUTHORIZED.value(),"用户认证失败,请重新登录");
        String json = JSON.toJSONString(result);
        //处理异常
        WebUtils.renderString(response,json);

    }
}

​ 如果是授权过程中出现的异常会被封装成AccessDeniedException然后调用AccessDeniedHandler对象的方法去进行异常处理。

自定义实现类 AccessDeniedHandlerImpl

package org.example.exception;

import com.alibaba.fastjson.JSON;
import org.example.result.ResponseResult;
import org.example.util.WebUtils;
import org.springframework.http.HttpStatus;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 如果我们在认证或者授权的过程中出现了异常会被ExceptionTranslationFilter捕获到。
 * 在ExceptionTranslationFilter中会去判断是认证失败还是授权失败出现的异常。
 * 如果是授权过程中出现的异常会被封装成AccessDeniedException
 * 然后调用AccessDeniedHandler对象的方法去进行异常处理。
 */

@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e)
            throws IOException, ServletException {
        ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN.value(), "权限不足");
        String json = JSON.toJSONString(result);
        WebUtils.renderString(response,json);
    }
}

自定义异常处理类写完后,需要在 SecurityConfig 中配置给SpringSecurity

    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPoint;
    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandler;
                // 配置异常处理器
                // 配置认证失败处理器
                http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
                // 配置授权失败处理器
                http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);

重启启动项目后,测试 用户认证失败

测试 权限不足 

至此, 整个springSecurity项目搭建完毕。

SpringSecurity 跨域 

浏览器出于安全的考虑,使用 XMLHttpRequest对象发起 HTTP请求时必须遵守同源策略,否则就是跨域的HTTP请求,默认情况下是被禁止的。 同源策略要求源相同才能正常进行通信,即协议、域名、端口号都完全一致。

​ 前后端分离项目,前端项目和后端项目一般都不是同源的,所以肯定会存在跨域请求的问题。

​ 所以我们就要处理一下,让前端能进行跨域请求。

定义一个 实现 WebMvcConfigurer 的接口 CorsConfig 类 ,为SpringBoot配置跨域请求

package org.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路径
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOrigins("*")
                // 是否允许cookie
                .allowCredentials(true)
                // 设置允许的请求方式
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                // 设置允许的header属性
                .allowedHeaders("*")
                // 跨域允许时间
                .maxAge(3600);
    }
}

开启SpringSecurity的跨域访问,在 configure 配置类中配置

//配置跨域
        http.cors();

至此,跨越请求配置结束!

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security 并不直接解决跨域问题,而是通过集成 Spring MVC 提供的跨域解决方案来处理。 在 Spring MVC 中,可以通过添加 `@CrossOrigin` 注解来实现跨域访问。在 Spring Security 中,可以通过配置 `WebSecurityConfigurerAdapter` 来添加 `CorsConfigurationSource`,从而实现跨域访问。 具体实现方法如下: 1. 在配置类中添加 `CorsConfigurationSource`: ``` @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("*")); configuration.setAllowedMethods(Arrays.asList("*")); configuration.setAllowedHeaders(Arrays.asList("*")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } // ... } ``` 2. 将 `CorsFilter` 添加到 Spring Security 过滤器链中: ``` @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { // ... @Override protected void configure(HttpSecurity http) throws Exception { http // ... .cors() .and() // ... } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } } ``` 这样就可以通过 Spring Security 实现跨域访问了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值