In addition to shi's response, I would make some changes in the Handler. You could use a Map<String,String>
as class field in the handler to manage the role-redirections matchings.
And you could also extend org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler to take advantage of it's already implemented methods, this way:
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
public class MySimpleUrlAuthenticationSuccessHandler
extends SimpleUrlAuthenticationSuccessHandler
implements AuthenticationSuccessHandler {
protected Logger logger = Logger.getLogger(this.getClass());
private Map<String, String> authorityRedirectionMap;
public MySimpleUrlAuthenticationSuccessHandler(Map<String, String> authorityRedirectionMap) {
super();
this.authorityRedirectionMap = authorityRedirectionMap;
}
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
String targetUrl = determineTargetUrl(request, response, authentication);
if (response.isCommitted()) {
logger.debug("Response has already been committed. Unable to redirect to "
+ targetUrl);
return;
}
this.getRedirectStrategy().sendRedirect(request, response, targetUrl);
}
/**
*
* @param request
* @param response
* @param authentication
* @return
*/
protected String determineTargetUrl(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) {
for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
if(this.authorityRedirectionMap.containsKey(grantedAuthority.getAuthority())){
return this.authorityRedirectionMap.get(grantedAuthority.getAuthority());
}
}
return super.determineTargetUrl(request, response);
}
}
Your configuration xml's success handler section should be like this:
<beans:bean id="myAuthenticationSuccessHandler"
class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler">
<beans:constructor-arg>
<beans:map>
<beans:entry key="ROLE_USER" value="/user.html" />
<beans:entry key="ROLE_ADMIN" value="/admin.html" />
<beans:entry key="ROLE_CUSTOMER" value="/customer.html" />
<beans:entry key="ROLE_OTHER" value="/other.html" />
</beans:map>
</beans:constructor-arg>
<beans:property name="defaultTargetUrl" value="/default.html" />
</beans:bean>