AWS API Gateway generated sdk request errors - java

I've created an API using AWS API Gateway. All of the methods used in the API require IAM authentication.
I tried to test the API locally and got the following exception:
myapi.model.MyAPIException: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1632)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1304)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1058)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:743)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:717)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667)
at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)
at com.amazonaws.client.ClientHandlerImpl.doInvoke(ClientHandlerImpl.java:204)
at com.amazonaws.client.ClientHandlerImpl.invoke(ClientHandlerImpl.java:185)
at com.amazonaws.client.ClientHandlerImpl.execute(ClientHandlerImpl.java:93)
at com.amazonaws.opensdk.protect.client.SdkClientHandler.execute(SdkClientHandler.java:42)
at myapi.MyAPIClient.myMethod(MyAPIClient.java:101)
...
For building the request I used the following code:
public static void main(String[] args) {
MyAPI client = MyAPI .builder()
.apiKey(myApiKey)
.iamCredentials(DefaultAWSCredentialsProviderChain.getInstance())
.build();
MyMethodRequest myMethodRequest = new MyMethodRequest().arg(methodArg);
MyMethodResult result = client.myMethod(myMethodRequest);
}
The credentials loaded by the DefaultAWSCredentialsProviderChain are my credentials which have admin access to all of my AWS services so I'm not sure what is wrong.
Any help is appreciated.

The problem ended being having entered the wrong apiKey for the API.
When I changed it to a valid API key generated by API Gateway everything worked.
Also, you have to make sure the API Key is linked to a valid usage plan or it will not work

Usually class more like:
package ...;
public class ListingMusic implements
RequestHandler<HashMap<String, Object>, String> {
#Override
public String handleRequest(HashMap<String, Object> input, Context context) {
...
}
}
Maybe it can be that your lambda can't start

Related

Quarkus: how to secure WebSocket when using Keycloak / OIDC

I have gone down many rabbit holes and cannot get this working. I am hoping someone can help me.
I am using Keycloak and my REST endpoints are successfully secured like this abbreviated example:
#Path("/api")
public class MyResource {
#Inject
SecurityIdentity securityIdentity;
#Inject
JsonWebToken jwt;
#GET
#Path("/mydata")
#RolesAllowed("user")
#NoCache
public Uni<Response> getMyData(Request request) {
// Get a claim from the Keycloak JWT
String mySpecialClaim = (String) jwt.claim("myCustomClaim").get();
// Do some work...
String resJson = "{result of work here}";
return Uni.createFrom().item(resJson)
.onItem()
.transform(item -> item != "" ? Response.ok(item) : Response.status(Response.Status.NO_CONTENT))
.onItem()
.transform(Response.ResponseBuilder::build);
}
}
The access token is supplied by the client app which manages the Keycloak authentication and which sends the API request with a Bearer token. Standard stuff, all working. :-)
Now, I want to do something similar with a WebSocket endpoint.
I am using the Quarkus Websockets sample as my guide and can get it all working without Authorization - ie making unsecured calls.
I am stuck trying to secure the WebSocket connection.
The closest I have come to finding a solution is this post in the Quarkus GitHub issues:
https://github.com/quarkusio/quarkus/issues/29919
I have coded that up as per the sample code in the post. Logging shows the reactive route and WebSocketSecurityConfigurator are both being called and the access_token from the JS WebSocket client is present and presumably being processed by the Quarkus default security processes, as it does for REST end points. All good.
The missing piece is how to code the onOpen() and onMessage() methods in my WebSocket endpoint so they are secure, reactive, and I can access the JWT to get the claims I need.
Can anyone elaborate on this code fragment from the Quarkus issue post mentioned above, please? I have added what I think I need as per the sample further below.
The fragment from the issue post:
#Authenticated
#ServerEndpoint(
value ="/ws",
configurator = WebSocketSecurityConfigurator.class
)
public class WebSocket {
#Inject
UserInfo userInfo;
// ...
}
My additions:
#Authenticated
#ServerEndpoint(
value ="/services/{clientid}",
configurator = WebSocketSecurityConfigurator.class
)
public class WebSocket {
#Inject
SecurityIdentity securityIdentity;
#Inject
JsonWebToken jwt;
#Inject
UserInfo userInfo;
#OnOpen
#RolesAllowed("user") // Is this possible here? Or do I use the JWT and test myself?
public void onOpen(Session session, #PathParam("clientid") String clientid) {
// Get a claim from the Keycloak JWT
String mySpecialClaim = (String) jwt.claim("myCustomClaim").get();
// Do some setup work...
// eg cache the session in a map, etc
}
#OnMessage
public void onMessage(String message, #PathParam("clientid") String clientid) {
// Get a claim from the Keycloak JWT
String myOtherSpecialClaim = (String) jwt.claim("myOtherCustomClaim").get();
// Do some work using the message...
String someMessage = "tell the world";
// Broadcast something ...
myBroadcastFunction(someMessage);
}
}
In the non-secure version, the onOpen() and onMessage() methods return void because, of course, unlike a REST endpoint, one broadcasts the result instead of returning it.
In this secured version that does not work. If I only have an onOpen() method, and code it like this:
#OnOpen
public void onOpen(Session session, #PathParam("clientid") String clientid) {
Log.info("websocket onOpen session=" + session.getId());
}
It throws:
Unhandled error in annotated endpoint org.flowt.orgserver.gateway.WebSocketGateway_Subclass#732f20f8
java.lang.RuntimeException: java.lang.RuntimeException: java.lang.RuntimeException:
io.quarkus.runtime.BlockingOperationNotAllowedException: Blocking security check attempted in code running on the event loop.
Make the secured method return an async type, i.e. Uni, Multi or CompletionStage,
or use an authentication mechanism that sets the SecurityIdentity in a blocking manner prior to delegating the call
I would like not to block the event loop, so the first suggestion is the preferred one.
But how should I code that?
If I make the onOpen() return a Uni, how do I subscribe to it so it runs?
Can I still access the JWT to get the claims I need?
Do annotations like #RolesAllowed("user") still work in this context?
I wont waste space here with all my failed attempts. I am thinking I am not the first person to need to do this and there must be some kind of pattern to implement. The Quarkus docs are silent on this.
Can anyone tell me how to code the onOpen() and onMessage() methods using Quarkus so that the WebSocket endpoints are secured and the JWT is available inside those methods?
EDIT =======
To resolve the blocking exception, the Quarkus docs here say
To work around this you need to #Inject an instance
of io.quarkus.security.identity.CurrentIdentityAssociation,
and call the Uni<SecurityIdentity> getDeferredIdentity(); method.
You can then subscribe to the resulting Uni and will be
notified when authentication is complete and the identity
is available.
I cannot work out how to implement that instruction. Debugging into the Quarkus code I see that my access_token is being processed, the user is retrieved from Keycloak but the deferredIdentity is not being set. Therefore onOpen() never runs.
Clearly this is not what the docs mean me to do!
Here is my class:
package org.flowt.orgserver.gateway;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.websocket.Session;
import javax.websocket.OnOpen;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import io.quarkus.logging.Log;
import io.quarkus.security.Authenticated;
import io.quarkus.security.identity.CurrentIdentityAssociation;
import io.quarkus.security.identity.SecurityIdentity;
import io.smallrye.mutiny.Uni;
#ApplicationScoped
#Authenticated
#ServerEndpoint(value = "/services/{clientid}", configurator = WebSocketSecurityConfigurator.class)
public class WebSocketGateway {
#Inject
SecurityIdentity securityIdentity;
#Inject
CurrentIdentityAssociation identities;
#OnOpen
public Uni<Void> onOpen(Session session, #PathParam("clientid") String clientid) {
// This never runs
Log.info("=========================== onOpen session=" + session.getId());
return identities.getDeferredIdentity()
.onItem()
.transformToUni(identity -> {
// Just to see if we reach here
Log.info("identity=" + identity.toString());
return Uni.createFrom().voidItem();
});
}
}
And just to reiterate: the REST endpoints in this same app for the same logged in user work perfectly.
Thanks,
Murray

Quarkus: request to URL given as string

I want to make an HTTP request with Quarkus. However, the target URL is not known at compilation time, it will be composed from different parts at runtime.
Quarkus provides a way to build static REST clients like this:
#Path("/v2")
#RegisterRestClient
public interface CountriesService {
#GET
#Path("/name/{name}")
#Produces("application/json")
Set<Country> getByName(#PathParam String name);
}
However, I am loking for something like the Python requests package:
url = 'https://stackoverflow.com/questions/ask'
response = requests.get(url)
I am building the application in Kotlin, so all Java and Kotlin libraries should work.
What should I use?
With the MP REST Client defined in an interface, you can use the programmatic client creation API:
CountriesService remoteApi = RestClientBuilder.newBuilder()
.baseUri("created at runtime url")
.build(CountriesService.class);
remoteApi.getByName("");

How to create an object of IAuthenticationProvider of GraphServiceClient with fixed inputs

I am trying to connect to Microsoft Share Point from my Java application. The documentation for Microsoft Graph SDK for Java is not so clear.
I am trying to initiate the Graph client, while providing the credentials needed via a custom GUI or configuration file.
I am trying to do as follow but can
IGraphServiceClient client = GraphServiceClient.builder().authenticationProvider(authenticationProvider).buildClient();
I need the "authenticationProvider" object to be of a class implementing IAuthenticationProvider, however its not clear what parameters to add or how to create this object. Has anyone tried this before and what is the correct way to build the client and provide the required credentials?
Microsoft has an example project where they have a simple instance of IAuthenticationProvider.
public class SimpleAuthProvider implements IAuthenticationProvider {
private String accessToken = null;
public SimpleAuthProvider(String accessToken) {
this.accessToken = accessToken;
}
#Override
public void authenticateRequest(IHttpRequest request) {
// Add the access token in the Authorization header
request.addHeader("Authorization", "Bearer " + accessToken);
}
}
The AuthenticationProviders that implement a variety of different OAuth flows are available in a seperate package. See this Github repo here:
https://github.com/microsoftgraph/msgraph-sdk-java-auth

consume Oauth2 (authorization code) rest api with spring rest template

I'm trying to consume a rest web service in spring integration project. This web service is secured with oauth2 (authorization code).Any idea how to achieve this?
I tried using OAuth2RestTemplate but it gave me an error:
org.springframework.security.oauth2.client.resource.UserRedirectRequiredException: A redirect is required to get the users approval
Below is my code.
import java.util.Arrays;
import org.springframework.security.oauth2.client.token.AccessTokenRequest;
import org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
public class OAuth2Client1 {
public static void main(String[] args) {
AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();
resource.setId("My Developer");
resource.setClientId("xxxxxx");
resource.setClientSecret("xxxxxx");
resource.setAccessTokenUri("https://api.infusionsoft.com/token");
resource.setUserAuthorizationUri("https://signin.infusionsoft.com/app/oauth/authorize");
resource.setPreEstablishedRedirectUri("https://myapps.com:8181/my_work");
resource.setScope(Arrays.asList("full"));
try {
AuthorizationCodeAccessTokenProvider authProvider =
new AuthorizationCodeAccessTokenProvider();
AccessTokenRequest request = new DefaultAccessTokenRequest();
String str = authProvider.obtainAuthorizationCode(resource, request);
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Authorization Code flow is used to authenticate user in web browser through redirect. It requires user authentication by username and password.
Your case is about communication between two services, also called as M2M (machine-to-machine). Service is not allowed to store user credentials by itself due security reasons. You should use Client Credentials flow that requred only client id and client secret for authentication. So then you'll able to use OAuth2RestTemplate.
If the service is secured with oAuth2, you must play with oAuth rules in order to get to the resource server. It means your app needs to register and get clientID and client-secret, then the users of your app can use it to oAuth-connect...
It does not matter HOW you invoke the call, you have to use oAuth. OAuth2RestTemplate is just a Spring's RestTemplate implementation for oAuth developers, that abstracts some logic that is relevant for oAuth...

Restricting Access to method in Play Framework with Authorization - Java

I am having trouble grasping the idea of authorization in PlayFramework (version 2.5). My situation is I have a REST API method getUser and I want to restrict its access by performing authorization with a token that is coming in custom request header named "X-Authorization". Now my controller code looks like that:
package controllers;
import models.User;
import org.bson.types.ObjectId;
import play.mvc.*;
import org.json.simple.*;
import views.html.*;
public class ApiController extends Controller {
public Result getUser(String userId) {
User user = User.findById(new ObjectId(userId));
JSONObject userG = new JSONObject();
//Some code to append data to userG before return
return ok(userG.toJSONString());
}
}
The route URL is defined like this:
GET /api/user/:id controllers.ApiController.getUser(id)
Option 1 could be to check the Authorization token inside the method getUser and also check for other credentials but I want to restrict access before even it get calls getUser method. As in future I will be adding more method calls to this REST API. So I will be reusing the same authorization to those future REST APIs as well.
I found there is authorization available in Play Framework which I am not able to understand. I tried to implement Authorization by extending class Security.Authenticator and overriding methods getUserName and onUnauthorized like this:
package controllers;
import models.Site;
import models.User;
import org.json.simple.JSONObject;
import play.mvc.Http.Context;
import play.mvc.Result;
import play.mvc.Security;
public class Secured extends Security.Authenticator {
#Override
public String getUsername(Context ctx) {
String auth_key = ctx.request().getHeader("X-Authorization");
Site site = Site.fineByAccessKey(auth_key);
if (site != null && auth_key.equals(site.access_key)) {
return auth_key;
} else {
return null;
}
}
#Override
public Result onUnauthorized(Context ctx) {
JSONObject errorAuth = new JSONObject();
errorAuth.put("status", "error");
errorAuth.put("msg", "You are not authorized to access the API");
return unauthorized(errorAuth.toJSONString());
}
}
Then I've appended the annotation to the getUser method with #Security.Authenticated(Secured.class). It works fine and returns unauthorized error. But now I am not sure if that is the preferred way. I feel this is not the right way to do it as the name of the override of function getUsername suggests that too. I am not checking for any username in session or cookie rather only the token present in the header of request.
Also I know there is a module named Deadbolt which is used for authorization but I read its documents and I am not able to integrate it. It was relatively complex integration for a beginner like me. I was confused about how to use it. I thought about using SubjectPresent controller authorization but still I was not able to implement it successfully.
In the end what do you guys suggest that should I use Security.Authenticator the way I have implemented? Or do you suggest that I go to my first option that is checking authorization inside getUser method? Or Anyone can tell me how to implement Deadbolt in my scenario?
You are mixing Authorization and Authentication.
Here is a good thread: Authentication versus Authorization
I like this answer:
Authentication = login + password (who you are)
Authorization = permissions (what you are allowed to do)
Authentication == Authorization (excluding anonymous user) if you allow doing something for all users that you know (i.e. Authenticated users)
The main goal of Deadbolt is Authorization (already Authenticated users). Your main goal is Authentication.
I would advise you to use Pac4J, it Authentication library not only for Play, and it has versions as for Java as for Scala. There is a good sample project: https://github.com/pac4j/play-pac4j-java-demo
I use this library myself in my projects and the task
As in future i will be adding more method calls to this REST api. So i
will be reusing the same authorization to those future REST apis as
well.
I solve as easy as just add the configuration in the 'application.conf`:
pac4j.security {
rules = [
{"/admin/.*" = {
authorizers = "ADMIN"
clients = "FormClient"
}}
]
}
Just do not forget to add Security filter. This feature present in the example project, so just clone and try.
Another example form the official page:
pac4j.security.rules = [
# Admin pages need a special authorizer and do not support login via Twitter.
{"/admin/.*" = {
authorizers = "admin"
clients = "FormClient"
}}
# Rules for the REST services. These don't specify a client and will return 401
# when not authenticated.
{"/restservices/.*" = {
authorizers = "_authenticated_"
}}
# The login page needs to be publicly accessible.
{"/login.html" = {
authorizers = "_anonymous_"
}}
# 'Catch all' rule to make sure the whole application stays secure.
{".*" = {
authorizers = "_authenticated_"
clients = "FormClient,TwitterClient"
}}
]

Categories

Resources