【问题标题】:Spring Security for REST APIS not working for some roles [duplicate]REST APIS的Spring Security不适用于某些角色[重复]
【发布时间】:2021-05-05 08:57:34
【问题描述】:

我已经为 API 实现了 Spring Security。所有 api 对于 ADMIN 角色都可以正常工作,但是当我使用其他角色访问时,它会出现 404 错误。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public UserDetailsService userDetailsService() {
        return new CustomUserDetailsService();
    }

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

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService());
        authProvider.setPasswordEncoder(passwordEncoder());

        return authProvider;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/api/**").hasAuthority("ADMIN")
                .antMatchers("/api/repairs/**").hasAuthority("MECHANIC")
                .antMatchers("/api/users/**", "/api/sales-report/**").hasAuthority("MANAGER")
                .antMatchers("/api/bikes/**", "/api/transactions/**", "/api/customers/**", "/api/spareparts/**")
                .hasAuthority("SALESPERSON")
                .anyRequest().authenticated()
                .and()
                .formLogin().defaultSuccessUrl("/swagger-ui/")
                .and()
                .logout().permitAll()
                .and()
                .exceptionHandling().accessDeniedPage("/403")
        ;
    }

}

编辑: 我已经添加了用户详细信息和用户详细信息服务类的自定义实现。

这是我的 UserDetails 自定义实现

public class CustomUserDetails implements UserDetails {

    @Autowired
    private User user;

    public CustomUserDetails() {
    }

    public CustomUserDetails(User user) {
        this.user = user;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<Role> roles = user.getRoles();
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getRole()));
        }
        return authorities;
    }

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

这是 UserDetailsS​​ervice 的自定义实现。

@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByName(username);
        CustomUserDetails customUserDetails = null;
        if (user != null) {
            customUserDetails = new CustomUserDetails();
            customUserDetails.setUser(user);
        } else {
            throw new UsernameNotFoundException("User does not exist with name " + username);
        }
        System.out.println("NAME" + customUserDetails.getAuthorities());
        return customUserDetails;
    }
}

【问题讨论】:

  • 能否请您说明您如何授予用户权限?

标签: spring-boot rest spring-security


【解决方案1】:

如果将来有人遇到这个问题,我已经解决了。我把它改成

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/repairs/**").hasAnyAuthority("ADMIN", "MECHANIC")
                .antMatchers("/users/**", "/sales-report/**").hasAnyAuthority("ADMIN", "MANAGER")
                .antMatchers("/bikes/**", "/transactions/**", "/customers/**", "/spareparts/**")
                .hasAnyAuthority("ADMIN", "SALESPERSON")
                .anyRequest().authenticated()
                .and()
                .formLogin().defaultSuccessUrl("/swagger-ui/")
                .and()
                .logout().permitAll()
                .and()
                .exceptionHandling().accessDeniedPage("/403")
        ;
    }

我更改了配置方法,问题是 .antMatchers("/api/**").hasAuthority("ADMIN") 限制其他角色访问 /api/ 之后的任何内容。

【讨论】:

    猜你喜欢
    • 2019-03-08
    • 2020-12-19
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    • 2016-06-23
    • 2013-10-31
    • 2017-05-23
    相关资源
    最近更新 更多