spring boot整合spring security笔记

最近自己做了一个小项目,正在进行springboot和spring Security的整合,有一丢丢的感悟,在这里分享一下:

    首先,spring boot整合spring security最好是使用Thymleaf,因为spring boot官方支持使用thymleaf,这样的话,整合起来会方便很多,而且,thymleaf也支持静态加载,比jsp方便许多。那么:

   第一步:需要先引入thymleafh和spring security的依赖(如果是web项目需要引入对应的jar包) 

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  第二步:在java配置类中去对spring security进行配置(也可以在xml中进行配置,
不过,spring boot比较推荐在代码中进行配置,所以顺势而为了,就在代码中
进行配置)
 
/**
* Spring Security 配置类.
*
*/
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用方法安全设置
public class SecurityConfig extends WebSecurityConfigurerAdapter {

private static final String KEY = "zhusz.com";

@Autowired
  private UserDetailsService userDetailsService;

@Autowired
   private PasswordEncoder passwordEncoder;

@Bean  
   public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(); // 使用 BCrypt 加密
   }

@Bean  
   public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder); // 设置密码加密方式
       return authenticationProvider;
}

/**
   * 自定义配置
   */
  @Override
  protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/css/**", "/js/**", "/fonts/**", "/index").permitAll() // 都可以访问
           .antMatchers("/h2-console/**").permitAll() // 都可以访问
           .antMatchers("/admins/**").hasRole("ADMIN") // 需要相应的角色才能访问
           .and()
.formLogin() //基于 Form 表单登录验证
           .loginPage("/login").failureUrl("/login-error") // 自定义登录界面
           .and().rememberMe().key(KEY) // 启用 remember me
           .and().exceptionHandling().accessDeniedPage("/403"); // 处理异常,拒绝访问就重定向到 403 页面
     http.csrf().ignoringAntMatchers("/h2-console/**"); // 禁用 H2 控制台的 CSRF 防护
     http.headers().frameOptions().sameOrigin(); // 允许来自同一来源的H2 控制台的请求
  }

/**
   * 认证信息管理
   * @param auth
   * @throws Exception
   */
  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(authenticationProvider());
}
}
此处的   userDetailsService 是spring security提供给我们的,不需要我们自己去编写
还有
PasswordEncoder 
密码加密也是spring security提供的。可以直接拿过来使用。自定义配置
是配置我们的过滤条件用的,此处可以使用前台的remeber me来实现前台的记住我
功能。
antMatchers("/h2-console/**").permitAll()表示都可以访问/h2-console/路径下的内容
antMatchers("/admins/**").hasRole("ADMIN") 表示只有admin这样的角色才可以
访问/admins/路径下的内容。
具体的功能说明在代码注释中都有说明,可以参考一下。

猜你喜欢

转载自www.cnblogs.com/pigwood/p/10100606.html