在Spring中使用角色:boot + Spring安全性。我该如何控制谁能看到什么?

时间:2018-02-19 21:02:22

标签: spring-boot spring-security

我目前有一个正常运行的弹簧:启动Web应用程序,用户可以登录并且用户有角色。 (关系正常运作)。我正在努力理解的是,如何控制谁可以做什么?例如,如何进行设置,以便管理员只能访问某个网页。

以下是一个示例,我只希望管理员能够访问此“匹配”页面:

@GetMapping("/competition/{competitors}")
public String match(ModelMap map, @PathVariable(value = "competitors") String competitors, Principal principal) {

    String[] parts = competitors.split("-");
    String part1 = parts[0]; 
    String part2 = parts[1];

    map.addAttribute("part1", part1);
    map.addAttribute("part2", part2);
    return "match";
}

Match.html:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Match</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p th:text="'Match of ' + ${part1} + ' and ' + ${part2}" />
</body>
</html>

我的配置方法:

    @Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
                .antMatchers(
                        "/registration",
                        "/js/**",
                        "/css/**",
                        "/img/**",
                        "/webjars/**").permitAll()
                .anyRequest().authenticated()
            .and()
                .formLogin()
                    .loginPage("/login")
                        .permitAll()
            .and()
                .logout()
                    .invalidateHttpSession(true)
                    .clearAuthentication(true)
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                    .logoutSuccessUrl("/login?logout")
            .permitAll();
}

1 个答案:

答案 0 :(得分:0)

http.authorizeRequests()
        .antMatchers("/competition/**").hasRole("Your role here")

/competition/**下的任何内容都必须包含Your role

添加到您的代码段

http
     .authorizeRequests()
         .antMatchers(
                 "/registration",
                 "/js/**",
                 "/css/**",
                 "/img/**",
                 "/webjars/**").permitAll()
         .anyRequest().authenticated()
     .and()
         .formLogin()
             .loginPage("/login")
                 .permitAll()
     .and()
        .authorizeRequests()
            .antMatchers("/competition/**").hasRole("Your role here")
     .and()
         .logout()
             .invalidateHttpSession(true)
             .clearAuthentication(true)
             .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
             .logoutSuccessUrl("/login?logout")
     .permitAll();