首页 > 解决方案 > 字符串引导 REST 安全错误:类型=禁止,状态=403

问题描述

这个项目我使用过 Spring boot、安全认证、JPA 和 REST

这给了我 403 错误,这是角色基础错误。试了2天没解决,求大神帮忙。

我在这里分享代码。

这是我的安全配置类具有基于角色的 /hello 所有用户和 /admin/all 和 /admin/add 管理员用户。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(encodePsw());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/api/secure/admin/**").hasRole("ADMIN").antMatchers("/api/secure/**")
            .hasAnyRole("USER", "ADMIN").anyRequest().authenticated().and().formLogin().permitAll();
}

@Bean
public BCryptPasswordEncoder encodePsw() {
    return new BCryptPasswordEncoder();
}

}

这是我的控制器类有 3 个方法,即所有用户的 /hello 和 /admin/all 和 /admin/add 的 3 个基于角色的方法。

@RestController
@RequestMapping("/api/secure")
public class AdminController {

@Autowired
private UserRepository userRepo;

@Autowired
private BCryptPasswordEncoder passEncp;

@RequestMapping(value = "/hello")
public String hello() {
    return "Hello..";
}

//@PreAuthorize("hasAnyRole('ADMIN')")
@RequestMapping(value = "/admin/add", method = RequestMethod.POST)
public String addUserByAdmin(@RequestBody User user) {
    user.setPassword(passEncp.encode(user.getPassword()));
    userRepo.save(user);
    return "Add User Successfully";
}

//@PreAuthorize("hasAnyRole('ADMIN')")
@GetMapping("/admin/all")
public String securedHello() {
    return "Secured Hello";
}
}

这是角色 bean

@Entity
@Data
public class Role {
@Id
@GeneratedValue
private int roleId;
private String role;
}

此用户 Bean

@Entity
@Setter
@Getter
public class User {
@Id
private int userId;
private String username;
private String password;
private String email;
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinTable(name="user_role", joinColumns = @JoinColumn(name="user_id"), inverseJoinColumns = @JoinColumn(name="role_id"))
private Set<Role> roles;
}

用户存储接口

public interface UserRepository extends JpaRepository<User, Integer> {

User findByUsername(String username);

}

CustomUserDetails 类我认为问题出在这部分。我有 ROLE_USER 之类的保存角色,ROLE_ADMIN 也尝试不使用 ROLE_

@Getter
@Setter
public class CustomUserDetails implements UserDetails {

private User user;

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return user.getRoles().stream().map(role -> new SimpleGrantedAuthority(""+role))
            .collect(Collectors.toList());
}

@Override
public String getPassword() {
    // TODO Auto -generated method stub
    return user.getPassword();
}

@Override
public String getUsername() {
    // TODO Auto-generated method stub
    return user.getUsername();
}

服务类 CustomUserDetailsS​​ervice

@Service
public class CustomUserDetailsService implements UserDetailsService {

@Autowired
private UserRepository userRepo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepo.findByUsername(username);
    CustomUserDetails userDetails = null;
    if(user!=null) {
        userDetails = new CustomUserDetails();
        userDetails.setUser(user);
    }else {
        throw new UsernameNotFoundException("User not found with name "+username);
    }
    return userDetails;
}
}

我有另一个正在运行的具有不同 URL 映射的控制器类

标签: spring-bootspring-security-rest

解决方案


WebSecurityConfigurerAdapter 有一个重载的配置消息,该消息将 WebSecurity 作为参数,在要忽略的请求上接受 ant 匹配器。

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/hello");
}

对于所有用户,您可以忽略基于 /hello 的 url。


推荐阅读