How to avoid 302 response on https spring security unit test?
Using Springs MockMvc stuff you can also specify that you want to send a mock HTTPS request using the secure(true) method as follows:
restContactMockMvc.perform( get("/api/contacts").secure( true ) ).andExpect( status().isOk() )
Spring Security 5 authentication always return 302
This is because spring default authentication success handler looks for a url to redirect.
What one can do is use a custom AuthenticationSuccessHandler
i have used below and no redirects are happening.
public class AppAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{
protected void handle(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
}
}
Then define the bean and give it in the configure method for security
@Bean
public AuthenticationSuccessHandler appAuthenticationSuccessHandler(){
return new AppAuthenticationSuccessHandler();
}
Configure method
http
.authorizeRequests()
.antMatchers("/login*")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.successHandler(appAuthenticationSuccessHandler());
Spring Boot Security Authentication - 302 Redirects
spring security formLogin default intercept the "/login" request, i find that your login page url is "/login" which is conflict with this filter. you can define your login page url like this:
.formLogin()
.loginPage("/page/login.html").permitAll()
and change then controller mapping from login --> /page/login
Spring Security 3 - always return error 302
I believe Spring is redirecting you to /home
because you didn't actually authenticated a User through the login process.
- You access your web-app through
http://mylocal:8080/moon
returning the home.jsp view - You click the SignIn button, submitting your login form
since no form login is explicitly declared, Spring Security will display the username and password prompt box for the end-user to enter its credentials - These credentials are then POSTed to the login processing URL (
/acct/signin
) for which you happen to have a mapping with thesignin
method in theAccountController
- Such controller fails to authenticate a User the Spring way, but still redirect the request to
/demo
by returning a String - The
/demo
path is protected (.anyRequest().authenticated()
) to any unauthenticated user, since the current user is indeed unauthenticated, Spring Security will automatically redirect the request to the login page - You end up on
/home
(.loginPage("/home")
)
Using a InMemoryUserDetailsManagerConfigurer (see inMemoryAuthentication javadoc), you can only successfully login through the configured credentials. If you want a fully-fledged Authentication system, you must provide an UserDetailsService implementation to your Spring Security configuration (through the userDetailsService method).
EDIT : Following the conversation with chialin.lin, it seems the missing configuration was a defaultSuccessfulUrl for Spring Security to know where to redirect the user once authenticated.
Spring, Spring-security : Spring-security returning 302, even if login failed
security:form-login
is designed for web apps rather than REST clients. Although you can use it, you'll run into the kind of trouble you've described here.
I recommend using security:http-basic
instead (secured over HTTPS) and sending the login details each time.
Edit: If you insist on using form login, you'll need to tell the RestTemplate
not to follow redirects, which you can do with the following (using Apache HttpComponents instead of the standard JRE HttpUrlConnection
):
final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
final HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(
new DefaultRedirectStrategy() {
@Override
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
return false;
}
}
).build();
factory.setHttpClient(httpClient);
restTemplate.setRequestFactory(factory);
Spring Security 302 redirection
When a user registers, you are making a POST request to "/register".
However, "/register" requires a user to be authenticated.
You can add
.antMatchers("/register").permitAll()
to your security configuration in order to allow unauthenticated users to register.
Spring Boot Login Redirect 302 Losing HTTPS
I was able to solve this issue using the following spring config:
security.require-ssl=true
It will force HTTPS despite a spring boot app running on port 8080.
Related Topics
Split Comma Separated Values in Java, Int and String
Sharing a Variable Between Multiple Different Threads
How to Center Crop a Background Image of Linear Layout
Java.Sql.Sqlexception: Field Doesn't Have a Default Value
Simplifying the If-Else Condition Using Java Functional Style Programming
Keytool Error Bash: Keytool: Command Not Found
Springboot - How to Start Embedded Container
Saveastextfile() to Write the Final Rdd as Single Text File - Apache Spark
Map Json String Column of a JPA Entity to Java Object Automatically
How to Use Different Jsonproperty on Serialize & Deserialize Using Jackson API
How to Loop Through List of Webelements and Select One Webelement With a Condition
Unit Testing Private Functions in Junit With Mockito
How to Retrieve Element Value from Soap Response Using Java