How can we catch unauthorized exception which been thrown by quarkus - graphql

I am facing this problem but don't know how to achieve it.
I have a graphql endpoint to fetch list of user, it already enabled authentication check.
Basically, when I send a request fetchUsers without authorization header it will throw exception or status code to let the user know, but currently, it just response
{
"errors": [
{
"message": null,
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"fetchUsers"
],
"extensions": {
"classification": "DataFetchingException"
}
}
],
"data": {
"fetchUsers": null
}
}
And in the backend server, there have some exception throw:
SRGQL012000: Data Fetching Error: io.quarkus.security.UnauthorizedException
at io.quarkus.security.runtime.interceptor.check.AuthenticatedCheck.apply(AuthenticatedCheck.java:28)
at io.quarkus.security.runtime.interceptor.SecurityConstrainer.check(SecurityConstrainer.java:28)
at io.quarkus.security.runtime.interceptor.SecurityConstrainer_Subclass.check$$superforward1(SecurityConstrainer_Subclass.zig:100)
at io.quarkus.security.runtime.interceptor.SecurityConstrainer_Subclass$$function$$1.apply(SecurityConstrainer_Subclass$$function$$1.zig:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:54)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.proceed(InvocationInterceptor.java:62)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.monitor(InvocationInterceptor.java:49)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor_Bean.intercept(InvocationInterceptor_Bean.zig:521)
Is there any way to catch this Unauthorized exception and custom it, to response 401 and the error message that we want to response.

Related

Micronaut GraphQL: How to respond with a non-200 HTTP status code from within GraphQL handler?

Following the docs and here's my exception handler (Kotlin):
#Produces
#Singleton
#Requirements(Requires(classes = [ForbiddenException::class, ExceptionHandler::class]))
class ForbiddenExceptionHandler : ExceptionHandler<ForbiddenException, HttpResponse<*>> {
override fun handle(request: HttpRequest<*>, exception: ForbiddenException): HttpResponse<*> {
return HttpResponse.status<String>(HttpStatus.FORBIDDEN, exception?.message)
}
}
Throwing a ForbiddenException from within my GraphQL handler bubbles the message into the response body, but the status code is always 200.
Example response:
{
"errors": [
{
"message": "Exception while fetching data (/createUser) : FORBIDDEN",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"createUser"
],
"extensions": {
"classification": "DataFetchingException"
}
}
],
"data": null
}
Micronaut version: 1.3.3
Micronaut GraphQL version: 1.3.0.RC1
Disclaimer:
GraphQL is not REST. You are here asking a question related to the core foundation of graphql specification (and any implementations of graphql in general).
They made the choice to embed most errors encountered in the execution of the queries but yet always return a 200 HTTP status. Therefore, you won't be able to change that in your project. It is not a configuration of graphql-java.
The good news is that the format of errors is known. Therefore, you are able to deserialize the error return payload in your application and handle correctly any error that would be thrown by graphql.
Please have a look at this link for in-depth explanations about the main difference between REST and Graphql.

How to handle Exception and return proper HTTP code in Spring webflux?

I have a method which gives response using Mono.fromfuture(result) and which throws CustomException with 400 as status.
Now in my service class, when I call that method, the error and code I am throwing there is not getting propagated to my client(postman). Only the message is what I am seeing.
I am getting this below format: -
{
"timestamp": "2019-02-01T11:13:32.748+0000",
"path": "/some_url",
"status": 500,
"error": "Internal Server Error",
"message": "Unable to fetch Response"
}
Expectation (what I want to achieve) : -
{
"timestamp": "2019-02-01T11:13:32.748+0000",
"path": "/some_url",
"status": 400, // (my own status)
"error": "INVALID_ARGUMENT", // (my own error)
"message": "Unable to fetch Response"
}
My Code:-
public Mono<ResponseObject> fetchResponse(arg) {
return Mono.just(somedata which will give exception)
.flatMap(k -> callExternalService(k))
.onErrorMap(e -> Mono.error(
new BusinessException("Unable to fetch Response", e))
*/* e here is giving :-
"code" : 400,
"message" : "Request contains an invalid argument.",
"status" : "INVALID_ARGUMENT" */*
}
Have you looked at the documentation of the Response class?
You can create a Response of your own, using the static methods in the doc, and send it, instead of Mono.error, in the onErrorMap.
You have to return something like below:
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(klass, Klass.class);
ServerResponse.status(status).build();//read doc and set for yourself
You can also check this link.

GoCardless API using Classic ASP

I'm creating the following request in vbscript and sending to the gocardless sandbox:
url="https://api-sandbox.gocardless.com/"
typ="GET"
Set xml = Server.CreateObject("MSXML2.ServerXMLHTTP")
xml.Open typ, url, False
xml.setRequestHeader "Authorization", "Bearer " & GCAccessToken
xml.SetRequestHeader "GoCardless-Version", "2015-07-06"
xml.SetRequestHeader "Accept","application/json"
xml.SetRequestHeader "Content-Type", "application/json"
xml.Send
GetGC = xml.responseText
Set xml = Nothing
The response I always get despite any tweaks I do is:
{"error":{"message":"not found","errors":[{"reason":"not_found","message":"not found"}],"documentation_url":"https://developer.gocardless.com/api-reference#not_found","type":"invalid_api_usage","request_id":"0AA4000DECCD_AC121CEB1F90_5BE18701_19AD0009","code":404}}
Any help would be appreciated. Have successfully done similar for Stripe but now need to use GC.
If you read the response from the API
{
"error": {
"message": "not found",
"errors": [{
"reason": "not_found",
"message": "not found"
}
],
"documentation_url": "https://developer.gocardless.com/api-reference#not_found",
"type": "invalid_api_usage",
"request_id": "0AA4000DECCD_AC121CEB1F90_5BE18701_19AD0009",
"code": 404
}
}
The error appears to be a HTTP status code (as is common with RESTful APIs) - 404 Not Foundlooking at the documentation link provided in the response;
404
Not Found. The requested resource was not found or the authenticated user cannot access the resource. The response body will explain which resource was not found.
So the issue could be;
You have failed to authenticate using the token in the code provided.
You authenticated but don't have permission to access the resource.
The resource you are looking for does not exist.
In this particular instance, I would suggest it is because the resource doesn't exist as the code doesn't specify a resource, only the base URL of the API which won't constitute an API endpoint you can interact with.
Looking at the documentation it's clear you need to provide a valid endpoint in the URL, at the time of writing there are 15 core endpoints to interact with along with 2 helper endpoints.
For example, a create payment request/response would look like;
POST https://api.gocardless.com/payments HTTP/1.1
{
"payments": {
"amount": 100,
"currency": "GBP",
"charge_date": "2014-05-19",
"reference": "WINEBOX001",
"metadata": {
"order_dispatch_date": "2014-05-22"
},
"links": {
"mandate": "MD123"
}
}
}
HTTP/1.1 201 (Created)
Location: /payments/PM123
{
"payments": {
"id": "PM123",
"created_at": "2014-05-08T17:01:06.000Z",
"charge_date": "2014-05-21",
"amount": 100,
"description": null,
"currency": "GBP",
"status": "pending_submission",
"reference": "WINEBOX001",
"metadata": {
"order_dispatch_date": "2014-05-22"
},
"amount_refunded": 0,
"links": {
"mandate": "MD123",
"creditor": "CR123"
}
}
}
Unfortunately, the code sample provided in the question doesn't really do anything so it's difficult to suggest what you are trying to do. In conclusion, I would suggest re-visiting the documentation for the API and look through the samples provided.

Set Customize Response for Reactive Web Service using Spring Boot and MongoDB as backend

I am developing reactive-spring-boot web service and also using reactive-mongodb to store data. I want to return my customize response for API. example as below:
[
{
"result": [
{
"code": "",
"data": "",
"error": ""
}
]
}
Sample Method:
#PostMapping(value="/addEmployee")
public Mono<Response> addEmployeeDetails(Employee employee){
Response response = new Response();
if(employee.getEmpID() == null){
return response(getResponse());
}
Repository.save(employee);
return response(getResponse());
}
As you see in the code I have response() method which builds the required response.But it mono gives default response as below:
{
"timestamp": "2018-09-29T16:23:21.287+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Internal Server Error",
"path": "/employee"
}
I am not able to set my own status code and error message.

Google APi Bad Request

i try to implement Passes service of Google Api in our website but we always have error 400 problem
we follow this documentation
Giftcardclass: insert
i use postman for test
POST https://www.googleapis.com/walletobjects/v1/giftCardClass
Request body
{
"kind":"walletobjects#loyaltyObject",
"id":"test2.test",
"classId":"test.test",
"version":12,
"state":"active",
"issuername":"dsadasdasdas",
"barcode":{
"kind":"walletobjects#barcode",
"type":"ean13",
"value":"aaaa",
"alternateText":"aaaa"
}
}
jSon response
{ "error": {
"errors": [
{
"domain": "global",
"reason": "invalidArgument",
"message": "Bad Request"
}
],
"code": 400,
"message": "Bad Request" }
}
from the documentation seems that only id,issuerstate and reviewStatus are required.
Looks like your ids are formatted wrongly, it should be issuer_id.unique_id. See https://developers.google.com/pay/passes/rest/v1/giftcardclass#GiftCardClass.FIELDS.id for reference.

Resources