如何在Spring Security 的配置AuthenticationEntryPoint和 AccessDeniedHandler
时间: 2023-08-22 18:16:12 浏览: 63
在 Spring Security 中,可以通过配置 AuthenticationEntryPoint 和 AccessDeniedHandler 来处理未经身份验证的访问请求和访问被拒绝的情况。具体步骤如下:
1. 创建 AuthenticationEntryPoint 和 AccessDeniedHandler 的实现类,并实现对应的方法。
2. 在 Spring Security 的配置类中,通过配置 http 对象的 `exceptionHandling()` 方法来设置 AuthenticationEntryPoint 和 AccessDeniedHandler,例如:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
private MyAccessDeniedHandler accessDeniedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.accessDeniedHandler(accessDeniedHandler)
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.permitAll();
}
}
```
在上述的代码中,我们首先通过 `@Autowired` 注解将我们自己实现的 AuthenticationEntryPoint 和 AccessDeniedHandler 注入进来。然后在 `configure()` 方法中,我们通过 `exceptionHandling()` 方法来配置 AuthenticationEntryPoint 和 AccessDeniedHandler,最后将两个实现类传入对应的方法中即可。
需要注意的是,AuthenticationEntryPoint 和 AccessDeniedHandler 都是针对不同的场景进行处理的,因此在配置时需要区分清楚。AuthenticationEntryPoint 处理的是未经身份验证的访问请求,而 AccessDeniedHandler 处理的是访问被拒绝的情况。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)