Spring Boot + JWT + Kotlin:登录URL 403

时间:2018-03-25 16:58:20

标签: spring-mvc spring-boot spring-security kotlin jwt

关注此文:https://auth0.com/blog/developing-restful-apis-with-kotlin/

做一个家庭成长的auth,文章的第二部分。

当我尝试POST到登录URL时,我收到403错误。

这是我的SignUpController

package io.bss.api.controller

import io.bss.api.model.User
import io.bss.api.repository.UserRepository
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping

@Controller
@RequestMapping("/sign-up")
class SignUpController(val userRepository: UserRepository, val bCryptPasswordEncoder: BCryptPasswordEncoder) {
    @PostMapping()
    fun signUp(@RequestBody user: User) {
        user.password = bCryptPasswordEncoder.encode(user.password)
        userRepository.save(user)
    }
}

我的网络安全类:

package io.bss.api.security

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpMethod
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder

@Configuration
@EnableWebSecurity
open class WebSecurity(val userDetailsService: UserDetailsService) : WebSecurityConfigurerAdapter() {

    @Bean
    fun bCryptPasswordEncoder(): BCryptPasswordEncoder {
        return BCryptPasswordEncoder()
    }

    override fun configure(http: HttpSecurity) {
        http.csrf().disable().authorizeRequests()
                .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(JWTAuthenticationFilter(authenticationManager()))
                .addFilter(JWTAuthorizationFilter(authenticationManager()))
    }

    override fun configure(auth: AuthenticationManagerBuilder?) {
        auth!!.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder())
    }
}

我看到这篇文章是在2017年6月写的,所以也许春季启动中的某些内容发生了变化?这是我第一次使用它,所以我不知道。

1 个答案:

答案 0 :(得分:1)

Problem is you're trying touse @Controller annotation while using REST.

You have 2 options here:

  1. Annotate your class as @RestController
  2. Annotate each method in your controller with @ResponseBody, but you will need to return something then.