java - 如何配置Spring安全性

标签 java spring-boot http spring-security cors

我对 spring-security 的配置有疑问。到目前为止我已经做了一些配置,并且我可以通过 **GET 使用所有 API。但其余 API 都没有像 Delete-PUT-Post 那样。 为此,我收到如下错误:

错误为 403。enter image description here enter image description here enter image description here

所以我的配置分为两个类:

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();
    }
}

我的 Controller 如下:

ItemController

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,请看看类(class),也许你比我有更多的想法,因为我缺乏经验。

最佳答案

            http.authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()

您在参数中传递 OPTIONS 方法,用于指定允许哪种方法,仅允许 OPTIONS 类型请求,如果您想允许 get 请求,请使用 GET。如果您想允许所有请求类型,只需传递“/**”作为参数,而不指定任何方法类型。

关于java - 如何配置Spring安全性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60037168/

相关文章:

java - mongodb mongoTemplate 获取具有某些条件的不同字段

java - Spring boot @Cacheble 与 Ehcache

java - @Transactional 注释与 saveAndFlush 一起使用?

http - 在 vbscript 中检索多个 cookie

php - 隐藏标题发布数据

java - JPQL 多重联接和集合

java - GAE 部署页面速度警告

java - 有没有一种优雅的方法可以使用 Optional 初始化和返回可空字段的值

java - JNDI 失败,出现 javax.naming.NameNotFoundException :Name [jdbc/Database] is not bound in this Context when deploying Spring Boot2 Tomcat 9 NO EMBEDDED

c++ - 使用 QNetworkAccessManager.get,我如何决定中止?