SpringBoot怎么整合SpringSecurity实现认证拦截

avatar
作者
筋斗云
阅读量:3

要在Spring Boot项目中整合Spring Security实现认证拦截,你可以按照以下步骤操作:

  1. 添加Spring Security依赖:在pom.xml文件中添加Spring Security的依赖。

    <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-security</artifactId> </dependency> 
  2. 创建Spring Security配置类:创建一个继承自WebSecurityConfigurerAdapter的配置类,用于配置Spring Security。

    import org.springframework.context.annotation.Configuration; 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 {  } 
  3. 配置认证和授权规则:在配置类中重写configure()方法,配置认证和授权规则。

    import org.springframework.security.config.annotation.web.builders.HttpSecurity;  @Override protected void configure(HttpSecurity http) throws Exception {     http         .authorizeRequests()             .antMatchers("/public/**").permitAll()             .anyRequest().authenticated()             .and()         .formLogin()             .loginPage("/login")             .permitAll()             .and()         .logout()             .permitAll(); } 
  4. 创建登录页面:创建一个登录页面,例如login.html。

  5. 配置用户信息和密码加密:在配置类中重写configure()方法,配置用户信息和密码加密方式。

    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.crypto.password.PasswordEncoder;  @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception {     auth         .inMemoryAuthentication()             .withUser("admin")             .password(passwordEncoder().encode("admin123"))             .roles("ADMIN"); }  @Bean public PasswordEncoder passwordEncoder() {     return new BCryptPasswordEncoder(); // 使用BCryptPasswordEncoder进行密码加密 } 
  6. 配置忽略静态资源:在配置类中重写configure()方法,配置忽略静态资源的访问限制。

    import org.springframework.security.config.annotation.web.builders.WebSecurity;  @Override public void configure(WebSecurity web) throws Exception {     web         .ignoring()         .antMatchers("/css/**", "/js/**", "/images/**"); } 
  7. 运行项目并测试:启动Spring Boot项目并访问需要认证的资源,系统将跳转到登录页面,输入用户名密码即可完成认证。

这样就完成了Spring Boot整合Spring Security实现认证拦截的配置。你可以根据需要进行相应的定制和扩展。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!