如何使用角色正确保护端点?

js4nwp54  于 2021-09-30  发布在  Java
关注(0)|答案(0)|浏览(272)

关于这一点,我读过其他一些主题,例如:
如何正确使用spring security中的hasrole?
按角色保护特定终结点
我试着改变:

  1. .antMatchers("/addresses/**").hasAnyAuthority("ROLE_ADMIN", "ROLE_USER").antMatchers("/addresses/**").hasAnyRole("ADMIN", "USER") 2. http.httpBasic() 在受保护void的顶部和底部配置(最终httpsecurity http)
    3种组合:
    @安全的
    @预授权(“hasanyauthority('role\u admin','role\u user'))
    我正在用两个实体“user”和“address”制作一个简单的RESTAPI/用户对任何人都可用(除了delete:/users/{id}/user),而/addresses仅适用于角色为admin或user的已登录用户,但每次我尝试连接到该端点时,响应都是403-禁止的。
    ps:似乎我的应用程序没有正确读取密码(当我在postman im中更改密码时,我没有得到401-未经授权,但用户名的相同操作给了我401)
    地址控制器
@AllArgsConstructor
@RequestMapping("/addresses")
public class AddressController {

    private final AddressService addressService;

    @GetMapping
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_USER')")
    public List<Address> findAll() {
        return addressService.findAll();
    }

    @GetMapping("/{id}/address")
    public Address findAddressById(@PathVariable Long id) {
        return addressService.findById(id);
    }

    @PostMapping
    public ResponseEntity<Address> newAddress(@RequestBody Address newAddress) {
        return addressService.save(newAddress);
    }

    @Secured("ROLE_ADMIN")
    @DeleteMapping("/{id}/address")
    public void deleteAddressById(@PathVariable Long id) {
        addressService.deleteById(id);
    }

用户控制器

@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @GetMapping
    public List<User> findAll() {
        return userService.findAll();
    }

    @GetMapping("/{id}/user")
    public User findUserById(@PathVariable Long id) {
        return userService.findById(id);
    }

    @ExceptionHandler
    public ResponseEntity<String> exceptionHandler(userNotFoundException e) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
                .body(e.getMessage());
    }

    @PostMapping()
    public ResponseEntity<User> newUser(@RequestBody User newUser) {

        if (newUser.equals(null)) {
            throw new RuntimeException("You must define new user");
        } else {
            return userService.save(newUser);
        }
    }

    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @DeleteMapping("/{id}/user")
    public void deleteUserById(@PathVariable Long id) {
        userService.deleteById(id);
    }
}

安全配置

@Configuration
@AllArgsConstructor
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        prePostEnabled = true,
        securedEnabled = true,
        jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private MyUserDetailsService myUserDetailsService;

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.httpBasic();
        http.authorizeRequests()
                .antMatchers("/addresses/**").hasAnyAuthority("ROLE_ADMIN", "ROLE_USER")
                .antMatchers(HttpMethod.DELETE, "/addresses/**").hasRole("ADMIN")
                .antMatchers("/users/**").permitAll()
                .antMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN")
                .and()
                .formLogin()
                .and()
                .logout()
                .and()
                .csrf().disable();
    }

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

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

我的用户详细信息服务

@Service
@AllArgsConstructor
public class MyUserDetailsService implements UserDetailsService {

    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String userName) throws userNotFoundException {
        return userRepository.findByName(userName)
                .map(UserDetailsAdapter::new)
                .orElseThrow(() -> new userNotFoundException(userName + " not found"));
    }
}

用户详细信息适配器

public class UserDetailsAdapter implements UserDetails {

    private final User user;

    public UserDetailsAdapter(final User user) {
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return List.of(new SimpleGrantedAuthority(user.getRole()));
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题