authentication filter was called repeatedly - spring

I setup spring security for my rest apis. Here is a sample of my rest call,
GET: http://localhost:8081/dashboard/epic/data. When executing, filter, provider and eventual onAuthenticationSuccess are triggered. Here is the problem, instead of executing the rest url after authentication, it will go back to filter many times. For the second time, request.getRequestUrl will be http://localhost:8081/dashboard.
Here is my security-context.xml:
<http auto-config='false' authentication-manager-ref="authenticationManager" entry-point-ref="authenticationEntryPoint">
<intercept-url pattern="dashboard/**" access="ROLE_USER" />
<csrf disabled="true"/>
<custom-filter position="REMEMBER_ME_FILTER" ref="DashboardFilter"></custom-filter>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider ref="DashboardAuthProvider"></authentication-provider>
</authentication-manager>
<beans:bean id="DashboardFilter" class="com.apple.store.dashboard.security.DashboardAuthFilter">
<beans:property name="authenticationManager" ref="authenticationManager"/>
<beans:property name="authenticationSuccessHandler">
<beans:bean class="com.apple.store.dashboard.security.LoginSuccessHandler">
</beans:bean>
</beans:property>
</beans:bean>
<beans:bean id="authenticationEntryPoint" class="com.apple.store.dashboard.security.DashboardAuthEntryPoint">
</beans:bean>
<beans:bean id="DashboardAuthProvider" class="com.apple.store.dashboard.security.DashboardAuthProvider"> </beans:bean>
Here is my filter
public class DashboardAuthFilter extends AbstractAuthenticationProcessingFilter {
private static final Logger logger = LoggerFactory.getLogger(DashboardAuthFilter.class);
public DashboardAuthFilter() {
//super("/j_spring_cas_security_check");
super("/**");
}
public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response)
throws org.springframework.security.core.AuthenticationException, UnsupportedEncodingException {
logger.debug("Inside DashboardAuthFilter:attemptAuthentication method:");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth!=null ){
if (auth.isAuthenticated()){
logger.debug("Previously authenticated.isAuthenticated=true::: Auth details:" +auth);
return auth;
}
}
String _username = null;
String _password = null;
String authHeader = request.getHeader("Authorization");
if (authHeader != null) {
StringTokenizer st = new StringTokenizer(authHeader);
if (st.hasMoreTokens()) {
String basic = st.nextToken();
if (basic.equalsIgnoreCase("Basic")) {
try {
String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8");
logger.debug("Credentials: " + credentials);
int p = credentials.indexOf(":");
if (p != -1) {
_username = credentials.substring(0, p).trim();
_password = credentials.substring(p + 1).trim();
}
} catch (Exception e) {
}
}
}
}
else
System.out.println("request url is "+request.getRequestURL());
Authentication authResult = null;
try {
if( org.apache.commons.lang.StringUtils.isEmpty(_password)) {
throw new PreAuthenticatedCredentialsNotFoundException("No username:password..");
}
String credentials = "NA";
//String validateCookieDetails = correctAuthentication(AOSCookie, request);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(_username+":"+_password, credentials);
authResult = getAuthenticationManager().authenticate(authRequest);
logger.debug("Attempted authentication: authResult ::" + authResult.toString());
} catch (org.springframework.security.core.AuthenticationException e) {
logger.error("AttemptAuthentication: Not Authenticated : AuthenticationException ....." + e.getMessage());
} catch (Exception e) {
logger.error("Exception occured during authentication....." + e.getMessage());
}
return authResult;
}
Here is my provider:
public class DashboardAuthProvider implements AuthenticationProvider {
private static final Logger logger = LoggerFactory.getLogger(DashboardAuthProvider.class);
#Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
logger.debug("Inside DashboardAuthProvider: authenticate method +authentication=" + authentication);
Authentication auth =null;
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
try{
String[] principalStrArr = ((String)authentication.getPrincipal()).split(":");
//Convert the authentication principal object to a map
if (principalStrArr[0].equals("test1") && principalStrArr[1].equals("test1"))
{
String username = principalStrArr[0];
String password = principalStrArr[1];
final UserDetails principal = new AccessInfo(username, password, grantedAuths);
auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
logger.info("DashboardAuthProvider auth= " + auth);
}
else {
logger.info("Wrong credential");
return null;
}
}catch (Exception e){
logger.error(
"Exception occured in DashboardAuthProvider during authentication",
e);
}
return auth;
}
And here is my onAuthenticationSuccess:
public class LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
super.onAuthenticationSuccess(request, response, authentication);
}

Related

SecurityContextHolder authentication object not available to subsequent requests from the client

Inside getUserObject() method we are not able to get Authentication object. It's available for 1st request only. But its setting to null for subsequent requests from client. So please help me to configure it properly so that its available for all the requests calls.
I am not sure how to configure inside configure method in AuthConfig.java so that authentication object would be available for all the requests chain
AuthConfig.java:
#Configuration
#EnableWebSecurity
public class AuthConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/callback", "/", "/auth0/authorize", "/resources/**", "/public/**", "/static/**",
"/login.do", "/logout.do", "/thankYou.do", "/customerEngagement.do",
"/oldCustomerEngagement.do", "/registerNew.do", "/forgotPassword.do", "/checkMongoService.do",
"/reset.do", "/rlaLogin.do", "/fnfrefer.do", "/thankYouLeadAggregator.do", "/referral")
.permitAll()
.anyRequest().authenticated().and().
logout()
.logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler());
}
------------------------------------------------------------------------------
AuthController.java:
#RequestMapping(value = "/callback", method = RequestMethod.GET)
public void callback(HttpServletRequest request, HttpServletResponse response)
throws IOException, IdentityVerificationException {
try {
Tokens tokens = authenticationController.handle(request, response);
DecodedJWT jwt = JWT.decode(tokens.getIdToken());
List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
Authentication auth = new UsernamePasswordAuthenticationToken(jwt.getSubject(), jwt.getToken(), grantedAuths);
SecurityContext context = SecurityContextHolder.getContext();
context.setAuthentication(auth);
response.sendRedirect(config.getContextPath(request) + "/loancenter/home.do");
} catch (Exception e) {
LOG.info("callback page error");
response.sendRedirect(config.getContextPath(request) + "/loancenter");
}
}
--------------------------------------------------------------------------------
HomeController.java:
#Controller
public class DefaultController implements InitializingBean {
#RequestMapping(value = "home.do")
public ModelAndView showCustomerPage(HttpServletRequest req, HttpServletResponse res, Model model) {
ModelAndView mav = new ModelAndView();
try {
User user = getUserObject(req);
if(user==null) {
LOG.info("User not found in session");
mav.setViewName(JspLookup.LOGIN);
return mav;
}
} catch (Exception e) {
LOG.error("Exception in Home page ", e);
}
return mav;
}
protected User getUserObject(HttpServletRequest request) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
LOG.info("authentication::{}", authentication);
User user = null;
if (authentication == null) {
return user;
}
if (authentication.getPrincipal() instanceof User) {
user = (User) authentication.getPrincipal();
LOG.info("User already authenticated and logging :{}", user.getEmailId());
sendUserLoginEmailToLO(user);
} else {
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
DecodedJWT jwt = JWT.decode(token.getCredentials().toString());
user = userProfileDao.findByUserEmail(jwt.getClaims().get("email").asString());
if (user != null) {
LOG.info("First time authentication:{}", user.getEmailId());
boolean auth0EmailVerified = jwt.getClaims().get("email_verified").asBoolean();
LOG.info("First time authentication email verified flag from auth0:{}", auth0EmailVerified);
LOG.info("First time authentication email verified flag from nlc:{}", user.getEmailVerified());
if (BooleanUtils.isFalse(user.getEmailVerified()) && auth0EmailVerified) {
LOG.info("Email is verified in Auth0, updating email_verified flag to true in DB for userId: {}",
user.getId());
userProfileDao.verifyEmail(user.getId());
LOG.info("First time authentication updated email verified flag in nlc db:{}", user.getEmailId());
}
if (user.getNewEmailVerified() != null && BooleanUtils.isFalse(user.getNewEmailVerified())) {
LOG.info("The user is verifying his email: set his verified to true");
userProfileDao.verifyNewEmail(user.getId());
}
Authentication auth = new UsernamePasswordAuthenticationToken(user, jwt.getToken(),
token.getAuthorities());
messageServiceHelper.checkIfUserFirstLogin(user);
LOG.info("Authentication provided for user : {}", user.getEmailId());
LOG.debug("Auth object constructed : {}", auth);
SecurityContextHolder.getContext().setAuthentication(auth);
HttpSession session = request.getSession(true);
session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());
sendUserLoginEmailToLO(user);
}
}
return user;
}
}

LDAP custom authentication filter

I have a custom authentication CustomAuthenticationProvider class which does a authenticate the user by hitting LDAP remote server. I managed to create and configure the custom authentication provider but having trouble to call doAuthentication method which is defined in SecurityConfiguration.
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
private final Logger log=LoggerFactory.getLogger(CustomAuthenticationProvider.class);
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = (String) authentication.getCredentials();
if (username == null) {
throw new BadCredentialsException("User is not found");
}
if (password == null) {
throw new BadCredentialsException("Password is not found");
}
try {
LdapContextSource ldapContextSource = new LdapContextSource();
ldapContextSource.setUrl("ldap://jnj.com:3268");
ldapContextSource.setBase("dc=jnj,dc=com");
ldapContextSource.setUserDn(username);
ldapContextSource.setPassword(password);
try {
// initialize the context
ldapContextSource.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
}
LdapTemplate ldapTemplate = new LdapTemplate(ldapContextSource);
ldapTemplate.afterPropertiesSet();
// ldapTemplate.setIgnorePartialResultException(true); // Active Directory doesn’t transparently handle referrals. This fixes that.
AndFilter filter = new AndFilter();
filter.and(new EqualsFilter("sAMAccountName", username));
try {
boolean authed = ldapTemplate.authenticate("", filter.toString(), password);
log.debug("Auuthenticated : "+authed);
} catch (org.springframework.ldap.AuthenticationException ee) {
//userDisplay.setText(“Invalid Username/Password”);
}
} catch (Exception e) {
e.printStackTrace();
}
Collection<? extends GrantedAuthority> authorities = Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"));
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password, authorities);
return authenticationToken;
// return new UsernamePasswordAuthenticationToken(username,password);
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
This method is called in SecurityConfiguration,I need to bind this method to mine CustomAuthenticationProvider class
#Inject
public void configureGlobal(AuthenticationManagerBuilder auth) {
try {
auth.authenticationProvider(authProvider)
.ldapAuthentication().userDetailsContextMapper(userDetailsContextMapper())
.ldapAuthoritiesPopulator(ldapAuthoritiesPopulator()).userSearchBase(USER_SEARCH_BASE)
.userSearchFilter(USER_SEARCH_FILTER).groupSearchBase(GROUP_SEARCH_BASE)
.groupSearchFilter(GROUP_SEARCH_FILTER).contextSource(contextSource());
} catch (Exception e) {
throw new BeanInitializationException("Security configuration failed", e);
}
}
This method I need to call for LDAP
protected DirContextOperations doAuthentication(UsernamePasswordAuthenticationToken auth) {
String username = auth.getName();
String password = (String) auth.getCredentials();
DirContext ctx = bindAsUser(username, password);
try {
return searchForUser(ctx, username);
} catch (NamingException e) {
log.error("Failed to locate directory entry for authenticated user: " + username, e);
throw badCredentials(e);
} finally {
LdapUtils.closeContext(ctx);
}
}

Not getting login failure reason (only BadCredential Exception is popped)

Tried various ways to get custom message from spring, if user authentication fails.
Using
<spring.version>4.2.4.RELEASE</spring.version>
<spring.security.version>4.0.3.RELEASE</spring.security.version>
XML configuration
<http auto-config="true" use-expressions="false">
<intercept-url pattern="/**" access='ROLE_FUNCTION' />
<form-login login-page="/login"
default-target-url="/welcome"
username-parameter="j_username"
password-parameter="j_password"
login-processing-url="/j_spring_security_check"
always-use-default-target="true"
authentication-success-handler-ref="authenticationSuccessHandler"
authentication-failure-handler-ref="authenticationFailureHandler"
/>
<logout logout-url="/j_spring_security_logout" logout-success-url="/login?logout" delete-cookies="JSESSIONID" />
<access-denied-handler error-page="/accessDenied" />
<csrf disabled="true"/>
</http>
<authentication-manager>
<authentication-provider user-service-ref="**userDetailsService**">
<password-encoder ref="bcryptEncoder"/>
</authentication-provider>
</authentication-manager>
<beans:bean id="authenticationSuccessHandler" class="com.company.project.CustomAuthenticationSuccessHandler"/>
<beans:bean id="**authenticationFailureHandler**" class="com.company.project.CustomAuthenticationFailureHandler"/>
<beans:bean name="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
Bean definition excerpt is as below
Implementation
userDetailsService
#Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
logger.info("Getting access details for user : {}", username);
UserDto userDto = null;
boolean accountNonExpired = true;
boolean accountNonLocked = true;
boolean credentialsNonExpired = true;
boolean enabled = true;
try {
userDto = userService.loginUser(username);
if (userDto == null) {
throw new UsernameNotFoundException("User not found");
}
if (Active.Y != userDto.getActive()) {
enabled = false;
throw new BadCredentialsException("User account is inactive");
}
} catch (BaseException be) {
throw new BadCredentialsException(be.getMessage().toLowerCase());
}
UserContext context = new UserContext();
context.setLoginId(username);
context.setName(userDto.getName());
context.setPrincipleId(userDto.getId());
List<GrantedAuthority> grantedAuthorities = getGrantedAuthorities(userDto);
String password = getActivePassword(userDto);
accountNonExpired = isAccountActive(userDto);
accountNonLocked = isAccountUnlocked(userDto);
credentialsNonExpired = isCredentialsActive(userDto);
return new UserLoginDetails(grantedAuthorities, password, username, accountNonExpired, accountNonLocked, credentialsNonExpired, enabled, context);
}
}
authenticationSuccessHandler works fine.
authenticationFailureHandler
#Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Autowired
UserService userService;
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
try {
// execute it when user enters wrong password, i.e loginAttempt ...
} catch (Exception e) {
// TODO: something
}
// TODO: how do I send message, if authenticationException.
redirectStrategy.sendRedirect(request, response, "/login?error");
// clearAuthenticationAttributes(request);
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
}
To show error message I'm using following line
JSP
<c:set var="errorMessage" value="${sessionScope[\"SPRING_SECURITY_LAST_EXCEPTION\"].message}" />
Let me brief the expected messages.
If user enters wrong credentials he should get
"Invalid credentials"
If user account is inactive he should get
"Your account is not active"
If user exceeded permissible no. of
attempt his account will get locked and he will get "Your account is
locked"
If my implementation is not correct please let me know what changes should be done.
If you want to override the AuthenticationFailureHandler, you can extend the SimpleUrlAuthenticationFailureHandler, it already has a method to save exception.
protected final void saveException(HttpServletRequest request, AuthenticationException exception) {
if (forwardToDestination) {
request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
} else {
HttpSession session = request.getSession(false);
if (session != null || allowSessionCreation) {
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
}
}
}
When you save the exception to request or session, then you can get the message.
${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}

authentication-provider is not called

Here is my security-context.xml file:
<http auto-config='false' authentication-manager-ref="authenticationManager" entry-point-ref="authenticationEntryPoint">
<intercept-url pattern="/"/>
<intercept-url pattern="/**"/>
<csrf disabled="true"/>
<custom-filter position="REMEMBER_ME_FILTER" ref="DashboardFilter"></custom-filter>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider ref="DashboardAuthProvider"></authentication-provider>
</authentication-manager>
<beans:bean id="DashboardFilter" class="com.apple.store.dashboard.security.DashboardAuthFilter">
<beans:property name="authenticationManager" ref="authenticationManager"/>
</beans:bean>
<beans:bean id="authenticationEntryPoint" class="com.apple.store.dashboard.security.DashboardAuthEntryPoint">
</beans:bean>
<beans:bean id="DashboardAuthProvider" class="com.apple.store.dashboard.security.DashboardAuthProvider">
I have defined DashboardAuthProvider as such:
public class DashboardAuthProvider implements AuthenticationProvider {
private static final Logger logger = LoggerFactory.getLogger(DashboardAuthProvider.class);
#Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
logger.debug("Inside DashboardAuthProvider: authenticate method +authentication=" + authentication);
Authentication auth = null;
[...]
}
}
When I executed the code, I can hit the filter, but not provider. I read many spring security related document and couldn't find anything wrong with my configuration in xml. Could someone help?
Here is my filter:
public class DashboardAuthFilter extends AbstractAuthenticationProcessingFilter {
private static final Logger logger = LoggerFactory.getLogger(DashboardAuthFilter.class);
public DashboardAuthFilter() {
super("/**");
}
public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response)
throws org.springframework.security.core.AuthenticationException {
logger.debug("Inside DashboardAuthFilter:attemptAuthentication method:");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth!=null ){
if (auth.isAuthenticated()){
logger.debug("Previously authenticated.isAuthenticated=true::: Auth details:" +auth);
return auth;
}
}
//Validate the DS Auth Cookie
Cookie AOSCookie = WebUtils.getCookie(request, "myacinfo-uat");//
if ( AOSCookie == null )
return null;
Authentication authResult = null;
try {
if( org.apache.commons.lang.StringUtils.isEmpty(AOSCookie.toString())) {
throw new PreAuthenticatedCredentialsNotFoundException("DS Auth Cookie not found. Commence DS Authentication..");
}
String credentials = "NA";
String validateCookieDetails = correctAuthentication(AOSCookie, request);
logger.debug("validateCookieDetails ....." + validateCookieDetails);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(validateCookieDetails, credentials);
authResult = getAuthenticationManager().authenticate(authRequest);
logger.debug("Attempted authentication: authResult ::" + authResult.toString());
} catch (org.springframework.security.core.AuthenticationException e) {
logger.error("AttemptAuthentication: Not Authenticated : AuthenticationException ....." + e.getMessage());
} catch (Exception e) {
logger.error("Exception occured during authentication....." + e.getMessage());
}
return authResult;
}
}

how can i create oauth 2 username password flow over spring security

i am trying to implement oauth2 username password flow on spring security
but i cant find any documentation and sample code
i am going over sparklr and tonr insode oauth2 samples
how can i implement it oauth2 2 legged
how can i disable login form
<form-login authentication-failure-url="/login.jsp" default-target-url="/index.jsp" login-page="/login.jsp"
login-processing-url="/login.do" />
<logout logout-success-url="/index.jsp" logout-url="/logout.do" />
<anonymous />
<custom-filter ref="oauth2ProviderFilter" after="EXCEPTION_TRANSLATION_FILTER" />
</http>
The default sparklr also supports username and password flow also,
it is easy, you need to write only client client is shown below:
i succeeded in the end;
public class App {
private static RestTemplate client=getRestTemplate();
private static int DEFAULT_PORT = 8080;
private static String DEFAULT_HOST = "localhost";
private static int port=DEFAULT_PORT;
private static String hostName = DEFAULT_HOST;
public static void main(String[] args) throws IOException {
try {
testHappyDayWithForm();
} catch (Exception ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void testHappyDayWithForm() throws Exception {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("grant_type", "password");
formData.add("client_id", "my-trusted-client");
formData.add("scope", "read");
formData.add("username", "muhammed");
formData.add("password", "1234");
ResponseEntity<String> response = postForString("/sparklr/oauth/token", formData);
System.out.println( response.getStatusCode());
System.out.println(response.getHeaders().getFirst("Cache-Control"));
DefaultOAuth2SerializationService serializationService = new DefaultOAuth2SerializationService();
OAuth2AccessToken accessToken = serializationService.deserializeJsonAccessToken(new ByteArrayInputStream(
response.getBody().getBytes()));
// now try and use the token to access a protected resource.
// first make sure the resource is actually protected.
//assertNotSame(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/photos?format=json"));
// now make sure an authorized request is valid.
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, accessToken.getValue()));
//assertEquals(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/photos?format=json", headers));
}
public static ResponseEntity<String> postForString(String path, MultiValueMap<String, String> formData) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_FORM_URLENCODED));
System.out.println(getUrl(path));
return client.exchange(getUrl(path), HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(formData,
headers), String.class);
}
public static String getUrl(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
return "http://" + hostName + ":" + port + path;
}
public static RestTemplate getRestTemplate() {
RestTemplate client = new RestTemplate();
CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory() {
#Override
protected void postProcessCommonsHttpMethod(HttpMethodBase httpMethod) {
httpMethod.setFollowRedirects(false);
// We don't want stateful conversations for this test
httpMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
}
};
client.setRequestFactory(requestFactory);
client.setErrorHandler(new ResponseErrorHandler() {
// Pass errors through in response entity for status code analysis
public boolean hasError(ClientHttpResponse response) throws IOException {
return false;
}
public void handleError(ClientHttpResponse response) throws IOException {
}
});
return client;
}

Resources