Getting 302 on delete http method using rest ssured - rest-assured

I am new to rest assured testing.
I am doing authentication using cookies and the GET call is returning a 200 status but when i am doing a delete, i am getting 302. What am i doing wrong?
This works-
public void Getcall(String id){
RestAssured.useRelaxedHTTPSValidation();
String c= driver.manage().getCookies().toString();
Response response= RestAssured.given().when().baseUri("service url"+id).cookie(c).**get**
().then().extract().response();
System.out.println(response.getStatusCode());
}
This does not work- (gives 302)
public void softDeleteCal(){
RestAssured.useRelaxedHTTPSValidation();
String c= driver.manage().getCookies().toString();
Response response= RestAssured.given().when().baseUri("service url"+id").cookie(c).**delete**
().then().extract().response();
System.out.println(response.getStatusCode());
}
This is format of cookie from the chrome developers console> network tab
Cookie: VCAP_ID=fdf425dd-80e3-4820-757b-73c6; JSESSIONID=AA5B704E5DC85CACEADFF09D61084A06

Related

Preflight request fails on Chrome, Safary, Opera

I´m struggling with CORS requests on an Springsecurity backen project + Angulajs frontend.
CORS requests are working fine on IE (also with curl, wget and python requests) but miserably fail on Chrome and Safary because of Preflight bad request.
I know that those Browsers are blocking CORS POSTs, making the request empty as soon as the reach the backend, in fact I don’t see any data when I log out the request from backend. I tried every possible combination of:
Frontend side:
1) $http(method: POST)
2) $http.post(
3) Adding flags: Access-Control-Allow-Origin, Access-Control-Expose, etc.
4) Adding all possible header combination: ‘Content–Type’:’application/
Browser side:
1) Start chrome with flag: --disable-web-security
2) Installing Chrome extension CORS
Backend side:
1) Spring Security Disable csfr
2) Spring Security Permit all
3) Spring Security HttpMethod.OPTION
4) Set up a CORS Filter that accept all origins: “*”
5) Activated CORS framework for spring extending WebMvcConfigurerAdapter class.
Nothing, NHOTING worked for me!
I discussed this issue in another post: CORS POST request fails on Chrome, Safari and Firefox
I´m still unable to perform CORS requests, this is now I major issue and I suspect the problem is in LoginFilter:
public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {
private TokenAuthenticationService tokenAuthenticationService;
public JWTLoginFilter(String url, AuthenticationManager
authenticationManager) {
super(new AntPathRequestMatcher(url));
setAuthenticationManager(authenticationManager);
tokenAuthenticationService = new TokenAuthenticationService();
}
#Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws AuthenticationException, IOException, ServletException {
try {
ServletInputStream inputStream = httpServletRequest.getInputStream();
httpServletRequest.getCharacterEncoding();
AccountCredentials credentials = null;
ObjectMapper mapper = new ObjectMapper();
credentials = mapper.readValue(inputStream, AccountCredentials.class);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
return getAuthenticationManager().authenticate(token);
} catch (JsonMappingException e) {
e.printStackTrace();
throw e;
} catch (JsonParseException e) {
e.printStackTrace();
throw e;
} catch (AuthenticationException e) {
e.printStackTrace();
throw e;
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
#Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication)
throws IOException, ServletException {
AccountCredentials cred = (AccountCredentials) authentication.getPrincipal();
tokenAuthenticationService.addAuthentication(response, cred);
}
}
EDIT
the exact error on Google Chrome is:
:8000/#!/login:1 XMLHttpRequest cannot load http://localhost:8080/myApp/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 403.
So I found that it does not has ANYTHING to do with the request headers, but the problems are the response headers.
To make the preflight passing through, all response headers have to be mapped, as example:
response.addHeader("Access-Control-Expose-Headers", "xsrf-token, Authorization, Barer, Token");
The preflight request is sent AUTOMATICALLY with verb option by browser itself BEFORE the real request is sent.
You must configure your server to send response with some headers when this preflight request is sent. With spring security you can use :
#Provider
#Component
public class CrossDomainContainerResponseFilter implements ContainerResponseFilter {
#Override
public void filter(ContainerRequestContext containerRequestContext,
ContainerResponseContext containerResponseContext) throws IOException {
containerResponseContext.getHeaders().add("Access-Control-Allow-Origin", "YOUR FRONTEND URI");
containerResponseContext.getHeaders().add("Access-Control-Allow-Headers",
"Access-Control-Allow-Origin");
containerResponseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
containerResponseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
}
}
If you are using XML config, you can also use the <cors /> tag.
The --disable-web-security never worked for me on Chrome. But it worked on Vivaldi Browser.

CORS: Rest API with ASP.NET 4.5.1 MVC

I have a problem allowing cross site scripting for my application. GET requests work fine when i try to do a POST i get:
XMLHttpRequest cannot load http://localhost:49187/api/CampaignRegistration. The request was redirected to 'http://localhost:49187/Authentication/UnAuthorized?ReturnUrl=%2Fapi%2FCampaignRegistration', which is disallowed for cross-origin requests that require preflight.
My preflight request returns 200 OK (without the authentication header) but my actual request returns 302 Not Found (which contains my authentication header).
My preflight request looks like this:
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:POST
and the response is:
Access-Control-Allow-Headers:content-type
Access-Control-Allow-Origin:*
And my request payload headers are:
{Cache-Control: "no-cache", Authorization: "Basic XXXXX"}
I have enabled CORS in my WebApiConfig.cs like this (i will change the origin: * when it actually works). I removed everything related to CORS in my web.config.
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
My WebApi Controllers all extends a BasicApiController which includes a custom authenticate attribute which looks like this:
protected override bool IsAuthorized(HttpActionContext actionContext)
{
try
{
if (HttpContext.Current.Request.Headers.AllKeys.Contains("Authorization"))
{
string authHeader = HttpContext.Current.Request.Headers["Authorization"];
string cred =
Encoding.UTF8.GetString(Convert.FromBase64String(authHeader.Substring("Basic ".Length)));
string[] parts = cred.Split(':');
string userName = parts[0];
string password = parts[1];
if (userName == _configRepository.WebApiUsername && password == _configRepository.WebApiPassword)
{
return true;
}
}
return false;
}
catch (Exception ex)
{
return false;
}
}
My frontend was made using backbone.js but i really don't think the issue is on the front end side. I have tried changing the web.config to no avail, from what i gathered nothing is needed in it after enabling CORS like i did. I tried bypassing the authentication for OPTIONS methods since my application does not use OPTIONS (outside of preflight requests) but, as expected, that did nothing as the preflight request is ok even without the authentication header. If anyone has any ideas it would be greatly appreciated !
Seems the issue was client side. The authorization parameter was in the payload not in the headers.... /facepalm.

Spring Security OAuth2: CORS preflight channel did not succeed

I was receiving this error while making a call to '/oauth/token' when I was making an HTTP call to the server instance running on my own system. I fixed this by creating a filter like this:
#Component
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
HttpServletRequest httpServletRequest = (HttpServletRequest) req;
if (httpServletRequest.getMethod() != "OPTIONS") {
chain.doFilter(req, res);
} else {
// In case of HTTP OPTIONS method, just return the response
}
}
I have added it as a filter in WebConfigurer:
private void initCORSFilter(ServletContext servletContext, EnumSet<DispatcherType> disps) {
log.debug("Registering CORS Filter");
FilterRegistration.Dynamic corsFilter = servletContext.addFilter("corsFilter", new SimpleCORSFilter());
Map<String, String> parameters = new HashMap<>();
corsFilter.setInitParameters(parameters);
corsFilter.addMappingForUrlPatterns(disps, true, "/*");
corsFilter.setAsyncSupported(true);
}
I am getting this error in FireFox:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://182.176.221.94:9091/ams/oauth/token. (Reason: CORS preflight channel did not succeed).
In short I was making sure the the preflight OPTIONS call always gets a response to proceed ahead. This was working on my own system, but now that the server instance is deployed on a Linux server, I am again getting this issue. And I am getting this only on calling 'oauth/token', everything other call is working fine.
What can I possibly do to get rid of this. Any help?
Your filter does not need to be annotated with #Component and it should be mapped with adequate url pattern in WebConfigurer class like other filters used in JHipster.
Also your filter should not break the filter chain as it does for OPTIONS. It's not consistent to allow OPTIONS method in header and then to not return the headers if you are processing an OPTIONS request.
The problem was that I was using != comparison for if (httpServletRequest.getMethod() != "OPTIONS". I changed it to if (!httpServletRequest.getMethod().equalsIgnoreCase("OPTIONS")) instead and it worked. This could have something to do with the fact that I tested on local machine while running the codebase but created a WAR file out of it and deployed on the server where it didn't work. I am not sure what exactly is the reason, but this fixed the issue.

Dart request succeeding ... somehow?

I'm developing a dart application which will consume a REST service I'm building. I started writing out the dart code to perform an ajax request to my login endpoint. However, even when my dart ajax request should fail, it claims to succeed.
I don't have any services up and running (and even if I did it would be using the wrong domain / port right now), but this code gives a 200 OK HttpResponse every time:
class PlayerController {
const PlayerController();
static const String LOGIN_URL = "login";
void login(String username, String password) {
Map<String, String> headers = {"Content-Type": "application/x-www-form-urlencoded"};
String body = "j_username=$username&j_password=$password&submit=Login";
HttpRequest.request(LOGIN_URL, method: "POST", requestHeaders: headers, sendData: body)
.then((request) => processLogin(request, username))
.catchError((e) => processLoginError(e));
}
void processLogin(var whatIsThis, String username) {
query("#loginButton").text = "Logout";
//TODO get the player then set them
}
void processLoginError(var e) {
print("total failure to login because of $e");
}
}
It always hits the processLogin method, and never hits the processLoginError method. Does anyone have any idea why this would be? Should I be performing this ajax request in a different way? (If you couldn't guess, it will be signing into spring security).
I read somewhere that file system requests always succeed. Is Dart somehow making this a file system request rather than a web request?
This is because the request actually completes successfully.
Your request to "login" will actually call http://127.0.0.1:6521/[Path_to_your_Dart_file]/login
The server started by Dart when running in Dartium (127.0.0.1:6521) seems to answer to every POST request with HTTP 200 and an empty response body.
If you change the method from POST to GET, it will fail as expected.
As for why the server does this - I don't really know. This would have to be answered by the Dart team.

FormAuthentication with WebAPI using Breeze

I am protecting WebAPI using forms Authentication, that is using Breezecontroller
When i try to call WebAPi method i am getting back the following error.
status:404
statusText: "Not Found"
message:"MetaData query failed for:'';, No Http resource was found tha matches...
My question is why am i not getting back "UnAuthorized error(401)" ?
metadata is decorated with [Authorize] as well.
Seems like FormsAuthentication's redirect is giving problem.
It is redirecting to Login(has AllowAnonymous) WebApi method and reports it cannot find, eventhough i have. Also i am applying the Authrozie to the methods instead of controller. the exact error is
{"$id":"1","$type":"System.Web.Http.HttpError,System.Web.Http","Message":"NoHTTPresourcewasfoundthatmatchestherequestURI'http://localhost:40678/api/Country/Login?ReturnUrl=/api/Country/Metadata'.","MessageDetail":"Noactionwasfoundonthecontroller'Country'thatmatchestherequest."}
Just tried and working fine. I'm betting you have a mistake in your URL.
Here is the prelim to my controller:
[Authorize]
[BreezeController]
public class BreezeTodoController : ApiController
{
private readonly BreezeTodoContext _context;
public BreezeTodoController() {
_context = new BreezeTodoContext(User);
}
[HttpGet]
public string Metadata() {
return _context.Metadata();
}
// ... more
I hit it with this URL
http://localhost:32377/api/breezetodox/metadata
And I get back the 401
Request URL:http://localhost:32377/api/breezetodo/metadata
Request Method:GET
Status Code:401 Unauthorized
But if I make a mistake in the URL (see 'x' after breezetodo)
Request URL:http://localhost:32377/api/breezetodox/metadata
Request Method:GET
Status Code:404 Not Found
Same thing if my action name doesn't match (see 'x' after metadata):
Request URL:http://localhost:32377/api/breezetodo/metadatax
Request Method:GET
Status Code:404 Not Found
In other words, HTTP can't report that a resource is unauthorized if it can't find that resource in the first place.
when tagging the BreezeController with [Authorize] and then trying to retrieve the Breeze Metadata directly with this link:
Request URL:http://localhost/breeze/breeze/metadata
redirects to:
http://localhost/Login?ReturnUrl=%2Fbreeze%2Fbreeze%2Fmetadata with a 404
Without the [Authorize] the access to the Breeze metadata with the same link works fine.

Resources