ajax login with spring webMVC and spring security - ajax

I've been using Spring Security 3.0 for our website login mechanism using a dedicated login webpage. Now I need that login webpage to instead be a lightbox/popup window on every webpage in our site where upon logging in I get an AJAX result whether it was successful or not. What's the best way to go about this with Spring Security and Spring webmvc 3.0?

At the client-side you may simulate a normal form submission to your login url via ajax. For example, in jQuery:
$.ajax({
url: "${pageContext.request.contextPath}/j_spring_security_check",
type: "POST",
data: $("#loginFormName").serialize(),
beforeSend: function (xhr) {
xhr.setRequestHeader("X-Ajax-call", "true");
},
success: function(result) {
if (result == "ok") {
...
} else if (result == "error") {
...
}
}
});
At the server side, you may customize AuthenticationSuccessHandler and AuthenticationFailureHandler to return a value instead of redirect. Because you probably need a normal login page as well (for attempt to access a secured page via direct url), you should tell ajax calls from normal calls, for example, using header:
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private AuthenticationSuccessHandler defaultHandler;
public AjaxAuthenticationSuccessHandler() {
}
public AjaxAuthenticationSuccessHandler(AuthenticationSuccessHandler defaultHandler) {
this.defaultHandler = defaultHandler;
}
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication auth)
throws IOException, ServletException {
if ("true".equals(request.getHeader("X-Ajax-call"))) {
response.getWriter().print("ok");
response.getWriter().flush();
} else {
defaultHandler.onAuthenticationSuccess(request, response, auth);
}
}
}

I did something similar (thanks axtavt):
public class AjaxAuthenticationSuccessHandler extends
SimpleUrlAuthenticationSuccessHandler {
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication auth)
throws IOException, ServletException {
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
response.getWriter().print(
"{success:true, targetUrl : \'"
+ this.getTargetUrlParameter() + "\'}");
response.getWriter().flush();
} else {
super.onAuthenticationSuccess(request, response, auth);
}
}}
I chose to extend the simple success handler for the default behavior on non-Ajax requests. Here's the XML to make it work:
<http auto-config="false" use-expressions="true" entry-point-ref="authenticationProcessingFilterEntryPoint">
<custom-filter position="FORM_LOGIN_FILTER" ref="authenticationFilter" />
...
...
</http>
<beans:bean id="authenticationProcessingFilterEntryPoint"
class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<beans:property name="loginFormUrl" value="/index.do" />
<beans:property name="forceHttps" value="false" />
</beans:bean>
<beans:bean id="authenticationFilter" class=
"org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<beans:property name="authenticationManager" ref="authenticationManager"/>
<beans:property name="filterProcessesUrl" value="/j_spring_security_check"/>
<beans:property name="sessionAuthenticationStrategy" ref="sas" />
<beans:property name="authenticationFailureHandler" ref="failureHandler"/>
<beans:property name="authenticationSuccessHandler" ref="successHandler"/>
</beans:bean>
<beans:bean id="successHandler" class="foo.AjaxAuthenticationSuccessHandler">
<beans:property name="defaultTargetUrl" value="/login.html"/>
</beans:bean>
<beans:bean id="failureHandler" class="foo.AjaxAuthenticationFailureHandler" />

Related

How to Over ride BindAuthenticator handleBindException for Spring LDAP Authentication setup in Spring Boot

For Spring security setup in Spring Boot. The LDAP Authentication provider is configured by default to use BindAuthenticator class.
This Class contains method
/**
* Allows subclasses to inspect the exception thrown by an attempt to bind with a
* particular DN. The default implementation just reports the failure to the debug
* logger.
*/
protected void handleBindException(String userDn, String username, Throwable cause) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to bind as " + userDn + ": " + cause);
}
}
This Method is to handle the authentication related Exceptions like invalid credentials.
I want to over-ride this method so i can handle this issue and return proper error message on the basis of error codes returned by LDAP. like invalid password or the account is locked.
Current LDAP implementation always returns "Bad Credentials" that does not give the right picture that why my credentials are invalid. i want to cover the cases
where the account is Locked
password is expired so i can redirect to change password
account locked due to number of invalid password retries
Please help
The issue i fixed by defining the LDAP context instead of using the Spring Boot LDAPAuthenticationProviderConfigurer.
Then created the FilterBasedLdapUserSearch and Over-written the BindAuthentication with my ConnectBindAuthenticator.
i created a separate LDAPConfiguration class for spring boot configuration and registered all these custom objects as Beans.
From the above Objects i created LDAPAuthenticationProvider by passing my Custom Objects to constructor
The Config is as below
#Bean
public DefaultSpringSecurityContextSource contextSource() {
DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(env.getProperty("ldap.url"));
contextSource.setBase(env.getProperty("ldap.base"));
contextSource.setUserDn(env.getProperty("ldap.managerDn"));
contextSource.setPassword(env.getProperty("ldap.managerPassword"));
return contextSource;
}
#Bean
public ConnectBindAuthenticator bindAuthenticator() {
ConnectBindAuthenticator connectBindAuthenticator = new ConnectBindAuthenticator(contextSource());
connectBindAuthenticator.setUserSearch(ldapUserSearch());
connectBindAuthenticator.setUserDnPatterns(new String[]{env.getProperty("ldap.managerDn")});
return connectBindAuthenticator;
}
#Bean
public LdapUserSearch ldapUserSearch() {
return new FilterBasedLdapUserSearch("", env.getProperty("ldap.userSearchFilter"), contextSource());
}
You have to change your spring security configuration to add your extension of BindAuthenticator:
CustomBindAuthenticator.java
public class CustomBindAuthenticator extends BindAuthenticator {
public CustomBindAuthenticator(BaseLdapPathContextSource contextSource) {
super(contextSource);
}
#Override
protected void handleBindException(String userDn, String username, Throwable cause) {
// TODO: Include here the logic of your custom BindAuthenticator
if (somethingHappens()) {
throw new MyCustomException("Custom error message");
}
super.handleBindException(userDn, username, cause);
}
}
spring-security.xml
<beans:bean id="contextSource"
class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<beans:constructor-arg value="LDAP_URL" />
<beans:property name="userDn" value="USER_DN" />
<beans:property name="password" value="PASSWORD" />
</beans:bean>
<beans:bean id="userSearch"
class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
<beans:constructor-arg index="0" value="USER_SEARCH_BASE" />
<beans:constructor-arg index="1" value="USER_SEARCH_FILTER" />
<beans:constructor-arg index="2" ref="contextSource" />
</beans:bean>
<beans:bean id="ldapAuthProvider"
class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">
<beans:constructor-arg>
<beans:bean class="com.your.project.CustomBindAuthenticator">
<beans:constructor-arg ref="contextSource" />
<beans:property name="userSearch" ref="userSearch" />
</beans:bean>
</beans:constructor-arg>
</beans:bean>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="ldapAuthProvider" />
</security:authentication-manager>
Hope it's helpful.

Is it possible to using expression on Spring SecurityMetadataSource?

i want to manage url authorization by Database. So, i'm implement Security MetadataSource. It was perfect except cann't using expression.
below is my code and xml settings.
xml
<beans:bean id="filterSecurityInterceptor" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="accessDecisionManager" ref="accessDecisionManager" />
<beans:property name="securityMetadataSource" ref="securityMetadataSource" />
</beans:bean>
<beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
<beans:constructor-arg>
<beans:list>
<beans:bean class="org.springframework.security.access.vote.RoleVoter">
<beans:property name="rolePrefix" value="" />
</beans:bean>
</beans:list>
</beans:constructor-arg>
<beans:property name="allowIfAllAbstainDecisions" value="false" />
</beans:bean>
<beans:bean id="securityMetadataSource" class="my.package.CustomSecurityMetadataSource">
</beans:bean>
java
public class CustomSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
#Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
FilterInvocation fi = (FilterInvocation) object;
String url = fi.getRequestUrl();
HttpServletRequest request = fi.getHttpRequest();
// TODO get url authorization from db and caching
String[] roles = new String[] { "ROLE_ANONYMOUS", "ROLE_USER"};
return SecurityConfig.createList(roles);
}
#Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
#Override
public boolean supports(Class<?> clazz) {
return FilterInvocation.class.isAssignableFrom(clazz);
}
}
i want to using expression like hasAnyRole("ROLE_ADMIN", "ROLE_USER").
how can i use expression?

Redirection of pages in spring mvc

I have a product page which displays all products
home.jsp:
<a class="campaign" href="page/dynamic/product1">
Controller
#RequestMapping(value="/page/dynamic/{pagename}")
public ModelAndView loadProductPage(ModelMap model, #PathVariable("pagename") String pagename) {
model.addAttribute("productname",pagename);
return new ModelAndView("products/"+pagename+"/"+pagename);
}
It is getting redirected to the product1 page. Product1 page has a link called features
product1.jsp
<li>Features</li>
Controller
#RequestMapping(value="/page/loadpage/{choosedProduct}/{linkChoosed}")
public ModelAndView loadProductMenuPages(ModelMap model, #PathVariable("linkChoosed") String linkChoosed, #PathVariable("choosedProduct") String choosedProduct) {
System.out.println("Loading links here");
System.out.println("cones gere");
System.out.println("Product Choosed" + choosedProduct);
System.out.println("Link Choosed" + linkChoosed);
return new ModelAndView("products/"+choosedProduct+"/"+linkChoosed);
}
It is not getting redirected to the "features page", but throws an error:
HTTP Status 404 - /controller/WEB-INF/views/products/loadpage/loadpage.jsp
What should I need to do to get redirected to features page?
EDIT:
Adding servlet-context.xml informed in comment:
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
In your configuration file please configure below tag
<bean id="PageRedirect"
class="org.springframework.web.servlet.view.RedirectView">
<property name="url" value="RedirectPage.jsp" />
</bean>
And in your controller
#Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
return new ModelAndView("PageRedirect");
}

Integrating spring security with Ajax calls

So I have a web app that utilises jsf and primefaces for it's front end presentation.
We are using Spring security for the login mechanism and have defined the concurrency as such
<session-management session-fixation-protection="newSession">
<concurrency-control max-sessions="1" error-if-maximum-exceeded="true"
expired-url="multipleLogins.xhtml" />
</session-management>
The problem seems to be when a user has two logins from different browsers there are certain buttonas that perform ajax actions that do not trigger the redirect. It seems to only be buttons that submit forms or redirect to pages themselves that will recognise the multiple logins actions.
For example, this button
<p:commandButton id="retrieve" value="#{msgs.BUTTON_RETRIEVE}"
action="#{removeContactForm.retrieve}" update="#form"/>
Which retrieves things from a web service and displays them on a page will not trigger the redirect if there are multiple logins.
<p:commandButton id="remove" value="#{msgs.BUTTON_REMOVE}"
action="/pages/confirm/confirmRemove.xhtml" ajax="false" process="#this"
immediate="true" rendered="#{!empty removeContactManager and
removeContactManager.contactRolesSuccessful}" />
This button will however (as it redirects to another page)
Anyone know a way of making the webapp register those ajax calls as events, without sticking everything ajax based into a new page?
I have used the JSFRedirectStrategy written by Ben Simpson for redirecting to a session expired url when the session expires using the session management filter. Source can be found here.
I think the same can be applied here but we need to remove the namespace configuration and add some beans like this:
<http>
<custom-filter position="CONCURRENT_SESSION_FILTER" ref="concurrencyFilter" />
<custom-filter position="FORM_LOGIN_FILTER" ref="myAuthFilter" />
<session-management session-authentication-strategy-ref="sas"/>
</http>
<beans:bean id="concurrencyFilter"
class="org.springframework.security.web.session.ConcurrentSessionFilter">
<beans:constructor-arg name="sessionRegistry" ref="sessionRegistry" />
<beans:constructor-arg name="expiredUrl" value="/multipleLogins.xhtml" />
<!-- this permits redirection to session timeout page from javascript/ajax or http -->
<beans:property name="redirectStrategy" ref="jsfRedirectStrategy" />
</beans:bean>
<beans:bean id="myAuthFilter" class=
"org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<beans:property name="sessionAuthenticationStrategy" ref="sas" />
<beans:property name="authenticationManager" ref="authenticationManager" />
</beans:bean>
<beans:bean id="sas" class=
"org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">
<beans:constructor-arg name="sessionRegistry" ref="sessionRegistry" />
<beans:property name="maximumSessions" value="1" />
<beans:property name="alwaysCreateSession" value="true" />
<beans:property name="exceptionIfMaximumExceeded" value="true" />
</beans:bean>
<beans:bean id="jsfRedirectStrategy" class="com.examples.JsfRedirectStrategy"/>
<beans:bean id="sessionRegistry"
class="org.springframework.security.core.session.SessionRegistryImpl" />
Now, you can check if the request was an ajax request and then send a redirect like this in the JSFRedirectStrategy class:
Here is the code copied from the ICEfaces tutorial.
/**
* This class represents an extension to the way DefaultRedirectStrategy works.
* This class takes into account if the incoming request causing action by Spring Security
* requires a "partail-response" xml redirect instead of a response.sendRedirect().
*
* #author Ben Simpson ben.simpson#icesoft.com
*/
public class JsfRedirectStrategy implements RedirectStrategy {
protected final Log logger = LogFactory.getLog(getClass());
private boolean contextRelative;
/**
* Redirects the response to the supplied URL.
* <p>
* If <tt>contextRelative</tt> is set, the redirect value will be the value after the request context path. Note
* that this will result in the loss of protocol information (HTTP or HTTPS), so will cause problems if a
* redirect is being performed to change to HTTPS, for example.
*/
public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
String redirectUrl = calculateRedirectUrl(request.getContextPath(), url);
redirectUrl = response.encodeRedirectURL(redirectUrl);
if (logger.isDebugEnabled()) {
logger.debug("Redirecting to '" + redirectUrl + "'");
}
//we should redirect using ajax response if the case warrants
boolean ajaxRedirect = request.getHeader("faces-request") != null
&& request.getHeader("faces-request").toLowerCase().indexOf("ajax") > -1;
if(ajaxRedirect) {
//javax.faces.context.FacesContext ctxt = javax.faces.context.FacesContext.getCurrentInstance();
//ctxt.getExternalContext().redirect(redirectUrl);
String ajaxRedirectXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<partial-response><redirect url=\""+redirectUrl+"\"></redirect></partial-response>";
response.setContentType("text/xml");
response.getWriter().write(ajaxRedirectXml);
} else {
response.sendRedirect(redirectUrl);
}
}
private String calculateRedirectUrl(String contextPath, String url) {
if (!UrlUtils.isAbsoluteUrl(url)) {
if (contextRelative) {
return url;
} else {
return contextPath + url;
}
}
// Full URL, including http(s)://
if (!contextRelative) {
return url;
}
// Calculate the relative URL from the fully qualified URL, minus the scheme and base context.
url = url.substring(url.indexOf("://") + 3); // strip off scheme
url = url.substring(url.indexOf(contextPath) + contextPath.length());
if (url.length() > 1 && url.charAt(0) == '/') {
url = url.substring(1);
}
return url;
}
/**
* If <tt>true</tt>, causes any redirection URLs to be calculated minus the protocol
* and context path (defaults to <tt>false</tt>).
*/
public void setContextRelative(boolean useRelativeContext) {
this.contextRelative = useRelativeContext;
}
}

spring security : how to apply #PreAuthorize to SwitchUserFilter

I have to check whether the user has the permission to switch user, on the basis of his userId. In my security xml, inside the <http> element, I am specifying a custom filter :
<custom-filter after="FILTER_SECURITY_INTERCEPTOR" ref="switchUserProcessingFilter"/>
<beans:bean id="switchUserProcessingFilter" class="com.something.MySwitchUserFilter">
<beans:property name="userDetailsService" ref="userServices" />
<beans:property name="switchUserUrl" value="/admin/switchUser" />
<beans:property name="exitUserUrl" value="/exitUser" />
<beans:property name="successHandler" ref="userSwitchSuccessHandler"></beans:property>
</beans:bean>
In MySwitchUserFilter, I override only a single method :
#Override
#PreAuthorize("canISwitchToThisUser(#{request.getAttribute('userId')}")
protected Authentication attemptSwitchUser(HttpServletRequest request) throws AuthenticationException {
return super.attemptSwitchUser(request);
}
#PreAuthorize is working at other locations, but i wonder why its not working here. Note that I am also passing an request parameter 'userId' along with the customary 'j_username'. Note that I am able to switch user, just that the annotation is not being processed.

Resources