Playframework 2.8 setSession works on Postman, but not on browser - scala

I've been working on an api project on Scala Playframework 2.8.
Everything seems to work fine on Postman, but when trying to connect it to my frontend project, .withSession doesn't create any cookie in the browser although it does create one in Postman.
I thought it had something to do with the csrf and cors definitions on the api's application.conf but I've edited it a lot and nothing works.
I'm getting no errors, just don't get the session to be set in the client, so i can't log-in anyone to the api :\
I'm sharing my application.conf code:
# https://www.playframework.com/documentation/latest/Configuration
# Default database configuration using MySQL database engine
# Connect to playdb as playdbuser
db.default.driver=com.mysql.jdbc.Driver
db.default.url="blabla"
db.default.username="blalba"
db.default.password="blabla"
play.http.session.secure = false
play.http.session.cookieName = "PLAY_SESSION"
play.http.session.httpOnly = true
play.filters.disabled+=play.filters.csrf.CSRFFilter
play.cache.bindCaches = ["db-cache"]
play.filters.hosts {
allowed = ["."]
}
play.filters.enabled += "play.filters.cors.CORSFilter"
play.filters.cors {
allowedHttpMethods = ["GET", "HEAD", "POST", "PUT", "OPTIONS"]
allowedHttpHeaders = ["Accept", "Content-Type"]
}
play.http.secret.key = "blablabla"
Anyone has an idea why the browser blocks me from creating the session from the Scala playframework 2.8 api?

Got it. (I feel so stupid :/)
The problem wasn't with the backend, Play was working as expected.
The problem was with the frontend (react.js).
Once I added credentials: 'include' to the fetch call, it worked.
Started realising the problem is not in the backend thanks to #cbley's response, so thank you for that.

Related

Unable to access Rest URL using scalaj-Http client with SSL certificates(JKS File)

I am new to Scala. I am trying to access REST API URl and trying to get json data from there using Scalaj-Http with Spark framework in local vm(Intellij). But with the following Code I am always getting Http error code 401 from code and the server log is responding with "new ssl session,TLS V1.2 No Client Cert.
The jks file that I am using seems ok with proper SSL Handshake and its installed on server side.
val url = "https://abcdef:1234/api/v1/get?q=abc"
val alias ="xxxxxx-1234 yyyyy"
val sslFactory = SSLFactory.builder()
.withIdentityMaterial("abc.jks","pass".tocharArray)
.withTrustMaterial("abc.jks","pass".tocharArray)
.withClientIdentityRoute(alias,url)
.build()
val optn = HttpOptions.sslSocketFactory(sslfactory.getSslSocketfactory)
val res = Http(url) //Here getting 401 res.code
.option(optn)
.option(HttpOptions.allowUnsafeURL)
.asString
Tried everything but unable to solve. Kindly help please
I got the code working as I have to discard this option option(HttpOptions.allowUnsafe
URL)
Thanks

RESTful call testing in Eclipse

In my case, I am running a eclipse project providing the Restful api, and I will call that api like in the following example. I am curious if I should create another project in the eclipse to run the following code to test the api.
Jersey Example
Form form = new Form();
form.add("x", "foo");
form.add("y", "bar");
Client client = ClientBuilder.newClient();
WebTarget resource = client.target("http://localhost:8080/someresource");
Builder request = resource.request();
request.accept(MediaType.APPLICATION_JSON);
Response response = request.get();
if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
System.out.println("Success! " + response.getStatus());
System.out.println(response.getEntity());
} else {
System.out.println("ERROR! " + response.getStatus());
System.out.println(response.getEntity());
}
you can run your code as a java application using main method.
Or since you are saying you have you services running you can use POSTMAN REST Client available as a plugin for chrome and chromium browsers. i don't know about the support for the same in other browsers.
Using postman you'll be able to see exactly how your restful service is working. you'll be able to send request headers and other parameters as a part of the rest request. Postman is the way to go for end to end web service testing.

production build of ember app works, but when using ember serve, cookies not sent to api

I have a rest API running on localhost:8001/my_app/api/, and I have apache setup to reverse proxy it from localhost/my_app/api. That's working fine.
In order to have permissions to do anything with the api, it requires my session cookie, my csrftoken cookie and a X-CSRFToken HTTP header. I've configured adapters/application.js as follows:
adapters/application.js
import Ember from 'ember';
import DRFAdapter from './drf';
export default DRFAdapter.extend({
headers: Ember.computed(function() {
return {
'X-CSRFToken': Ember.get(document.cookie.match(/csrftoken\=([^;]*)/), '1'),
};
}).volatile(),
ajax: function(url, method, hash) {
hash = hash || {}; // hash may be undefined
hash.crossDomain = true;
hash.xhrFields = {withCredentials: true};
return this._super(url, method, hash);
}
});
If I do a ember build -prod and copy the contents of the dist dir to /var/www/myApp/, apache serves my app, and it works just fine.
It's when I try to use ember-cli's builtin development server where I run into problems. I'm getting 403 errors from my api. It turns out that while the X-CSRFToken header is being sent neither of my cookies are. If I look in my chrome developer tools, it shows that I have both cookies - they simply aren't in the request headers. They're both from localhost, so I'm a bit confused.
Also, I currently I have CORS on my rest backend setup. Here are the headers I'm currently receiving:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:4200
I thought that since allow-credentials == true and allow-origin != * that cookies were supposed to be allowed. sigh.
Here's my API_HOST and contentSecurityPolicy:
config/environment.js
if (environment === 'development') {
ENV.APP.LOG_TRANSITIONS = true;
ENV.APP.API_HOST = "http://localhost"
ENV.contentSecurityPolicy = {
'default-src': "'none'",
'script-src': "'self' 'unsafe-eval' localhost",
'font-src': "'self'",
'connect-src': "'self' localhost",
'img-src': "'self'",
'style-src': "'self'",
'media-src': "'self'"
};
}
As you can see above, the api requests are being sent through my reverse proxy. I've played around with ember serve --proxy trying both http://localhost:80/ and http://localhost:8001/ but neither have helped. I've also tried setting my development ENV.API_HOST = 'http://localhost:8001/'; with and without the various proxy values.
This edit, build, deploy, refresh my browser, test, & repeat process is REALLY slow and getting old REALLY fast.
Could someone please explain to me how to get the ember-cli development server to properly access my rest api?

Spring security rest plugin: token based authentiction

I am trying to get successfully integrate Spring security rest plugin
But I am constantly failed,I am using the memcahed for token storage. Config.groovy Setup which I used to implement the plugin is :
//login end point url
grails.plugin.springsecurity.rest.login.active=true
grails.plugin.springsecurity.rest.login.endpointUrl='/api/login'
grails.plugin.springsecurity.rest.login.failureStatusCode='401'
//for memcached
grails.plugin.springsecurity.rest.token.storage.useMemcached=false
grails.plugin.springsecurity.rest.token.storage.memcached.hosts='localhost:11211'
grails.plugin.springsecurity.rest.token.storage.memcached.username=''
grails.plugin.springsecurity.rest.token.storage.memcached.password=''
grails.plugin.springsecurity.rest.token.storage.memcached.expiration=3600
//token generation
grails.plugin.springsecurity.rest.token.generation.useSecureRandom=true
grails.plugin.springsecurity.rest.token.generation.useUUID=false
I making a request on /api/login via Post man rest client with
{
"username": "john.doe",
"password": "dontTellAnybody"
}
json data but it gives me spring security auth page's html in response, Am I doing some wrong configuration?Is there any futher configuration is required.I mentioned that I am using memcache for token storage.Any Idea will be helpfull for me.
Edit: please see the logs file
Edit2 : please check this log file

Rest assured with digest auth

I have a working spring-mvc application with rest services and some rest-assured tests which are fine :
#Test
public void createFoobarFromScratchReturns201(){
expect().statusCode(201).given()
.queryParam("foo", generateFoo())
.queryParam("bar", generateBar())
.when().post("/foo/bar/");
}
=> OK
Then I implemented a digest authentication. Everything is working well, now I have to log in to use my services :
curl http://localhost:8089/foo/bar
=> HTTP ERROR 401, Full authentication is required to access this resource
curl http://localhost:8089/foo/bar --digest -u user_test:password
=> HTTP 201, CREATED
But when I try to upgrade my tests with the most obvious function, I still have a 401 error :
#Test
public void createFoobarFromScratchReturns201(){
expect().statusCode(201).given()
.auth().digest("user_test", "password") // Digest added here
.queryParam("foo", generateFoo())
.queryParam("bar", generateBar())
.when().post("/foo/bar/");
}
=> Expected status code <201> doesn't match actual status code <401>
I found some clues with the preemptive() function, but it seems to be only implemented for basic :
// Returns an AuthenticatedScheme and stores it into the general configuration
RestAssured.authentication = preemptive().basic("user_test", "password");
// Try a similar thing, but it didn't work :
RestAssured.authentication = RestAssured.digest("user_test", "password");
Currently, I am trying to achieve two things :
I need to upgrade a couple of my tests to support digest
I need to amend the #Before of the rest of my tests suites (whose are not related to auth issues), to be already logged in.
Any ideas or documentation ?
Try enabling support for cookies in the HTTP client embedded inside Rest Assured with:
RestAssuredConfig config = new RestAssuredConfig().httpClient(new HttpClientConfig().setParam(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH));
expect().statusCode(201).given()
.auth().digest("user_test", "password") // Digest added here
.config(config)
.queryParam("foo", generateFoo())
.queryParam("bar", generateBar())
.when().post("/foo/bar/");
The HTTP client (and therefore Rest Assured) supports digest authentication and the configuration of RestAssured using the digest method works well.