拒绝授权用户访问

时间:2019-05-12 00:32:00

标签: spring kotlin spring-security spring-security-oauth2

我正在使用Spring Boot和Kotlin制作REST API。我有一个控制器,可以创建用户实体:

@RequestMapping("/", method = [RequestMethod.POST])
    fun  createUser(@RequestBody userModel: UserModel): ResponseEntity<Void> {
        val username = userModel.mobile
        if (!userService.exists(username)) {
            val user = User(
                    userModel.mobile,
                    "",
                    "",
                    userModel.password!!,
                    userModel.enabled,
                    null
            )
            user.roles.add("ROLE_USER")
            userService.save(user)
        } else throw IllegalAccessException("Пользователь с таким именем уже существует")
        return ResponseEntity
                .created(URI(UserModel(userDetailsServiceImpl.loadUserByUsername(username)).getLink("self").href))
                .build()
    } 

效果很好,但是我需要拒绝为经过身份验证的人创建新用户。 我正在尝试这样做:

override fun configure(http: HttpSecurity) {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/api").not().hasAnyRole("USER", "ADMIN")
                .antMatchers("/api/company").hasAnyRole("USER", "ADMIN")
                .antMatchers("/api/user").hasAnyRole("USER", "ADMIN")
                .antMatchers("/api/admin").hasRole("ADMIN")
    }

但是,即使我已通过身份验证,也可以创建用户。谁能解释我的错误?

我正在使用OAuth2和H2数据库(存储用户实体)。

UPD

再次-如果用户已经创建帐户,我需要拒绝它(用户不能再创建一个帐户)。

0 个答案:

没有答案