spring security 是一个用于权限验证和资源权限管理的的一个库。简单的记录一下,spring security集成到spring boot 项目中的过程。 ### WebSecurityConfiguration 主要是一个`WebSecurityConfiguration` ``` java @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService(getUserDetailsService()) .passwordEncoder(new PasswordEncoder() { @Override public String encode(CharSequence rawPassword) { return rawPassword.toString(); } @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { return rawPassword.toString().equals(encodedPassword); } }); } ``` - 继承`WebSecurityConfigurerAdapter`,然后重写这个`configure`方法, 可以设置用户的来源: `userDetailsService(UserDetailsService uds)` ,`UserDetailsService` 决定了用户怎么来的。 比如:通过用户名从数据库查询 ``` java @Bean public UserDetailsService getUserDetailsService(){ return username -> { SysUser user = userRepository.getSysUserByUsername(username); if (user != null){ return user; }else { throw new UsernameNotFoundException("no such user name."); } }; } ``` - 可以设定密码的验证机制 ``` java .passwordEncoder(new PasswordEncoder() { @Override public String encode(CharSequence rawPassword) { return rawPassword.toString(); } @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { return rawPassword.toString().equals(encodedPassword); } }); ``` 可以设置密码的加密和匹配方式 ### 对请求进行权限控制 提供了如csrf等功能, - csrf - antMatchers - formLogin - logout 等,对这些可以进一步设置 - disable() **如csrf** - permitAll() **不要权限** - authenticated() **需要权限** 等。 例子: ``` java @Override protected void configure(HttpSecurity http) throws Exception { http .csrf() .and() .authorizeRequests() .antMatchers("/api/*") .authenticated() .antMatchers("/") .authenticated() .and() .formLogin() .loginPage("/login/page") .defaultSuccessUrl("/out") .loginProcessingUrl("/login") .failureUrl("/e") .permitAll() .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/out") .permitAll(); CsrfFilter csrfFilter = new CsrfFilter(); http.addFilterAfter(csrfFilter,CsrfFilter.class); } ```