先放上github的鏈接GraphQL demo
pom
<!-- graphQL依賴-->
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>5.10.0</version>
</dependency>
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>altair-spring-boot-starter</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphiql-spring-boot-starter</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>playground-spring-boot-starter</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
GraphQL要實現(xiàn)權(quán)限認(rèn)證主要是依靠directive
先創(chuàng)建一個directive
public class RoleDirective implements SchemaDirectiveWiring {
@Override
public GraphQLFieldDefinition onField(SchemaDirectiveWiringEnvironment<GraphQLFieldDefinition> env) {
List<String> targetRoles = (List<String>) env.getDirective().getArgument("roles").getValue();
DataFetcher originDataFetcher = env.getFieldDataFetcher();
env.setFieldDataFetcher(new DataFetcher() {
@Override
public Object get(DataFetchingEnvironment environment) throws Exception {
// 從線程上下文中獲取用戶身份信息
AuthContextHolder authContextHolder = new AuthContextHolder();
AuthContext authContext = authContextHolder.getContext();
// 權(quán)限認(rèn)證邏輯
if (targetRoles.contains(authContext.getRole())) {
// 用戶身份在給定的role列表中,調(diào)用dataFetcher返回數(shù)據(jù)
return originDataFetcher.get(environment);
} else {
// 用戶身份不在role列表中,直接返回null
return null;
}
}
});
return env.getElement();
}
}
接下來就是對directive進行配置
// 像這樣添加roleDirective,如果要添加多個就創(chuàng)建多個類似的Bean
@Bean
public SchemaDirective myCustomDirective() {
return new SchemaDirective("role", new RoleDirective());
}
.graphqls文件寫法
directive @role(roles:[String!]!) on FIELD_DEFINITION
type Book {
id: ID
name: String
pageNum: Int @role(roles:["ADMIN"])
authorId: ID @role(roles:["ADMIN"])
author:Author
}
至此,對GraphQL的權(quán)限認(rèn)證配置就完成了。
AuthContextHolder的實現(xiàn)可以看這片文章Java權(quán)限認(rèn)證實現(xiàn)原理