如何正确使用 Spring Security 中的 hasRole? [英] How to use hasRole in Spring Security properly?

查看:24
本文介绍了如何正确使用 Spring Security 中的 hasRole?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现的是保护一个只有一个角色可以访问的 url,当我尝试添加 .hasRole(USER") 时,另一个角色仍然可以访问它.这是我的做法:

hi what i trying to achieve is to protect a url that only one role can access to it, when i try add .hasRole("USER"), still the other role can access it. Here is how i do it :

这是我的控制器:

@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 安全配置的样子:

i want to protect @GetMapping("/something") only for ROLE_ADMIN, here is how my Spring Security Configuration looked like :

@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;
    }
}

这是我实现 UserDetailsS​​ervice 类的服务:

and here is my service that implements UserDetailsService class :

@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());
    }
}

这是我的数据库角色数据:

and here is my database role data :

如你所见,我有 ROLE_USER 和 ROLE_ADMIN

as you can see i have ROLE_USER and ROLE_ADMIN

这是我加入的数据库

** 我刚刚更新了我的问题,我已经回答了一半的问题,请阅读下面我的回答以查看最新问题

** i just updated my question and i have answer of half of my issue, please read my answer below to see the latest issue

推荐答案

在 spring security 中,最严格的规则首先被定义,因此你的配置应该是这样的

In spring security the most restrictive rules are defined first, therefore your configuration should look like this

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic();
    http.authorizeRequests()
            .antMatchers(HttpMethod.GET,"/**/something").hasRole("USER")
            .antMatchers("/**").authenticated()               
            .and().httpBasic().and().csrf().disable();
}

这篇关于如何正确使用 Spring Security 中的 hasRole?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆