bharathi bharathi - 2 months ago 21
Java Question

Redirect to home page after login in spring mvc

I have a problem. Suppose I login into the application and accessing different pages and leaving the application ideal for 5 min in http://localhost:8080/InformationManagement/smartapp/allFileNetStatus and then trying to access once the session get expired and get redirected to login page.
Once I enter the credentials it get logged in it get me to http://localhost:8080/InformationManagement/smartapp/allFileNetStatus instead of home page(http://localhost:8080/InformationManagement/)

Note: My Login page and Home page URL is same

How can I control this in spring security.

Code:

<http pattern="/resources" security="none" />

<http auto-config="true" use-expressions="true">
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/logout" access="permitAll" />
<intercept-url pattern="/denied" access="hasRole('ROLE_USER')" />
<intercept-url pattern="/" access="permitAll" />
<intercept-url pattern="/user" access="hasRole('ROLE_USER')" />
<intercept-url pattern="/user/create" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/user/update"
access="hasAnyRole('ROLE_READ','ROLE_ADMIN')" />
<intercept-url pattern="/smartapp/getNewFileNetStatus" access="hasRole('ROLE_SMARTAPP')" />
<intercept-url pattern="/smartapp/allFileNetStatus" access="hasRole('ROLE_SMARTAPP')" />
<intercept-url pattern="/user/alluser" access="hasAnyRole('ROLE_READ','ROLE_ADMIN')" />
<intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')" />

<form-login login-page="/login" authentication-failure-url="/login/failure"
default-target-url="/" />

<access-denied-handler error-page="/denied" />

<logout invalidate-session="true" logout-success-url="/logout/success"
logout-url="/logout" />
</http>



<beans:bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="userDetailsService"></beans:property>

</beans:bean>

<beans:bean id="authenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<beans:property name="providers">
<beans:list>
<beans:ref local="daoAuthenticationProvider" />
</beans:list>
</beans:property>
</beans:bean>

<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder hash="md5"></password-encoder>
</authentication-provider>
</authentication-manager>




HomeController.java

@Controller
@RequestMapping("/")
public class HomeController {

/*
* @Value("${msg}") private String msg;
*/

@Autowired
UserDetailsService userService;

Logger logger = Logger.getLogger(HomeController.class);

@RequestMapping(value = "/help", method = RequestMethod.GET)
public String getAdminPage() {
return "help";
}

@RequestMapping(method = RequestMethod.GET)
public String getHomePage(Model model, HttpSession session) {

Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();

if (!(auth instanceof AnonymousAuthenticationToken)) {

/* The user is logged in :) */
if (logger.isInfoEnabled()) {
logger.info("User got logged in...");
}
int passwordResetValue = userService.userPasswordReset(auth
.getName());
session.setAttribute("username",auth.getName());
System.out.println("username-- set-->"+session.getAttribute("username"));
System.out.println("passwordResetValue" + passwordResetValue);
if (passwordResetValue == 0) {
return "home";
} else {
return "redirect:/password/changePassword?value=reset";
}

} else {
if (logger.isInfoEnabled()) {
logger.info("Redirected to Login Page");
}
return "access/login";
}
}


AccessController.java

@Controller
@RequestMapping
public class AccessController {

@RequestMapping(value = "/denied")
public String denied() {
return "access/denied";
}

@RequestMapping("/login")
public String login() {
/*System.out.println("message-->" + message);
model.addAttribute("message", message);*/
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();

if (!(auth instanceof AnonymousAuthenticationToken)) {
auth.getPrincipal();
/* The user is logged in :) */
System.out.println("eeee");
return "redirect:/";
} else {
System.out.println("Finalalaay" + auth.getDetails());
return "access/login";
}
}

@RequestMapping(value = "/login/failure")
public String loginFailure(final RedirectAttributes redirect) {
String message = "Please verify username and password";
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();

if (!(auth instanceof AnonymousAuthenticationToken)) {

/* The user is logged in :) */
return "redirect:/";
} else {
redirect.addFlashAttribute("message", message);
return "redirect:/login";
}
}

@RequestMapping(value = "/logout/success")
public String logoutSuccess(final RedirectAttributes redirect) {
String message = "You have been successfully logged out.";
redirect.addFlashAttribute("message", message);
return "redirect:/login";
}


}

Answer

You should implement your own AuthenticationSuccessHandler for that.

 <!-- Add to your form login the handler-->
 <form-login login-page="/login" authentication-failure-url="/login/failure"
        default-target-url="/" authentication-success-handler-ref="homeRedirectSuccessHandler" />
 <beans:bean id="homeRedirectSuccessHandler"
    class="your.package.HomeRedirectSuccessHandler" />

And in your HomeRedirectSuccessHandler:

protected void handle(HttpServletRequest request, 
  HttpServletResponse response, Authentication authentication) throws IOException {

    redirectStrategy.sendRedirect(request, response, "yourHomepage.html);
}
Comments