简介【Spring-Security框架】

概要

通过持续更新这篇文章,记录自己从0到1对Spring-Security框架的使用实践过程。

框架依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

Security的本质特点

  1. 认证(Authentication):确保用户身份的真实性。Spring Security 支持多种认证机制,如表单登录、HTTP 基本身份验证、OAuth2、JWT 等,能够验证用户提供的凭证并确认其身份。
  2. 授权(Authorization):控制已认证用户对系统资源的访问权限。这基于角色(Role-based)或权限(Permission-based)的访问控制,确保用户只能访问他们被授予权限的资源。
  3. 安全性上下文管理(Security Context Management):维护用户的认证状态(即 Authentication 对象),在整个请求生命周期中透明地传递用户身份信息,使得安全决策可以在应用的任何层做出。
  4. 会话管理(Session Management):保护和管理用户会话,防止会话劫持和会话固定攻击。
  5. 安全防护(Security Protection):提供防御措施以抵御常见的Web攻击,如跨站脚本(XSS)、跨站请求伪造(CSRF)、SQL注入等。
  6. 灵活的配置与扩展性:Spring Security 设计高度可配置,开发者可以根据应用需求轻松定制安全策略,并且易于与其他Spring组件集成,支持AOP(面向切面编程)以实现细粒度的安全控制。
  7. 密码管理和加密服务:内置支持密码编码器和加密工具,帮助开发者安全地存储和处理敏感数据。

技术细节

配置文件

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/base/auth/login").permitAll()
                .anyRequest().authenticated()
                .and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
        http.cors();
    }


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

    @Bean
    public SessionRegistry sessionRegistry() {
        //定义了一个 SessionRegistry Bean,用于管理会话信息
        return new SessionRegistryImpl();
    }

    @Bean
    public SessionInformationExpiredStrategy sessionInformationExpiredStrategy() {
        //定义了一个 SessionInformationExpiredStrategy Bean,用于处理会话过期时的策略。
        return new CustomSessionInformationExpiredStrategy();
    }

    @Bean
    public ConcurrentSessionFilter concurrentSessionFilter() {
        return new ConcurrentSessionFilter(sessionRegistry(), sessionInformationExpiredStrategy());
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        //重写了该方法,用于获取 AuthenticationManager 的 Bean。
        return super.authenticationManagerBean();
    }

小结

正在逐步更新中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

N_D_A

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值