原来一直使用shiro做安全框架,配置起来相当方便,正好有机会接触下SpringSecurity,学习下这个。顺道结合下jwt,把安全信息管理的问题扔给客户端,
准备
首先用的是SpringBoot,省去写各种xml的时间。然后把依赖加入一下
<!--安全--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!--jwt--> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency>
application.yml加上一点配置信息,后面会用
jwt: secret: secret expiration: 7200000 token: Authorization
可能用到代码,目录结构放出来一本文来源gaodai$ma#com搞$$代**码)网@下
配置
SecurityConfig配置
首先是配置SecurityConfig,代码如下
@Configuration @EnableWebSecurity// 这个注解必须加,开启Security @EnableGlobalMethodSecurity(prePostEnabled = true)//保证post之前的注解可以使用 public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; @Autowired JwtUserDetailsService jwtUserDetailsService; @Autowired JwtAuthorizationTokenFilter authenticationTokenFilter; //先来这里认证一下 @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoderBean()); } //拦截在这配 @Override protected void configure(HttpSecurity http) throws Exception { http .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint) .and() .authorizeRequests() .antMatchers("/login").permitAll() .antMatchers("/haha").permitAll() .antMatchers("/sysUser/test").permitAll() .antMatchers(HttpMethod.OPTIONS, "/**").anonymous() .anyRequest().authenticated() // 剩下所有的验证都需要验证 .and() .csrf().disable() // 禁用 Spring Security 自带的跨域处理 .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 定制我们自己的 session 策略:调整为让 Spring Security 不创建和使用 session http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); } @Bean public PasswordEncoder passwordEncoderBean() { return new BCryptPasswordEncoder(); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }
ok,下面娓娓道来。首先我们这个配置类继承了WebSecurityConfigurerAdapter,这里面有三个重要的方法需要我们重写一下:
configure(HttpSecurity http):这个方法是我们配置拦截的地方,exceptionHandling().authenticationEntryPoint(),这里面主要配置如果没有凭证,可以进行一些操作,这个后面会看jwtAuthenticationEntryPoint这个里面的代码。进行下一项配置,为了区分必须加入.and()。authorizeRequests()这个后边配置那些路径有需要什么权限,比如我配置的那几个url都是permitAll(),及不需要权限就可以访问。值得一提的是antMatchers(HttpMethod.OPTIONS, “/**”),是为了方便后面写前后端分离的时候前端过来的第一次验证请求,这样做,会减少这种请求的时间和资源使用。csrf().disable()是为了防止csdf攻击的,至于什么是csdf攻击,请自行百度。