gpt4 book ai didi

Spring + GraphQL - 可选授权

转载 作者:行者123 更新时间:2023-12-04 13:44:53 27 4
gpt4 key购买 nike

我目前正在使用 Spring Boot StarterGraphQL Java Tools在我的 Spring 应用程序中使用 GraphQL。只要我授权 graphql 端点,它就可以与我的授权过滤器配合使用。现在我想向公众开放某些突变或查询(因此不需要授权),这就是我绊倒的地方。我如何打开 graphql 端点但仍然能够使用 @PreAuthorize方法级授权的 Spring 安全性注释?换句话说:是否可以对端点进行“可选”授权?

这是我的配置:

@Override
protected void configure(HttpSecurity http) throws Exception {
log.debug("configureHttpSecurity");

// Only authorize the request if it is NOT in the permitAllEndpoints AND matches API_ROOT_URL OR
// MESSAGING_ROOT_URL
List<RequestMatcher> requestMatchers = new ArrayList<>();
requestMatchers.add(new SkipPathRequestMatcher(permitAllEndpointList, API_ROOT_URL));
requestMatchers.add(new AntPathRequestMatcher(MESSAGING_ROOT_URL));
OrRequestMatcher apiMatcher = new OrRequestMatcher(requestMatchers);

http.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(permitAllEndpointList.toArray(new String[0]))
.permitAll()
.and()
.authorizeRequests()
.antMatchers(API_ROOT_URL, MESSAGING_ROOT_URL)
.authenticated()
.and()
.addFilterBefore(new CustomCorsFilter(),
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new AuthenticationFilter(authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new AuthorizationFilter(apiMatcher),
UsernamePasswordAuthenticationFilter.class);
}
apiMatcher是打开某些 REST 端点。
这是我的 AuthorizationFilter :
@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse)
throws AuthenticationException, IOException, ServletException {
try {
String authorization = httpServletRequest.getHeader("Authorization");
if (authorization != null && authorization.startsWith("Bearer ")) {
return getAuthentication(authorization.replace("Bearer ", ""));
}
} catch (ExecutionException e) {
httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN,"The provided token was either not valid or is already expired!");
return null;
} catch (IOException | InterruptedException e) {
httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"There was a problem verifying the supplied token!");
return null;
}
httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Unauthorized");
return null;
}

如果我没有在 attemptAuthentication 结束时发送错误我将能够访问不应打开的 REST 端点。此外,如果我只允许 GraphQL 端点,则不会发生任何授权,因此每个 @PreAuthorize即使我提供了有效的 JWT,也会失败。
可能是我的方法已经是错误的。如果是这种情况,请告诉我。

最佳答案

我通过使用两个安全配置解决了这个问题。一个用于我的 REST api,它已强制执行身份验证/授权。另一个有一个可选的授权过滤器,它只使用存在的 token 。
现在唯一的缺点是所有的查询和变异默认都是公开的,需要一个 @PreAuthorize要关闭的注释。

关于Spring + GraphQL - 可选授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50541783/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com