java - Spring 安全: issues 403 after authorization with single granted

标签 java spring spring-boot spring-mvc spring-security

使用过 Spring Boot 2 + Spring Security Starter。

授权用户,但由于某种原因给出错误 403。

我尝试以不同的方式进行配置,但不起作用。

授权成功后(loadUserByUsername方法工作正常),它在所有带有/admin 前缀的页面上显示 403,在授权之前,切换到任何带有此前缀的页面都会导致重定向到/login

@Controller
public class AdminController {
    @RequestMapping(value = "/admin", method = {GET, POST})
    public String adminMainPage() {
        return "redirect:/admin/article";
    }
}

@Controller
@RequestMapping("/admin/article")
public class ArticleController {
  @RequestMapping(value = "", method = {GET, POST})
  public ModelAndView indexAdminPage(...){
  ...
  }
}

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements UserDetailsService {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .userDetailsService(this)
                .authorizeRequests()
                .antMatchers("/", "/login",
                        "/login*", "/assets/**", "/lib/**", "/page.scripts/*").permitAll()
                .antMatchers("/admin/**").hasAnyRole("ADMIN")
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .usernameParameter("login")
                .passwordParameter("password")
                .successForwardUrl("/admin")
                .permitAll()
                .and()
                .logout()
                .deleteCookies("JSESSIONID")
                .permitAll();
    }

    private Collection<? extends GrantedAuthority> adminGrantedAuthoritySet = new HashSet<>() {{
        add(new SimpleGrantedAuthority("ADMIN"));
    }};

    private final UserRepository userRepository;

    public WebSecurityConfig(UserRepository userRepository ) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
        Optional<UserEntity> optionalUser = userRepository.findByLogin(login);
        if (optionalUser.isEmpty()) {
            throw new UsernameNotFoundException("User by login '" + login + "' not found");
        } else {
            UserEntity userEntity = optionalUser.get();
            return new User(login, userEntity.getPassword(), adminGrantedAuthoritySet);
        }
    }
}

最佳答案

在 Spring Security 中,角色权限之间是有区别的。
角色是一个权限,前缀为“ROLE_”。在此示例中,权限“ROLE_ADMIN”与角色“ADMIN”相同。

您将管理员authorities设置为new SimpleGrantedAuthority("ADMIN")列表,但您限制对.hasAnyRole("ADMIN"的访问“)

您需要更改其中一项配置。
如果您使用 .hasAnyRole("ADMIN"),则应更改管理 authorities 列表以使用 new SimpleGrantedAuthority("ROLE_ADMIN")
否则,如果您希望列表为 new SimpleGrantedAuthority("ADMIN"),那么您应该使用 .hasAnyAuthority("ADMIN")

关于java - Spring 安全: issues 403 after authorization with single granted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59023358/

相关文章:

java - Maven:如何将现有的maven项目拆分为不同的项目?

java - 使用 JTDS 在 Spring Boot 中配置 HikariCP

java - 带有 Spring Data REST 的不同 REST API 的多个调度程序 servlet 的 Spring Boot (JAR)

javaBean 无法检测类属性

java - 为什么\u000a 是坏字符?

java - spring如何调用websocket服务器向客户端发送消息

java - Mockito 无法注入(inject)模拟

java - 将 PHP 中的 SHA1 哈希值转换为 JAVA 代码

java - 如何将 Class 对象用作参数化类型?

java - 需要澄清,这被认为是内联类还是回调还是其他什么?