当前位置: 首页 > 科技观察

SpringSecurity权限控制系列(二)

时间:2023-03-12 12:49:50 科技观察

本文主要内容:请求拦截和自定义登录页面。上一篇:《??Spring Security权限控制系列(一)??》自定义拦截请求在默认项目中引入SpringSecurity后,所有的请求都会被拦截,包括静态资源,这绝对不是我们想要的。接下来我们看看如何实现资源的自定义拦截。创建如下静态资源,并配置静态资源访问路径。由于静态资源的默认访问路径是/**,所以在静态资源上加了一个前缀,以区别于Controller。spring:mvc:static-path-pattern:/resources/**要访问静态资源,首先要将SpringSecurity从项目中移除,然后再访问。分别访问index.js和index.html。可以正常访问。接下来在项目中添加SpringSecurity之后,再访问,会发现之前可以访问的话,可以直接跳转到登录页面。静态资源发布自定义配置设置路径方向规则。@ConfigurationpublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{@Overrideprotectedvoidconfigure(HttpSecurityhttp)throwsException{http.authorizeRequests()//获取基于SpEL的URL授权对象expression.antMatchers("/resources/**")//设置任何其URI路径规则以/resources.permitAll()开头的请求;//只要是基于上面/resources开头的请求,都会被允许http.formLogin();//如果请求不是上面配置的访问uri前缀,则允许登录}}再次访问静态资源,此时可以正常访问,无需跳转到登录页面,访问Controller接口GET/demos/home运行结果。发现可以访问静态资源,我们的Controller也可以访问。修改配置只释放指定资源//direction/resource①请求的资源http.authorizeRequests().anyRequest()//任何请求.authenticated();//需要登录认证授权②http.formLogin();}经过以上配置后,所有以/resources为前缀的请求都会被重定向,其他任何请求都会被拦截并跳过,进入登录页面。注意:如果上述①和②顺序颠倒,则服务启动时会报错。错误信息如下。Causedby:java.lang.IllegalStateException:Can'tconfigureantMatchersafteranyRequestatorg.springframework.util.Assert.state(Assert.java:76)~[spring-core-5.3.12.jar:5.3.12]不能在anyRequest之后配置antMatchers。为请求配置角色定义2个控制器。@RestController@RequestMapping("/demos")publicclassDemoController{@GetMapping("home")publicObjecthome(){return"demoshome";}}@RestController@RequestMapping("/api")publicclassApiController{@GetMapping("/{id}")publicObjectget(@PathVariable("id")Integerid){return"Get-"+id+"-数据”;}}我们期望/demos/**接口访问必须有USERS权限,/api/**接口访问必须有ADMIN权限,配置如下:@Overrideprotectedvoidconfigure(AuthenticationManagerBuilderauth)throwsException{//配置访客用户,此用户具有ADMIN角色auth.inMemoryAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance()).withUser("guest").password("123456").roles("ADMIN");}@Overrideprotectedvoidconfigure(HttpSecurityhttp)抛出异常{http.csrf().disable();http。authorizeRequests().antMatchers("/resources/**").permitAll();//这里不需要使用ROLE_前缀,系统会自动插入前缀http.authorizeRequests().antMatchers("/demos/**").hasRole("USERS");///demos/**必须有USERS角色http.authorizeRequests().antMatchers("/api/**").hasRole("ADMIN");///api/**必须有ADMIN角色http.authorizeRequests().anyRequest().authenticated();http.formLogin();}分别访问/demos/home和/api/1接口通过guest/123456登录后,接口之间返回403状态错误(读403.html),我的项目在static下新建了一个403.html错误页面/error/api/**接口访问正常,然后我们在配置一个USERS权限的用户protectedvoidconfigure(AuthenticationManagerBuilderauth)throwsException{auth.inMemoryAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance()).withUser("guest").password("123456").roles("ADMIN").and().withUser("test").password("666666").roles("USERS");}通过测试访问/demosuser登录后可以正常访问/home接口配置多个权限很多情况下,我们期望用户只要使用其中的任意一个权限,就可以访问该资源,那么如何配置呢?http.authorizeRequests().antMatchers("/demos/**").hasAnyRole("USERS","AKKF","BLLE");http.authorizeRequests().antMatchers("/api/**").hasAnyRole("管理员","经理","系统");通过上面的配置,只要有任何权限就可以满足。其他配置具有多个具有相同权限的URI。http.authorizeRequests().antMatchers("/demos/**","/api/**").hasAnyAuthority("ROLE_USERS","ROLE_ADMIN");对请求的方法控制。http.authorizeRequests().antMatchers(HttpMethod.GET).permitAll();自定义登录页引入依赖spring-boot-starter-thymeleafthymeleaf配置spring:thymeleaf:prefix:classpath:/templates/登录页面在/resources/templates/下新建login.html页面。这里省略不相关的东西。

认证登录

安全登录
记住我安全登录Controller定义登录页面@ControllerpublicclassLoginController{@GetMapping("/custom/login")publicStringlogin(){return"login";}}自定义配置登录页面protectedvoidconfigure(HttpSecurityhttp)throwsException{http.csrf().disable();http.authorizeRequests().antMatchers("/resources/**").permitAll();http.authorizeRequests().antMatchers("/demos/**").hasRole("USERS");http.authorizeRequests().antMatchers("/api/**").hasRole("ADMIN");//登录页面指向上面配置的Controller可以是http.formLogin().loginPage("/custom/login");}测试:总结:SpringSecurity是如何配置必须有权限拦截请求资源访问的配置。自定义登录页面。