基于URL参数的Spring Security REST API角色

时间:2017-01-09 00:36:38

标签: java spring rest spring-security

我在Spring Boot中使用Spring Security和OAuth2编写了一个REST API。资源以这种方式得到保护:

## Data
library(ggplot2)
library(plyr)
library(gtable)
library(grid)

params <- paste0("param", 1:3)
medians <- data.frame(value = c(seq(0.1,0.6, by = 0.1), rep(NA, 3)),
                      model = rep(c("M1", "M2", "M3"), each = 3),
                      parameter = rep(paste0("param", 1:3), 3))
m3_posterior <- data.frame(value = runif(900, 0.2, 0.7), 
                           model = "M3", 
                           parameter = rep(params, each = 3)) 
m3_stats <- ddply(m3_posterior, .(parameter), summarize,
                 lower = quantile(value, 0.025), 
                 upper = quantile(value, 0.975) ) 
confs <- data.frame(lower = c(seq(0.05, 0.55, by = 0.1), m3_stats$lower),
                    upper = c(seq(0.15, 0.65, by = 0.1), m3_stats$upper),
                    model = rep(c("M1", "M2", "M3"), each = 3),
                    parameter = rep(params, 3))                        

print_list <- list()

for (param in 1 : length(params)) {
  gg_medians <- subset(medians, parameter == params[param])
  gg_confs <- subset(confs, parameter == params[param])
  gg_post <- subset(m3_posterior, parameter == params[param])

  p1 <- ggplot(gg_medians, aes(model)) + 
        geom_bar(aes(y = value), stat="identity", fill = "white", colour = "black") +
        geom_errorbar(data = gg_confs, 
                      aes(ymax=upper, ymin=lower)) +
        scale_y_continuous(limits=c(0,1)) + labs(x=params[param])

  p2 <- ggplot(gg_post, aes(parameter)) +
        geom_violin(aes(y = value), width=1.5, fill = NA) +
        geom_errorbar(data = subset(gg_confs, model == "M3"),
            aes(ymax=upper, ymin=lower), colour = "red") +
        scale_y_continuous(limits=c(0,1)) + labs(x=params[param]) + 
        theme_bw() +
        theme(panel.grid = element_blank(),
              panel.border = element_blank(),
              panel.background = element_rect(fill = "transparent"))

  p2_grob <- ggplotGrob(p2)
  panel = gtable_filter(p2_grob, "panel")   # Select plot panel from p2

  print_list[[param]] <- p1 + annotation_custom(grob = panel,
                           xmin = 2.5, xmax = 3.5,
                           ymin = -Inf, ymax = Inf)      # Put the panel it into p1
}

# From print_list:
#    separate y-axis and panel columns in print_list[[1]]
#    and get panel columns from print_list[[2]] and print_list[[3]]
g1 = ggplotGrob(print_list[[1]])   
axis = g1[, 2:3]                  # Get the y axis
g1 = g1[, -c(1:3)]                # Get the panel & columns to the right for param1
g2 = ggplotGrob(print_list[[2]])
g2 = g2[, -c(1:3)]                # Get the panel & columns to the right for param2
g3 = ggplotGrob(print_list[[3]])
g3 = g3[, -c(1:3)]                # Get the panel & columns to the right for param3

# Set up gtable 5 columns X 1 row
#    5 columns: left margin, width of y axis, width of three panels 
#    1 row
gt = gtable(unit.c(unit(5.5, "pt"), sum(axis$widths), unit(c(1,1,1), "null")), unit(1, "null"))

# Populate the gtable, and draw the plot
gt = gtable_add_grob(gt, list(axis, g1, g2, g3), t = 1, l = 2:5)
grid.newpage()
grid.draw(gt)

我想基于项目引入API的新部分,其中权限是细粒度的。让我们考虑一个打印项目配置的简单端点。

@Override
public void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/api/v1/security/**").hasRole("ADMIN");
}

如何将资源服务器配置为仅允许具有角色GET /api/v1/project/{projectId}/config 的用户访问,而无需手动指定所有项目?

此外,如果此机制具有特定名称,请在评论中告诉我,我可以更改问题标题。

1 个答案:

答案 0 :(得分:7)

您可以在授权表达式中使用路径值。

根据Path Variables in Web Security Expressions,您应该编写自定义授权逻辑。

public class WebSecurity {
  public boolean checkUserHasAccessToProjectId(Authentication authentication, int projectId) {
    // here you can check if the user has the correct role
    // or implement more complex and custom authorization logic if necessary 
  }
}

然后在Java安全配置中,您可以引用此方法并将相关路径片段的值传递给它。

http.authorizeRequests()
  .antMatchers("/api/v1/project/{projectId}/config")
  .access("@webSecurity.checkUserHasAccessToProjectId(authentication,#projectId)")
  ...
相关问题