在Spring Boot REST API中捕获AccessDeniedException可以通过以下步骤实现:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
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;
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
// 自定义异常处理逻辑
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAccessDeniedHandler customAccessDeniedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and()
.exceptionHandling()
.accessDeniedHandler(customAccessDeniedHandler);
}
}
在上述配置中,我们使用antMatchers()方法指定了需要进行认证的API路径,使用authenticated()方法表示需要进行身份验证。如果访问被拒绝,将会调用自定义的AccessDeniedHandler进行处理。
这是一个基本的示例,你可以根据自己的需求进行定制化。关于Spring Boot和Spring Security的更多详细信息,你可以参考腾讯云的Spring Boot和Spring Security相关产品和文档:
没有搜到相关的沙龙