java Spring安全基于角色的HTTP请求授权

vsdwdz23  于 2022-12-25  发布在  Java
关注(0)|答案(1)|浏览(147)

我得到403禁止从库存中删除一个项目,以及在数据库中创建一个新的资源,下面是我的配置和我写的控制器。

Web安全配置类:

package com.inventoryservice.config;

import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authorization.AuthorityAuthorizationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("test")
                .password("test_pass")
                .roles("ADMIN")
                .and()
                .withUser("store")
                .password("store_pass")
                .roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests()
                    .antMatchers(HttpMethod.DELETE, "/items-management").hasRole("ADMIN")
                    .antMatchers(HttpMethod.POST, "/items-management").hasAnyRole("ADMIN","USER")
                    .antMatchers(HttpMethod.GET, "/items-management").permitAll()
                .anyRequest().authenticated();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}

库存管理员:

它将所有端点配置为从服务获取数据库记录

package com.inventoryservice.controller;

import com.inventoryservice.dto.request.InventoryRequestDto;
import com.inventoryservice.dto.response.InventoryItemDto;
import com.inventoryservice.dto.response.InventoryResponseDto;
import com.inventoryservice.entity.Inventory;
import com.inventoryservice.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/items-management")
public class InventoryController {

    private ItemService itemService;

    @Autowired
    public InventoryController(ItemService itemService) {
        this.itemService = itemService;
    }

    @GetMapping
    public ResponseEntity<InventoryResponseDto> getItems() {
        return new ResponseEntity(
                InventoryResponseDto.builder()
                        .lines(itemService.getItems())
                        .build()
                , HttpStatus.OK
        );
    }

    @PostMapping
    public ResponseEntity<InventoryResponseDto> create(@RequestBody InventoryRequestDto inventory) {
        return new ResponseEntity(
                InventoryResponseDto
                        .builder()
                        .lines(itemService.create(inventory.getLines()))
                        .build()
                , HttpStatus.CREATED
        );
    }

    @DeleteMapping
    public ResponseEntity delete(@RequestBody InventoryItemDto inventoryItemDto) {
        itemService.deleteItems(
                inventoryItemDto.getItemIds()
        );
        return ResponseEntity.ok(inventoryItemDto);
    }
}
mzsu5hc0

mzsu5hc01#

我之所以遇到这个问题,是因为Spring Security默认启用了防止跨站点请求伪造(CSRF)攻击的功能,该功能旨在诱骗用户在经过身份验证的应用程序中执行特定操作。
CSRF保护是为了防止不希望的变异行为,因此你的POST请求失败。有关CSRF的更多信息,当有理由禁用CSRF保护时,请参阅文档。
现在,为了测试您的端点,您可以禁用CSRF,如下所示:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests()
        .antMatchers(HttpMethod.DELETE, "/items-management").hasRole("ADMIN")
        .antMatchers(HttpMethod.POST, "/items-management").hasAnyRole("ADMIN","USER")
        .antMatchers(HttpMethod.GET, "/items-management").permitAll()
        .anyRequest().authenticated()
        .csrf().disable();   // <- add this line
}

相关问题