Request works in postman not IONIC - java

I'm developing an ionic app with a back-end with Java spring Boot with Spring security on it. When I tried to get a token with postman everything went well but in ionic, I got a 401 HTTP code. I have no cors problem, I have disabled it in my browser.
Here is the code from Ionic:
login() {
return new Promise((resolve, reject) => {
var credentials = "grant_type=password" + "&username=admin" + "&password=admin";
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
headers.append('Authorization', 'Basic c2NhbnRhYm91ZmZlOlhZN2ttem9OemwxMDA=');
console.log(headers.toString);
this.http.post('http://localhost:8443/oauth/token', credentials, {
headers: headers
})
.subscribe(res => {
console.log(res);
let data = JSON.parse("" + res.toString); // res.json();
this.token = data.token;
this.storage.set('token', data.token);
resolve(data);
resolve(JSON.parse("" + res.toString) /* res.json() */ );
}, (err) => {
reject(err);
});
});
}
Thx for yr help I'm stuck on it for more than 3 weeks

Related

React cookie integration with spring

I have a website, backend is in spring, frontend is in React. I save a cookie on backend using
Cookie cookie = new Cookie("userId", testDTO.getId());
userCookie.setPath("/");
response.addCookie(userCookie);
But when react posts request on the controller, my browser doesnt get that cookie. Storage in firefox is just empty.
Frontend code:
const requestOptions = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
name: username,
stayLogged: false
})
};
fetch('http://localhost:8080/health-check/post',requestOptions)
.then(response => response.json())
.then(data =>{console.log(data);})
I fixed it. Just added to the post mapping in the controller
#CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")

How to pass parameters from cordova HTTP to Spring controller

In my ionic 5.0.0 application I'm using cordova's native HTTP to make the rest calls. Below is the code snippet of my logout function.
But when i execute this function i'm getting following error.
"advanced-http: \"data\" argument supports only following data types: String"
logout() {
this.setData("url", "/web/oauth/revoke-token");
let apiUrl = this.getBaseUrl() + this.getData("url");
const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Authorization': 'Basic Y2hyR3liUnBxQUR3X2VDemw5dzc0cHU4dXNnYTpKdmZ1azgyYnBUQlVnNDJ6NU1hZFhXOWJPeElh'
};
const params = {
'companyId': this.getData("COMPANY_ID"),
'token': this.getData("ACCESS_TOKEN"),
'client_id': this.getData("CLIENT_ID"),
'token_type_hint': 'access_token'
};
this.nativeHttp.post(apiUrl, params, headers).then(response => {
console.log("success response: "+response);
})
.catch(error => {
console.log("error response: "+error);
});
console.log("finished");
}
Here is my Spring controller which receives the params.
#RequestMapping(value = "/oauth/revoke-token", method = RequestMethod.POST)
#ResponseBody
public ResponseEntity<Object> logout(HttpServletRequest request) {
String clientId = request.getParameter(OAuth2Constants.CLIENT_ID);
String token = request.getParameter(OAuth2Constants.TOKEN);
String tokenTypeHint = request.getParameter(OAuth2Constants.TOKEN_TYPE_HINT);
String companyId = request.getParameter(WebConstants.COMPANY_ID_PARAMETER);
}
But unfortunately all params receives in the controller as null.
Can someone help me?
Finally I found a solution for the issue. Simply set the data serializer for http request as follows before doing the post call.
this.nativeHttp.setDataSerializer( "urlencoded" );

JWT - No authorization is added in the header in browser

I am using JWT and Spring security for developing a Forum Application. I am getting 403 error when accessing users' endpoints. It happened after the merge, previously everything working properly. The endpoint works properly from POSTMAN but the issue occurs when accessing from browser
Nothing in the code has been mixed up, now the Authorization header is not added to the request, but only in the endpoints for users, in other cases, it works. The bare token is stored at the local storage of the browser. What could be the reason for something like that?
Angular interceptor adding authorization header:
intercept(request: HttpRequest<any>, next: HttpHandler) {
const authHeader = AUTHORIZATION_HEADER;
const accessToken = this.authService.getAuthorization();
if (accessToken !== null) {
request = request.clone({
headers: request.headers.set(authHeader, accessToken),
withCredentials: false
});
}
return next.handle(request);
}
}
Angular Auth Service
login(userCredentials: UserCredentials): Observable<any> {
return this.http
.post<AccountInfo>(`${API_URL}/login`, userCredentials, { observe: 'response' })
.pipe(
tap((response: HttpResponse<AccountInfo>) => {
const token = response.headers.get(AUTHORIZATION_HEADER);
this.storeAuthorization(token);
const body = response.body;
this.storeAccountInfo(body);
})
);
}
getAuthorization(): string {
return localStorage.getItem(AUTHORIZATION_KEY);
}
private storeAuthorization(authToken: string) {
localStorage.setItem(AUTHORIZATION_KEY, authToken);
}
private storeAccountInfo(accountInfo: AccountInfo) {
localStorage.setItem(USERNAME_KEY, accountInfo.username);
localStorage.setItem(ROLE_KEY, accountInfo.role.toString());
}
Here is the git repo containing the source code
https://github.com/PatrykKleczkowski/Forum/tree/feature/improvments

React-native-uploader Android Errors

I'm currently trying to debug a react-native package (react-native-uploader) I'm using to try and upload a bundle of files (photos). Despite working on ios, the current implementation is returning the following error for android:
Response{protocol=http/1.1, code=405, message=Method Not Allowed, url=${config.apiBase}/load/${this.props.id}/uploadconfirmation}
The error is originating from this line in the package:
Response response = client.newCall(request).execute();
Where the client is:
private final OkHttpClient client = new OkHttpClient()
Where request is:
Request{method=POST, url=${config.apiBase}/load/${this.props.id}/uploadconfirmation, tag=null}
I've successfully made posts to the endpoint using formdata:
let tData = new FormData();
const that = this;
tData.append("confirmation_doc", {
uri: files[0].filepath,
type: "image/jpeg",
name: "confirmation_doc.jpg",
});
axios.post(
`${config.apiBase}/load/${this.props.id}/uploadconfirmation`,
tData
)
.then(response => {
Alert.alert(
"Success",
"Uploaded Successfully!",
[{ text: "OK", onPress: () => that.props.close() }],
{ cancelable: false }
);
});
I've tried looking through the source code to determine where things are falling apart and it seems like everything is posting as it should (headers look good, method looks good, endpoint looks good). I'm not all too familiar with Java so any input would be appreciated.
HTTP 405 Method Not Allowed ... is a client-side error.
The method received in the request-line is known by the origin server but not supported by the target resource.
if the JavaScript works, but the Java won't... you might be looking for the MultipartBuilder
... in combination with MediaType.FORM.
In order to solve this issue, I had to abandon the react-native-uploader package I had been using. Below is how I managed to resolve the issue:
let tData = new FormData();
this.state.selectedImages.forEach((item, i) => {
tData.append("doc[]", {
uri: item.uri,
type: "image/jpeg",
name: item.filename || `filename${i}.jpg`,
});
});
fetch(`${config.apiBase}/load/${this.props.id}/uploadconfirmation`, {
method: "post",
headers: {
Accept: "application/x-www-form-urlencoded",
Authorization: `Token ${this.props.token}`,
},
body: tData,
})
.then(res => res.json())
.then(res => {
Alert.alert(
"Success",
"Uploaded Successfully!",
[{ text: "OK", onPress: () => that.props.close() }],
{ cancelable: false }
);
})
.catch(err => {
console.error("error uploading images: ", err);
});

Angularjs http no response from Spring Boot

I'm trying to develop a small application to create index on local elasticsearch engine. I use angularjs on the front-end, and spring-boot on the back-end. It can create index successfully, however, when I want to retrive the response in the front-end, it keeps throwing me errors.
Below is my AngularJS api call:
app.service('ESIndexService', function($http) {
this.createESIndex = function(esindexObj) {
var settings = {
method: 'POST',
url: BASE_URL + "/ESIndex/createESIndex",
data: esindexObj
};
return $http(settings).then(function(response) {
console.log("response:"+response);
return response;
}, function(error) {
console.log("error:"+error);
return error;
});
};
});
Then this is my controller:
#CrossOrigin
#RestController
#RequestMapping(value = "ESIndex")
public class ESIndexController {
#RequestMapping(value = "createESIndex", method = RequestMethod.POST)
public #ResponseBody String createIndex(#RequestBody ESIndex esIndex) {
try {
Settings settings = Settings.builder()
.put("xpack.security.user", String.format("%s:%s", Constants.ES_UNAME, Constants.ES_PWD)).build();
TransportClient client = new PreBuiltXPackTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(Constants.ES_HOST), Constants.ES_PORT));
CreateIndexResponse response = client.admin().indices().prepareCreate(esIndex.getName()).setSettings(Settings.builder()
.put("index.number_of_shards", esIndex.getNumberOfShards())
.put("index.number_of_replicas", esIndex.getNumberOfReplicas())).get();
client.close();
if(response.isAcknowledged() && response.isShardsAcked())
return Constants.SUCCESS;
else
return "Fail to create index!";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
I want to get the response status and data in AngularJS response. However, it keeps throwing me errors:
error:SyntaxError: Unexpected token i in JSON at position 0
I'm not using JSON.parse function, why it gives me error like this?
After adding responseType: 'text', still throwing same error, the chrome nextwork
It turns out I need to add "transformResponse: undefined", however, in another of my project, I never did this. What's the difference?
AngularJS:
this.newBlog = function(blogObj) {
var settings = {
method: 'POST',
url: baseUrl + "/blog/newBlog.do",
data: blogObj
}
return $http(settings).then(function(response) {
return response;
}, function(error) {
return error;
});
};
Java Controller:
#RequestMapping(value="newBlog.do", method=RequestMethod.POST)
public #ResponseBody String newBlog(#RequestBody Blog blog, HttpServletRequest request) {
User createdBy = (User) request.getSession().getAttribute("user");
if(createdBy == null)
return NO_SESSION_MSG;
else {
createdBy.setPwd(null);
blog.setCreatedAt(TQBUtilities.getCurrentTime());
blog.setLastUpdatedAt(TQBUtilities.getCurrentTime());
blog.setCreatedBy(createdBy);
return blogService.newBlog(blog);
}
}
Angular is automatically trying to parse the server response as JSON. Try adding this to your settings object
responseType: 'text'
So
var settings = {
method: 'POST',
url: BASE_URL + "/ESIndex/createESIndex",
data: esindexObj,
responseType: 'text'
};
#jheimbouch add "transformResponse: undefined" to http call, like below, works fine:
var settings = {
method: 'POST',
url: BASE_URL + "/ESIndex/createESIndex",
data: esindexObj,
transformResponse: undefined
};
However, why it is required in angularjs 1.6.2? When I was using AngularJS 1.4.8, I don't need to add transformResponse attributes.

Categories

Resources