【发布时间】:2021-04-07 20:19:16
【问题描述】:
嗨,我试图实现的是保护一个只有一个角色可以访问它的 url,当我尝试添加 .hasRole("USER") 时,其他角色仍然可以访问它。这是我的做法:
这是我的控制器:
@RestController
@RequestMapping("/couponapi")
public class CouponController {
@Autowired
CouponRepository couponRepository;
@PostMapping("/coupons")
public Coupon save(@RequestBody Coupon coupon) {
return couponRepository.save(coupon);
}
@GetMapping("/coupons/{code}")
public Coupon findByCode(@PathVariable("code") String code) {
return couponRepository.findByCode(code);
}
@GetMapping("/something")
public Coupon findByCodeX() {
return couponRepository.findByCode("SUPERSALE");
}
}
我只想为 ROLE_ADMIN 保护@GetMapping("/something"),这是我的 Spring 安全配置的样子:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailServiceImpl userDetailService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic();
http.authorizeRequests()
.antMatchers(HttpMethod.GET,"/couponapi/coupons/**").hasRole("USER")
.antMatchers(HttpMethod.POST,"/couponapi/coupons/**").hasRole("USER")
.antMatchers("/couponapi/something").hasRole("ADMIN")
.antMatchers("/**").authenticated()
.and().httpBasic().and().csrf().disable();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
这是我的角色类:
@Data
@EqualsAndHashCode(of = "id")
@ToString(of = { "id" })
@Entity
public class Roles implements GrantedAuthority {
private static final long serialVersionUID = -7314956574144971210L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany(mappedBy = "roles")
private Set<Users> users;
@Override
public String getAuthority() {
return null;
}
}
这是我实现 UserDetailsService 类的服务:
@Service
public class UserDetailServiceImpl implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Users users = userRepository.findByEmail(s);
if(users == null) {
throw new UsernameNotFoundException("Username Not Found");
}
return new User(users.getEmail(), users.getPassword(), users.getRoles());
}
}
这是我的数据库角色数据:
如你所见,我有 ROLE_USER 和 ROLE_ADMIN
这是我加入的数据库
** 我刚刚更新了我的问题,我已经回答了一半的问题,请阅读下面的答案以查看最新问题
【问题讨论】:
-
你可以尝试将
hasRole更改为hasAuthority,没有任何意义,但如果你可以尝试 -
当然,我试试这个 .hasAuthority("ROLE_USER") 还是一样的结果,不工作
-
好的,请在
CouponController中添加一个参数Authentication并检查其中的所有字段是什么 -
你的意思是这样吗? @GetMapping("/something") public Coupon findByCodeX(Authentication auth) { return couponRepository.findByCode("SUPERSALE"); } 我如何检查其中的所有字段人口?
-
请这样
标签: java spring spring-boot spring-security spring-data