Rest API call fails with status 302 (spring security, html5) - spring

I'm having 2 projects:
1) Restful Project with jdbc spring security (username:password) => port:9091
2) HTML5 Application with a JQGrid => port:9092
I have disabled csrf token in both the projects. Now, I'm able to hit the rest service successfully from browser and using postman and by passing the credentials
But when I try to hit the service from HTML5 Application (Jqgrid), I'm see that XHR Call is ending with status 302 and I'm not getting the results back.
So, please guide me on the same.

Additional Points:
I'm able to successfully hit the rest service from postman by passing basic authentication. But from JQGrid, I'm not able to query data even after using below code in my JQGrid. It always goes to status 302. (An FYI, I'm using stateless authentication in my spring security) :
loadBeforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Authorization", CURRENT_AUTH_KEY);
},
beforeSend: function (request)
{
request.withCredentials = true;
request.setRequestHeader("Authorization", CURRENT_AUTH_KEY);
},
ajaxEditOptions: {
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Authorization", CURRENT_AUTH_KEY);
}
},
ajaxGridOptions: { Authorization: CURRENT_AUTH_KEY } ,

Related

Spring Keycloak Adapter sometimes returns with "Token is not active" when uploading files

lately we are facing an issue that our Spring Boot backend service (stateless REST service) SOMETIMES returns an HTTP 401 (Unauthorized) error when users try to upload files >70 MB (or in other words, when the request takes longer than just a couple of seconds). This does not occur consistently and only happens sometimes (~every second or third attempt).
The www-authenticate header contains the following in these cases:
Bearer realm="test", error "invalid_token", error_description="Token is not active"
Our Spring (Boot) configuration is simple:
keycloak.auth-server-url=${KEYCLOAK_URL:http://keycloak:8080/auth}
keycloak.realm=${KEYCLOAK_REALM:test}
keycloak.resource=${KEYCLOAK_CLIENT:test}
keycloak.cors=true
keycloak.bearer-only=true
Essentially, our frontend code uses keycloak-js and does the following to keep the access token fresh:
setInterval(() => {
// updates the token if it expires within the next 5s
this.keycloak.updateToken(5).then((refreshed) => {
console.log('Access token updated:', refreshed)
if (refreshed) {
store.commit(AuthMutationTypes.SET_TOKEN, this.keycloak.token);
}
}).catch(() => {
console.log('Failed to refresh token');
});
}, 300);
Further, we use Axios and a respective request filter to inject the current token:
axios.interceptors.request.use(
(request: AxiosRequestConfig) => {
if (store.getters.isAuthenticated) {
request.headers.Authorization = 'Bearer ' + store.getters.token;
}
return request;
}
);
This worked very well so far and we have never experienced such a thing for our usual GETs/POSTs/PUTs etc. This happens only when users try to upload files larger than (around) 70MBish.
Any hint or tip how to debug this any further? We appreciate any help...
Cheers

POST request doesn't get response from server in chrome but work in postman

I'am making a POST request to spring boot endpoint and wanna get data return from server.With testing my API in Postman,it works good.but when testing it in
chrome,it doesn't even get a response and chrome NETWORK bar even did't have record.
so code is simple,I can't find any problem,RestController
#PostMapping("/signup")
public User signup(#RequestBody ModelUser user){
//fetch data from DTO and craft a user
User userData=user.adapter();
//...code here omit for sake of brevity
return userData;
}
it indeed get data from ajax,when I use logger(slf4j) to debug.
and ajax:
$("#sign-up").submit(function () {
var userInfo={}
userInfo["phone"]=$("#phone").val()
userInfo["password"]=$("#password").val()
$.ajax({
//ajax successful send to spring boot endpoint
type:"POST",
contentType:"application/json",
url:"http://localhost:8080/signup",
data:JSON.stringify(userInfo)
}).then(
function(){
//this doesn't print in console
console.log("Hello Callback is executed")
}
)
})
weird as it is,I never encounter this when I use GET request,since ajax callback is successfully called when I use GET to test a GetMapping endpoint.
oh,with lots of similar questions
AJAX POST request working in POSTMAN but not in Chrome
Angular 4 POST call to php API fails, but GET request work and POST requests work from Postman
POST response arrives in Postman, but not via Ajax?
I don't get any response status code in chrome and completely not involved CORS in question
Have you tried adding a consumes and produces media type of Json in the Java
#PostMapping(path="/signup", consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
And explicitly set the Accept header in the javascript
$.ajax({
//ajax successful send to spring boot endpoint
type:"POST",
headers: {Accept : "application/json"},
contentType:"application/json",
url:"http://localhost:8080/signup",
data:JSON.stringify(userInfo)
})
I'am sorry for my poor front end skill,the main reason is that I don't understand Javascript event.
$("#sign-up").submit(function (e) {
//e.preventDefault();
var user={};
user["phone"]="187308";
user["name"]="icywater";
$.ajax({
type:'POST',
contentType:'application/json',
data:JSON.stringify(user),
url:"http://localhost:8080/test"
}).done(function(data){
console.log("Hello Callback is executed");
console.log(data)
});
});
here when I click submit It actually already submit the form and don't wait ajax code to be executed,so I should use e.preventDefault()to suppress default behavior.It's nothing
related about POST or postman ,it is about the form submit default behavior,ahh,Oolong event.
I got it when I found this page

Ember acceptance test not working with AJAX

I'm starting to add acceptance tests to my Ember project. Starting off with one which tries to log-in to my app:
import { test } from 'ember-qunit';
import moduleForAcceptance from '../helpers/module-for-acceptance';
moduleForAcceptance('Acceptance | login');
test('logging in', function(assert){
visit('/login');
andThen(function(){
assert.equal(currentURL(), '/login');
});
fillIn('#login input[name=email]', 'my#email.com');
fillIn('#login input[name=password]', 'password');
click('#login button[type=submit]');
andThen(function(){
assert.equal(currentURL(), '/dashboard');
});
});
But it fails because the AJAX call to my REST API for authentication fails. This works fine when the app is running normally, but not when done through an acceptance test.
I've traced it back to the following error being returned by ember-ajax:
Ember AJAX Request POST https://127.0.0.1:8081/login returned a 0\nPayload (Empty Content-Type)\n""
My API isn't even getting the call, so this seems to be an error with sending the REST request. I've checked the hash object in node_modules/ember-ajax/addon/mixins/ajax-request.js just before it's sent through to the jQuery AJAX method:
{ type: 'POST',
data: { email: 'my#email.com', password: 'password' },
url: 'https://127.0.0.1:8081/login',
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
headers: { Authorization: 'Bearer undefined; PublicKey Ab732Jte883Jiubgd84376HhhndikT6' } }
contentType is defined. This is also exactly how hash looks when making the same AJAX call with the app running normally.
So what is there about Ember acceptance tests which would specifically prevent AJAX calls from working? I suspect there's a config or environment property I'm unaware of that I need to change/set to get it working.
I'm running:
ember-cli: 2.8.0
node: 4.5.0
ember-ajax: 2.5.1
ember-cli-qunit: 3.0.1
phantomjs: 2.1.7
What an eejit! My local REST API has an invalid SSL certificate. So I just needed to tell PhantomJS to ignore SSL errors in my testem.js file:
"phantomjs_args": [
"--ignore-ssl-errors=true"
],

How come I keep getting a "Request failed with response code 401" when trying to push via Urban Airship?

I have double, triple, and quadruple checked that I have the right master key that I'm passing. My parameters are taking directly from the UA website also so it can't be that. Anyone see what I'm doing wrong here???
Parse.Cloud.define("sendPush", function(request, response) {
var Buffer = require('buffer').Buffer;
var parameters = {
"audience" : "all",
"device_types" : "all",
"notification" : {
"alert" : "Hello from Urban Airship."
}
};
var params = JSON.stringify(parameters);
Parse.Cloud.httpRequest({
url: "https://go.urbanairship.com/api/push/",
method: 'POST',
headers: {
"Content-Type" : "application/json",
"Authorization" : 'Basic ' + new Buffer('MASTER_KEY').toString('base64'),
"Accept" : "application/vnd.urbanairship+json; version=3;"
},
body: params,
success: function(httpResponse) {
response.error(httpResponse);
},
error: function(httpResponse) {
response.error('Request failed with response code ' + httpResponse.status);
}
});
});
I've also tried adding in APP_SECRET:
"Authorization" : 'Basic ' + new Buffer('APP_SECRET':'MASTER_KEY').toString('base64'),
It's not clear from your code sample if you are including the app key in your request. API requests to Urban Airship use HTTP basic authentication. The username portion is the application key and the password portion in this case is the master secret. The application secret is restricted to lower-security APIs and is for use in the distributed application. The master secret is needed for sending messages and other server API requests.
Urban Airship provides a guide for troubleshooting common API issues.
I had the same problem and tried to figure it out by Network diagnosing tools for more than two days. Because after debugging I checked that I send the right credentials to UA. After all I called the UA and ask them to check the Credentials (in my case was appKey and appToken for streaming with java-connect API) if they are still valid. They checked and approved the validation but just in case sent me a new credentials. And I could connect with the new credentials!
It is for sure a bug by UA because I tested the whole time by another test application, which was a Desktop java application and I could connect to the server (with the same appKey and appToken) and get the events, but I got 401 error in my main Application, which was a Web Application running on TomCat 8.0 . It means It worked in a same time in with the same credential for one application and did not work for another application.

Mobile Hybrid application throws 500 error for all POST requests to JIRA Server

I have a Hybrid application using cordova and angular that utilizes the JIRA rest service. I am doing a simple call to add a comment to a JIRA ticket using ajax. All calls were working until the recent upgrade to JIRA 7. After the upgrade all calls except POST still succeed.
var data = {
"body": "quick comment",
};
var req = {
method: 'POST',
url: 'https://our.jiraserver.com/jira/rest/api/2/issue/{issuekey}/comment',
headers: {
'Authorization': 'Basic garbeldygoopasdfasdf',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*'
},
data: data
};
$http(req).then(function(response){
console.log('success', response);
}, function(error){
console.log('errpr', error);
});
A trimmed version of the error the server is throwing (for those TL;DR's)
message: "Expected authority at index 7: file://"
stack-trace: "java.lang.IllegalArgumentException: Expected authority at index 7: file://↵ at java.net.URI.create(URI.java:852)↵ at com.atlassian.applinks.cors.auth.DefaultCorsService.getApplicationLinksByOrigin(DefaultCorsService.java:56)↵ at com.atlassian.applinks.cors.auth.AppLinksCorsDefaults.allowsOrigin(AppLinksCorsDefaults.java:42)↵ at com.atlassian.plugins.rest.common.security.jersey.XsrfResourceFilter$1.apply(XsrfResourceFilter.java:255)↵ at com.atlassian.plugins.rest.common.security.jersey.XsrfResourceFilter$1.apply(XsrfResourceFilter.java:252)↵ at com.google.common.collect.Iterators.indexOf(Iterators.java:778)↵ at
I will note again these calls worked until very recently... as a workaround I setup a node/express servers to simply bounce my api calls through. I send the data there, it makes the same request and succeeds and passes the data back to my app. Of course this isn't ideal as I now have a split code base.
I went to Atlassian support who basically told be they cannot assist with third-party development.
Any suggestions or help would be greatly appreciated.

Resources