我有一个spring boot项目,我在上面设置了spring安全性来处理身份验证,如下所示(不同的类在不同的文件中)。
@Configuration
@EnableWebSecurity
class SecurityConfiguration(
private val userAuthenticationService: UserAuthenticationService)
: WebSecurityConfigurerAdapter(){
@Throws(Exception::class)
override fun configure(httpSecurity: HttpSecurity) {
httpSecurity
.cors()
.and()
.csrf().disable()
.authorizeRequests()
//.antMatchers("/#/login").permitAll()
.antMatchers(HttpMethod.POST,Constants.USERS_BASE_PATH).permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.formLogin()
//.loginPage("/#/login")
.loginProcessingUrl("/v0/login")
.permitAll()
.and()
.logout()
.logoutUrl("/v0/logout")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
.permitAll();
}
override fun configure(auth: AuthenticationManagerBuilder?) {
auth?.userDetailsService(userAuthenticationService)
}
@Bean
fun getPasswordEncoder(): PasswordEncoder? {
return BCryptPasswordEncoder()
}
}
@Service
class UserAuthenticationService(private val userRepository: UserRepository) : UserDetailsService{
override fun loadUserByUsername(username: String?): UserDetails {
val user = userRepository.findByUsername(username!!)
return UserAuthenticationDetails(user.username, user.password)
}
}
问题是,当我执行登录操作(如下)时,它返回一个HTML表单以执行带有200状态代码的登录,并且响应不包含“ Set-Cookie”标头,该标头包含用于以下请求的cookie
POST /v0/login HTTP/1.1
Host: localhost:8080
Authorization: Basic dXNlciAxOjEyMzQ1
Content-Type: application/x-www-form-urlencoded
username=user%201&password=12345
这是HTML响应消息:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Please sign in</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet" crossorigin="anonymous"/>
</head>
<body>
<div class="container">
<form class="form-signin" method="post" action="/v0/login">
<h2 class="form-signin-heading">Please sign in</h2>
<div class="alert alert-danger" role="alert">Result must not be null!</div> <p>
<label for="username" class="sr-only">Username</label>
<input type="text" id="username" name="username" class="form-control" placeholder="Username" required autofocus>
</p>
<p>
<label for="password" class="sr-only">Password</label>
<input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
</p>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div>
</body></html>
我已经尝试过Spring安全配置的几种变体,但是我肯定缺少一些东西。 返回带有正确cookie的“ Set-Cookie”标头的原因是,如果我尝试任何其他终结点并仅使用基本身份验证发送Authorization标头。但是由于某种原因,这不会在登录端点上发生。 我只是在使登录HTTP请求出错吗?还是我的配置错误?