我正在尝试为我们的API端点编写测试。为了获得使用授权,用户需要先进行身份验证。我能够访问受保护的端点并解析401未经授权的响应,但是我似乎根本不知道如何进行身份验证。
目前尝试放心的测试代码:
@Test
public void loginTest2() throws IOException
{
SessionFilter session = new SessionFilter();
RestAssured.baseURI = "https://localhost:8080";
Response response = RestAssured.given()
.config( RestAssured.config().sessionConfig( new SessionConfig().sessionIdName( "SESSION" ) ) )
.filter( session )
.auth().form( "dev", "test", FormAuthConfig.springSecurity() )
.when()
.post( "/login" )
.then()
.statusCode( 401 ).extract().response();
System.out.println( "response :" + response.asString() );
System.out.println( "response.cookie( \"SESSION\" ) :" + response.cookie( "SESSION" ) );
System.out.println( "sessionFilter.getSessionId() :" + session.getSessionId() );
}
测试输出:
response :{"timestamp":1534278154501,"status":401,"error":"Unauthorized","message":"Unauthorized.","path":"/login"}
response.cookie( "SESSION" ) :null
sessionFilter.getSessionId() :null
当前的Spring Security配置:
@Override
public void configure( HttpSecurity http ) throws Exception
{
http.addFilterBefore(
new CustomLoginPageFilter(), DefaultLoginPageGeneratingFilter.class );
http
.cors()
.and()
.exceptionHandling()
.accessDeniedHandler( accessDeniedHandler() )
.authenticationEntryPoint( new RestAuthenticationEntryPoint() )
.and()
.authorizeRequests()
.antMatchers( "/login" ).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage( "/login" )
.failureHandler( customAuthFailureHandler )
.successHandler( customAuthSuccessHandler )
.permitAll() );
}
CustomLoginPageFilter:
public class CustomLoginPageFilter extends GenericFilterBean
{
@Override
public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException
{
if ( ( SecurityContextHolder.getContext().getAuthentication() != null )
&& SecurityContextHolder.getContext().getAuthentication().isAuthenticated()
&& "/login".equals( ( (HttpServletRequest) request ).getRequestURI() ) )
{
( (HttpServletResponse) response ).sendRedirect( "/" );
}
chain.doFilter( request, response );
}
}
login.html表单:
<form name="loginForm" method="post" action="/login" id="login-form">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control underlined" name="username" id="login-username" autocomplete="off" placeholder="Enter your username"/>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control underlined" name="password" id="login-password" autocomplete="off" placeholder="Enter your password"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-primary" id="login-submit">
<em class="fa fa-key" id="login-submitButtonIcon"></em> Login</button>
</div>
</form>
我可以提供其他详细信息,但我不确定是哪些片段相关。