全国旗舰校区

不同学习城市 同样授课品质

北京

深圳

上海

广州

郑州

大连

武汉

成都

西安

杭州

青岛

重庆

长沙

哈尔滨

南京

太原

沈阳

合肥

贵阳

济南

下一个校区
就在你家门口
+
当前位置:首页  >  技术干货

HttpSecurity详解

发布时间:2023-11-23 14:27:15
发布人:xqq

一、HttpSecurity源码

HttpSecurity类是Spring Security核心配置类之一,用来配置Spring Security的行为,包括认证方式、权限控制、CSRF保护等。我们先来看一下HttpSecurity类的源码结构:


@Configuration
public final class HttpSecurity extends
        AbstractConfiguredSecurityBuilder
        implements SecurityBuilder, SecurityConfigurerAware, HttpSecurity>, HttpSecurityBuilder {

    // 构造方法
    public HttpSecurity(ObjectPostProcessor objectPostProcessor, AuthenticationManagerBuilder builder,
                        Map, Object> sharedObjects) {
        super(objectPostProcessor, true, sharedObjects);
        // come code here...
    }

    // 配置方法
    public HttpSecurity requestMatcher(RequestMatcher requestMatcher) {
        // some code here...
        return this;
    }

    // some other methods...

}

如上代码所示,HttpSecurity是一个@Configuration配置类,继承了AbstractConfiguredSecurityBuilder类,并实现了SecurityBuilder和SecurityConfigurerAware接口。其中,requestMatcher方法用于匹配请求的URL,根据匹配结果来对请求进行处理。

二、HttpSecurity的用法

使用方法可以分为以下几步:

1、创建一个SecurityConfigurer,并在其中重写configure方法,实现对HttpSecurity的配置;

2、通过调用HttpSecurity的apply方法,并传入第一步创建的SecurityConfigurer,来将SecurityConfigurer中的配置应用到HttpSecurity中;

3、配置成功后,HttpSecurity会返回一个DefaultSecurityFilterChain类型的对象,用于构建安全过滤器链。

三、HttpSecurity配置

3.1 HttpSecurity默认配置

当我们没有对HttpSecurity进行额外的配置时,Spring Security会使用默认配置。默认配置包括以下内容:


http
    .authorizeRequests()
        .anyRequest().authenticated()
        .and()
    .formLogin()
        .and()
    .httpBasic();

以上代码表示,所有请求需要进行身份验证,并且要求用户使用表单登录或HTTP基本认证。

3.2 HttpSecurity权限配置详解

针对不同路径和请求类型,我们可以配置不同的授权策略。


http.authorizeRequests()
    .antMatchers("/admin/**").hasRole("ADMIN")
    .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
    .anyRequest().authenticated()
    .and()
.formLogin()
    .loginPage("/login")
    .permitAll()
    .and()
.logout()
    .permitAll();

以上代码表示,对于"/admin/**"路径下的请求,需要有"ADMIN"角色方可访问;对于"/db/**"路径下的请求,需要有"ADMIN"和"DBA"两个角色方可访问;而其他请求只需要在通过身份验证后即可访问。同时,我们还可以设置登录页和退出页。

3.3 HttpSecurity解密失败怎么回事

解密失败可能是因为客户端传递的数据被篡改或者密钥不正确,当出现解密失败的情况,可以使用以下代码对HttpSecurity进行配置:


http.exceptionHandling()
    .authenticationEntryPoint(new Http403ForbiddenEntryPoint())
    .accessDeniedHandler(new AccessDeniedHandlerImpl());

以上代码为设置Http403ForbiddenEntryPoint和AccessDeniedHandlerImpl类,用于处理解密失败后的异常情况。

四、完整代码示例

下面是一个完整的HttpSecurity配置示例:


@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
        .logout()
            .permitAll()
            .and()
        .exceptionHandling()
            .authenticationEntryPoint(new Http403ForbiddenEntryPoint())
            .accessDeniedHandler(new AccessDeniedHandlerImpl());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

以上代码为一个完整的Spring Security配置类示例,其中包含了对HttpSecurity和AuthenticationManagerBuilder的配置。

httpsecurity

相关文章

C++中的write函数详解

C++中的write函数详解

2023-11-23
Java 学生类与教师类详解

Java 学生类与教师类详解

2023-11-23
PageHelper依赖详解

PageHelper依赖详解

2023-11-23
linux删除sh脚本的命令,linux删除.sh

linux删除sh脚本的命令,linux删除.sh

2023-11-23

最新文章

武汉新媒体行业公司排名

武汉新媒体行业公司排名

2023-11-01
武汉新媒体就业现状好吗

武汉新媒体就业现状好吗

2023-11-01
武汉全媒体行业发展现状及趋势

武汉全媒体行业发展现状及趋势

2023-10-31
武汉全媒体现状

武汉全媒体现状

2023-10-31