问题
我设法通过Postman获得了身份验证/授权。目前,我正在尝试通过对/ api / authenticate发出发布请求来拨打电话以进行登录。
但是,如果我正在打印AuthenticationManager的实例,则表明该值为空。
我尝试过什么/正在使用什么代码
SecurityConfig类。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
class SecurityConfig : WebSecurityConfigurerAdapter() {
@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
http.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers("/api/authentication/**").permitAll()
.anyRequest().authenticated()
.and()
.addFilter(JwtAuthenticationFilter(authenticationManager()))
.addFilter(JwtAuthorizationFilter(authenticationManager()))
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
}
@Throws(Exception::class)
public override fun configure(auth: AuthenticationManagerBuilder) {
auth.inMemoryAuthentication()
.withUser("user")
.password(passwordEncoder().encode("password"))
.authorities("ROLE_USER")
}
@Bean
fun passwordEncoder() = BCryptPasswordEncoder()
@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
val source = UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration("/**", CorsConfiguration().applyPermitDefaultValues())
return source
}
@Bean(name = [BeanIds.AUTHENTICATION_MANAGER])
@Throws(Exception::class)
override fun authenticationManagerBean(): AuthenticationManager {
return super.authenticationManagerBean()
}
}
我尝试登录的控制器类。
@RestController
@RequestMapping("/api/authentication")
class AuthenticationController() {
@PostMapping
fun logIn(): Authentication? {
val authenticationHelper = AuthenticationHelper();
return authenticationHelper.logIn("user", "password");
}
}
Helper类。
class AuthenticationHelper {
@Autowired
@Qualifier("authenticationManager")
var authenticationManager: AuthenticationManager? = null
fun logIn(username: String, password: String): Authentication? {
println(authenticationManager) // Gives me null
val authenticationToken = UsernamePasswordAuthenticationToken(username, password);
return authenticationManager?.authenticate(authenticationToken);
}
}