Spring Security 有条件的基本认证
Posted
技术标签:
【中文标题】Spring Security 有条件的基本认证【英文标题】:Spring Security Conditional Basic Auth 【发布时间】:2017-09-05 15:29:46 【问题描述】:我有一个端点,我想在不需要基本身份验证的情况下允许访问。如下端点:
@ApiOperation(value = "Get a image by id", response = ResponseEntity.class)
@RequestMapping(value = "/id", method = RequestMethod.GET) //sets the mapping url and the HTTP method
public void getById(@PathVariable("id") Long id, HttpServletResponse response) throws NotFoundException
ImageView view;
try
view = manager.get(id);
ByteArrayInputStream in = new ByteArrayInputStream(view.getImageData());
response.setContentType(MediaType.parseMediaType(view.getImageMimeType()).toString());
IOUtils.copy(in, response.getOutputStream());
catch (NotFoundException e)
response.setStatus(204); //HttpStatus.NO_CONTENT);
return;
catch (IOException ioe)
response.setStatus(400);//HttpState.BAD_REQUEST
return;
我已经阅读了其他几篇关于有类似问题的人的堆栈溢出帖子,并看到覆盖安全配置有效。以下是我通过阅读几篇文章设计的解决方案。但是,我仍然遇到问题并在请求没有身份验证的资源时收到 401。除此之外,完整的路线将是“host/service/v1/images/id”
@Override
protected void configure(HttpSecurity http) throws Exception
http.csrf().disable() //disable csrf being needed for header in a request
.authorizeRequests() //authorize the following request based on following set rules
.antMatchers(HttpMethod.OPTIONS, "**").permitAll() //allow any user to access this when OPTIONS
.antMatchers(HttpMethod.GET,"**/service/v1/images/**").permitAll() //allows GETS for given route permitted to all users
.anyRequest().authenticated() //catch all: this implies that if nothing matches the above two patterns, then require authentication
.and().httpBasic(); //utilize http basic for authentication
任何关于我可能做错了什么以及如何纠正这个问题的见解将不胜感激。
【问题讨论】:
【参考方案1】:为了忽略特定 URL 的安全性,请执行以下操作:
除了你的
@Override
protected void configure(HttpSecurity http) throws Exception ...
您还需要覆盖下一个方法:
@Override
public void configure(WebSecurity web) throws Exception ...
在该方法上,您可以编写类似的内容以忽略特定 URL 的安全性:
@Override
public void configure(WebSecurity web) throws Exception
web.ignoring().antMatchers("/css/**", "/js/**",
"/app/controllers/**", "/app/partials/**", "/app/*",
"/", "/index.html", "/favicon.ico");
上面的示例将禁用指定的 ant 匹配器的安全性。
你可以放弃 permitAll()
【讨论】:
所以我可以删除以下代码还是只删除许可?:.antMatchers(HttpMethod.GET,"/service/v1/images/").permitAll() 但首先添加 web.ignoring.antMatchers("/service/v1/images/")以上是关于Spring Security 有条件的基本认证的主要内容,如果未能解决你的问题,请参考以下文章
Spring Security OAuth2.0认证授权介绍