[英]How to configure spring security
我對 spring-security 的配置有問題。 所以到目前為止我已經進行了一些配置,並且我能夠通過**GET使用所有API。 但是其他 API 都不像 Delete-PUT-Post。 為此,我收到如下錯誤:
所以我的配置分為兩類:
CorsFilter.java
package com.example.rest.webservices.restfulwebservices.basic.auth;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CorsFilter implements Filter
{
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException
{
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
// if (request.getMethod().equals("OPTIONS"))
// {
response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"Content-Type, Authorization, Content-Length, X-Requested-With");
response.addHeader("Access-Control-Allow-Credentials", "true");
// }
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy()
{
}
}
第二類是:
SpringSecurityConfigurationBasicAuth
package com.example.rest.webservices.restfulwebservices.basic.auth;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.session.SessionManagementFilter;
@Configuration
@EnableWebSecurity
public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter {
@Bean
CorsFilter corsFilter() {
CorsFilter filter = new CorsFilter();
return filter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(corsFilter(), SessionManagementFilter.class);
//http.cors();
http .csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
http.authorizeRequests()
.antMatchers("/**").permitAll()
.anyRequest().authenticated()
.and()
// .formLogin().and()
.httpBasic();
}
}
我的控制器如下:
項目控制器
package com.example.rest.webservices.restfulwebservices.todo;
import java.net.URI;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@CrossOrigin(origins="http://localhost:4200")
@RestController
public class ItemController {
@Autowired
private ItemService itemService;
@GetMapping(path = "/users/{username}/items")
public List<Item> getAllToDosList(@PathVariable String username){
return itemService.findAll(username);
}
@GetMapping(path = "/users/{username}/item/{id}")
public Item getItem(@PathVariable String username, @PathVariable Integer id){
return itemService.findById(id);
}
@PutMapping("/users/{username}/item/{id}")
public ResponseEntity<Item> updateItem(@PathVariable String username,
@PathVariable Integer id, @RequestBody Item item ){
Item updateditem = itemService.saveItem(item);
return new ResponseEntity<Item>(updateditem, HttpStatus.OK);
}
@PostMapping("/users/{username}/item")
public ResponseEntity<Void> addItem(@PathVariable String username, @RequestBody Item item ){
Item createdItem = itemService.saveItem(item);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(createdItem.getId()).toUri();
return ResponseEntity.created(uri).build();
}
@DeleteMapping(path = "/users/{username}/item/{id}")
public ResponseEntity<Void> removeToDosFromList(@PathVariable String username,
@PathVariable Integer id){
Item todo = itemService.deleteToDoById(id);
if (todo != null)
{
return ResponseEntity.noContent().build();
}
return ResponseEntity.notFound().build();
}
}
而且目前只對GET API有效,請看課文,也許你的想法比我多,因為我缺乏經驗。
http.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
您正在參數中傳遞 OPTIONS 方法,該方法用於指定要允許的方法,僅允許 OPTIONS 類型的請求,如果要允許獲取請求,請使用 GET。 如果您想允許所有請求類型,只需傳遞“/**”作為參數,而不指定任何方法類型。
我認為這里的問題是:您想驗證用戶調用某些路徑嗎?
如果答案是否定的,你應該刪除這一行.anyRequest().authenticated()
如果答案是肯定的,您應該指定要進行身份驗證的網址並定義身份驗證方法並使用正確的授權標頭進行調用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.