spring - Spring Boot 安全中的 HTTP 403 禁止错误

标签 spring spring-boot spring-security basic-authentication spring-security-rest

Spring安全配置类

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .cors()
            .and()
            .authorizeRequests()
            .antMatchers("/user", "/login").permitAll()
            .antMatchers("/employee", "/insurance").hasRole("User")
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic()
            .and()
            .csrf().disable();
    }

    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(getPasswordEncoder());
    }
}

UserDetailsS​​ervice 实现类
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = null;
        Set<GrantedAuthority> grantedAuthorities = null;
        try
        {
            user = userService.findByUserName(userName);
            if(user == null)
                throw new UsernameNotFoundException("User " + userName  + " not available");

            grantedAuthorities = new HashSet<>();
            for(Role role: user.getRoles()) {
                grantedAuthorities.add(new SimpleGrantedAuthority(role.getRole().toString()));
            }
        }
        catch(Exception exp) {
            exp.printStackTrace();
        }
        return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), grantedAuthorities);
    }
}

员工休息 Controller 类
@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private InsuranceService insuranceService;

    @PostMapping("/employee")
    public ResponseEntity<Employee> create(@RequestBody Employee employee) throws Exception {
        employee = employeeService.create(employee);
        return new ResponseEntity<Employee>(employee, HttpStatus.CREATED);
    }

    @PutMapping("/employee")
    public ResponseEntity<Employee> update(@RequestBody Employee employee) throws Exception {
        employee = employeeService.update(employee);
        return new ResponseEntity<Employee>(employee, HttpStatus.OK);
    }

    @DeleteMapping("/employee/{id}")
    public ResponseEntity<String> delete(@PathVariable("id") long id) throws Exception {
        employeeService.delete(id);
        return new ResponseEntity<String>("Employee deleted successfully", HttpStatus.OK);
    }

    @GetMapping("/employee/{id}")
    public ResponseEntity<Employee> findEmployeeDetails(@PathVariable("id") long id) throws Exception {
        Employee employee = employeeService.findById(id);
        return new ResponseEntity<Employee>(employee, HttpStatus.OK);
    }

    @GetMapping("/employee")
    public ResponseEntity<List<Employee>> findAll() throws Exception {
        List<Employee> employees = employeeService.findAll();
        return new ResponseEntity<List<Employee>>(employees, HttpStatus.OK);
    }
}

对于通过 postman 提交给 的任何 HTTP 方法(POST/GET/PUT)请求,我收到 403 禁止错误/员工网址
{
    "timestamp": "2019-09-17T05:37:35.778+0000",
    "status": 403,
    "error": "Forbidden",
    "message": "Forbidden",
    "path": "/hr-core/employee"
}

即使我在 POSTMAN 中 HTTP 请求的基本身份验证 header (授权)中发送正确的用户名和密码,我也收到此错误。此用户还具有 USER 和 ADMIN 角色来访问 /员工 REST 端点。我已禁用 CSRF 在 http 安全中。

我该如何解决这个错误?

最佳答案

在 Spring Security 中, 之间存在差异。角色权威 .虽然权限可以是任何东西,但角色是以 ROLE_ 开头的权限子集。 .

假设您拥有以下权限:

GrantedAuthority authority1 = new SimpleGrantedAuthority("User");
GrantedAuthority authority2 = new SimpleGrantedAuthority("ROLE_Admin");

在这种情况下,authority1不包含角色,而 authority2是因为它以 ROLE_ 为前缀.

这意味着,如果您使用 hasRole("User") ,您将无权访问,因为它未定义为角色。 hasRole("Admin")另一方面会起作用。

要解决此问题,您有两种选择:
  • 确保您的角色确实以 ROLE_ 为前缀.如果您不以这种方式将它们存储在您的数据库中,您可以修改您的 UserDetailsServiceImpl :

    String roleName = "ROLE_" + role.getRole().toString();
    grantedAuthorities.add(new SimpleGrantedAuthority(roleName));
    
  • 或者,您可以使用 hasAuthority("User")反而:

    // ...
    .antMatchers("/employee", "/insurance").hasAuthority("User")
    // ...
    
  • 关于spring - Spring Boot 安全中的 HTTP 403 禁止错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57968149/

    相关文章:

    spring-security - Spring Security 和多个 ldap 配置

    java - 使用 Spring Boot 启动 tomcat 时出现 NotReadablePropertyException

    java - 具有单向关系的 Json 和 Jackson stackoverflow 循环

    java - 根据 spring Activity 配置文件修改映射路径

    java - 使用 BrowserLauncher 2 打开 URl 时,Acegi 抛出 AuthenticationCredentialsNotFoundException

    java - 如何从方法中提取依赖于类上下文的变量以避免重复代码?

    java - 何时以及如何创建 cglib-proxied 组件实例

    mysql - MyBatis 参数传递

    java - 跨两个数据库访问数据

    spring - Tomcat 7 Spring 应用程序 IntelliJ IDEA 10.5 OutOfMemoryError : PermGen space