springboot3.x 整合springsecurity 不需要继承WebSecurityConfigurerAdapter的配置方式

springsecurity使用(主要针对第一次接触的,熟悉的就没什么意义了)

一、思维误区

  1. 主要针对的是突然一下没有适应springsecurity的朋友,因为新版不需要继承WebSecurityConfigurerAdapter所以改配置一下有点懵的朋友。
  2. 刚开始准备搭建的时候找的网上的配置流程,有很多需要配置的地方,因为使用的是最新的jdk和springboot有一些配置的地方不一致,所以懵了。
  3. 因为是第一次搭spring security所以对每一个配置是干什么的,每一个类是干什么的并不清楚。也不知道版本差异的地方需要怎么替换。
  4. 所以开始学习spring security。但是网上的资料大都是上一个版本的。虽然讲的都比较细。但是要不是讲的很长。看一遍都感觉费劲,更别说一下完全掌握,并且自定义。要不就是主要只有配置(依照的配置好,因为版本却总不起作用)。(因为这次是修改,突然发现新版的配置网上也有教程了,所以这个其实意义也就不大了,不过还是留下吧,万一有能帮到的人
  5. 这种东西的使用,总归还是要成功一次。才好继续。
  6. 经过一段时间思考,突然发现自己陷入了一个误区:
  • 总以为,把所有的配置好了之后才可以使用…
  • 其实,什么也不配置,他本身就是一个完整的配置。是可以使用的。(只是可能不符合业务要求)
  1. 理解了这一点之后问题就简单了
  • 把所有不对的配置去掉(或者直接把所有的配置去掉)
  • 需要什么再放开什么

二、配置理解(主要只是自己用到的一些,如有需要网上很多)

  • 暂时先主要介绍了一下,配置类的概念,如果需要完整配置网上很多,随便哪个都可以。这个主要是辅助理解。(并且给一个springsecurity3.x的主配置)

  • 不想写太多。本来准备,把代码都贴上来。但是看着一下就多了,乱了。所以先不贴了。

核心配置类

@Configuration
@EnableWebSecurity //开启SpringSecurity的默认行为
@Slf4j //日志
//@EnableGlobalMethodSecurity(prePostEnabled = true)// 新版不推荐使用这个,这个的主	要功能是开启方法上的鉴权,使用下面这个就可以
@EnableMethodSecurity
// 新版不需要继承WebSecurityConfigurerAdapter
public class MySecurityConfig {
	// 这个类主要是获取库中的用户信息,交给security
	@Autowired
	UserDetailServiceImpl userDetailsService;
	// 这个的类是认证失败处理(我在这里主要是把错误消息以json方式返回)
	@Autowired
	private JwtAuthenticationEntryPoint unauthorizedHandler;
	// 鉴权失败的时候的处理类
	@Autowired
	private JwtAccessDeniedHandler jwtAccessDeniedHandler;


	/**
	* 核心配置
	*/
	@Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
			// 这个配置是关闭csrf
			.csrf(AbstractHttpConfigurer::disable)
			// 处理请求
            .authorizeHttpRequests(authorize -> {	                       
				// 放开哪些接口
      			authorize
				.requestMatchers("/login","/error","/withdraw/deposit/login")
				.permitAll();
                // 其他的都需要认证
				authorize.anyRequest().authenticated();
            })
			// 错误处理
            .exceptionHandling(m -> {
                m.authenticationEntryPoint(unauthorizedHandler);
                m.accessDeniedHandler(jwtAccessDeniedHandler);
            })
			// 如果使用token这个配置是必须的
            .addFilterBefore(authenticationJwtTokenFilter(), 	UsernamePasswordAuthenticationFilter.class)
			// 这个不配置也会生效
            .authenticationProvider(authenticationProvider())
			// 下面这个两个不待测效果了
            .httpBasic(Customizer.withDefaults())
            .formLogin(Customizer.withDefaults());
            
        return http.build();
	}


	/**
	* 这个是如果使用token方式需要在这个类中先处理token(根据token判断是否去认证)
	*/
	@Bean
	public TokenAuthenticationFilter authenticationJwtTokenFilter() {
    	return new TokenAuthenticationFilter();
	}

	// 身份认证提供程序(加密方式,用户查询)
	@Bean
	public DaoAuthenticationProvider authenticationProvider() {
    	DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    	authProvider.setUserDetailsService(userDetailsService);
    	authProvider.setPasswordEncoder(passwordEncoder());
    	return authProvider;
	}

	// 这个主要是为了其他地方可以使用认证管理器
	@Bean
	public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfiguration) throws Exception {
    	return authConfiguration.getAuthenticationManager();
	}

	// 加密方式
	@Bean
	public PasswordEncoder passwordEncoder() {
   		return new BCryptPasswordEncoder();
	}
}

博客地址:https://www.dreamsoul.top/archives/1704855069879

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security 是一个企业级安全框架,它提供了一系列的安全服务和基于标准的安全注解,帮助开发者在应用程序中实现身份认证和权限控制等功能。Spring Boot 是一个快速构建应用程序的框架,它提供了对 Spring 框架的自动配置,简化了项目的搭建和开发。将 Spring SecuritySpring Boot 结合使用,可以很方便地实现安全认证和授权功能。 下面是 Spring Boot 整合 Spring Security 的步骤: 1. 在 pom.xml 文件中添加 Spring Security 依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 创建一个 Security 配置类,用于配置 Spring Security 的相关参数,如安全拦截规则、用户认证方式等。可以继承 WebSecurityConfigurerAdapter 类,重写 configure 方法来实现配置。 ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .anyRequest().authenticated() .and() .formLogin() .and() .httpBasic(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin").password("{noop}admin123").roles("ADMIN") .and() .withUser("user").password("{noop}user123").roles("USER"); } } ``` 3. 在配置类中配置用户认证方式。可以使用内存认证、数据库认证或者 LDAP 认证等方式进行用户认证。 4. 配置安全拦截规则。可以通过 antMatchers 方法来设置 URL 的安全拦截规则,如 /admin/** 需要 ADMIN 角色才能访问,/user/** 需要 USER 角色才能访问。 5. 配置登录页面。可以通过 formLogin 方法来配置登录页面的 URL,如 /login。用户输入正确的用户名和密码后,会跳转到登录成功页面。 6. 配置 HTTP Basic 认证。可以通过 httpBasic 方法来开启 HTTP Basic 认证,这样客户端可以使用用户名和密码来访问受保护的资源。 通过上述步骤,就可以将 Spring Security 集成到 Spring Boot 应用程序中,实现安全认证和授权功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值