我为 endpoints 设置WebSecurityConfig属于GraphQl endpoints .
这是我的代码:
@Configuration
@EnableWebSecurity
class WebSecurityConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/users?{query}")
/*
the "#" resolves the variable in the path, "{id}" in this case.
the "@" resolves a current bean.
*/
.access("hasRole('USER') and @userSecurity.checkId(authentication, #query)")
.antMatchers("/**").hasRole("ADMIN")
.anyRequest().denyAll()
.and()
.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
}
@Bean
fun userSecurity() : UserSecurity {
return UserSecurity()
}
}
/**
* Custom check. Not only we need a user authenticated, but we also
* need to make sure that a user can only access his/her data, and not the
* one of the other users
*/
class UserSecurity{
@Autowired
private lateinit var userRepository: UserRepository
fun checkId(authentication: Authentication, query: String) : Boolean{
val current = (authentication.principal as UserDetails).username
print("\n\n\n")
println(query)
return try {
userRepository.findById(current).get().username == current
} catch (e : Exception){
false
}
}
}
我想要做的是从URL中提取GraphQL查询,并使用它来验证查询是否合法 .
F.eks . 如果JonhDoe尝试对其他一些用户数据进行查询 . 我们想要检查查询中的用户是否与spring boot认证的用户相同,然后允许或不允许进行请求 .
我在微服务架构中使用redis