问题
I am building an application using Spring boot with Spring security and front end reactJS. My code works well with authentication. But now i am planning to redirect the user to his previous requested page in case he has to login again.
I can extract targetUrl i.e. previous page from the successhandler but when i do a console.log(data) at the UI. I get the raw html data instead of URL name. I dont know why and how to open such a raw html code or can i send just html URL name from successhandler instead it sends complete raw html code? Any inputs are highly appreciated.
Expected console.log(data) - https://localhost:8080/addpage.html
Actual console.log(data) - raw html data of addpage.html
ApplicationSecurity.java
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private RESTAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
private RESTAuthenticationFailureHandler authenticationFailureHandler;
@Autowired
private RESTAuthenticationSuccessHandler authenticationSuccessHandler;
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/CSS/*").permitAll()
.antMatchers("/JS/*").permitAll()
.antMatchers("/login.html").permitAll()
.antMatchers("/*").authenticated()
.and()
.sessionManagement().maximumSessions(5).and().invalidSessionUrl("/login.html");
http.csrf().disable();
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
http.formLogin().successHandler(authenticationSuccessHandler);
http.formLogin().failureHandler(authenticationFailureHandler);
http.logout().logoutSuccessUrl("/login.html");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
}
RESTAuthenticationSuccessHandler.java
@Component
public class RESTAuthenticationSuccessHandler extends
SavedRequestAwareAuthenticationSuccessHandler {
private RequestCache requestCache = new HttpSessionRequestCache();
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
System.out.println(savedRequest);
if (savedRequest == null) {
HttpSession session = request.getSession();
if (session != null) {
String redirectUrl = (String) session.getAttribute("url_prior_login");
if (redirectUrl != null) {
session.removeAttribute("url_prior_login");
getRedirectStrategy().sendRedirect(request, response, redirectUrl);
} else {
super.onAuthenticationSuccess(request, response, authentication);
}
} else {
super.onAuthenticationSuccess(request, response, authentication);
}
return;
}
String targetUrlParameter = getTargetUrlParameter();
System.out.println(targetUrlParameter);
if (isAlwaysUseDefaultTargetUrl()
|| (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
requestCache.removeRequest(request, response);
super.onAuthenticationSuccess(request, response, authentication);
return;
}
clearAuthenticationAttributes(request);
// Use the DefaultSavedRequest URL
String targetUrl = savedRequest.getRedirectUrl();
System.out.println(targetUrl);
logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
getRedirectStrategy().sendRedirect(request, response, targetUrl);
}
}
UI code :
$.ajax({
type: "POST",
url: "/login",
data: data,
success: function(data){
console.log(data);
}.bind(this),
error:function(data)
{
alert(data.responseJSON.message);
}
});
console.log(data) - returns raw html code of targetURL which i cannot open as a html file. I need the html file name returned by targetURL from successhandler so that i can use window.location.href to open the file
回答1:
You can return the redirect url to response.
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// ... get target url
String targetUrl = "";
try {
response.setStatus(HttpServletResponse.OK);
PrintWriter writer = response.getWriter();
writer.write(targetUrl);
writer.flush();
writer.close();
} catch (IOException e) {
// ignore
logger.error(e.getMessage(), e);
}
}
回答2:
Sounds like a mime type issue. Inspect your web traffic with chrome inspect and make sure your headers are set correctly:
Response headers:
Content-Type:text/html; charset=utf-8
Request headers:
Accept:text/html
etc.
来源:https://stackoverflow.com/questions/43924104/redirecting-to-original-page-after-successful-login-returns-raw-data-instead-of