spring-boot - 字符串引导 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();
}
服务类 CustomUserDetailsService
@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 映射的控制器类
解决方案
WebSecurityConfigurerAdapter 有一个重载的配置消息,该消息将 WebSecurity 作为参数,在要忽略的请求上接受 ant 匹配器。
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/hello");
}
对于所有用户,您可以忽略基于 /hello 的 url。
推荐阅读
- reactjs - 在 React / Gatsby 中滚动时,在哪里放置 componentDidMount 以更改链接导航栏颜色?
- android - 测试室迁移。在资产文件夹中找不到架构文件
- r - 使用 div 标签获取级别指示器
- java - 具有继承和 JPA 的 Lombok @Builder
- rest - 有什么方法可以在不使用身份验证选项的情况下验证调度任务中的 xdmp:http-put 函数吗?
- c# - .Net Core 3.1 导入 WSDL 错误 - 如何解决?
- linux - 如何从 Bash shell 的输出中截断字符串?
- sql - 如何在 SQL 中使用 JOIN 从两个表的组合中找到 SUM (product_price)
- angular - 在升级到 Angular 9 期间,Typescript 编译中缺少 main.ts 和 polyfills.ts
- javascript - 如何允许 setState 在整个应用程序中使用上下文