Getting access token from Google cloud - google-cloud-platform

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.drive.DriveScopes;
public class pred {
public static String getGoogleAccessToken(String jsonKeyFilePath)
throws FileNotFoundException, IOException, GeneralSecurityException {
GoogleCredential credential = GoogleCredential.fromStream(
new FileInputStream(jsonKeyFilePath)).createScoped(
Collections.singleton(DriveScopes.DRIVE));
credential.refreshToken();
return credential.getAccessToken();
}
public static void main(String[] args) throws IOException, GeneralSecurityException {
String a=getGoogleAccessToken("D:ml-latest-small\\untitled\\src\\woven*************.json");
System.out.println(a);
}
}
I want to get access token to get prediction from a version deployed in the google cloud. Above code
gives an access token to google drive. Is there a way to change this part (DriveScopes.DRIVE) to get
an access token to google cloud. Or is there a another way to get access token from java.

Related

authentication with cognito aws in android studio

Hi I'm realizing the authentication with aws cognito I created the link between aws and android through this class:
import android.content.Context;
import java.util.HashMap;
import java.util.Map;
import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserPool;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserSession;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
public class Cognito {
public final static String USER_POOL_ID = "USER_POOL_ID";
public final static String IDENTITY_POOL_ID = "IDENTITY_POOL_ID";
public final static String CLIENT_ID = "CLIENT_ID";
public final static String CLIENT_SECRET = null;
public final static Regions REGION = Regions.US_EAST_1;
private static Cognito cognito;
private final CognitoUserPool cognitoUserPool;
private final CognitoCachingCredentialsProvider cognitoCachingCredentialsProvider;
private Cognito(Context context) {
cognitoUserPool = new CognitoUserPool(
context,
USER_POOL_ID,
CLIENT_ID,
CLIENT_SECRET,
REGION
);
cognitoCachingCredentialsProvider = new CognitoCachingCredentialsProvider(
context,
IDENTITY_POOL_ID,
REGION
);
}
public CognitoUserPool getCognitoUserPool() {
return cognitoUserPool;
}
public static Cognito getInstance(Context context) {
if(cognito != null)
return cognito;
return (cognito = new Cognito(context));
}
public void setLogin(CognitoUserSession session) {
cognitoCachingCredentialsProvider.clear();
Map<String,String> login = new HashMap<>();
login.put(
"cognito-idp." + Region.getRegion(REGION) + ".amazonaws.com/" + USER_POOL_ID,
session.getIdToken().getJWTToken()
);
cognitoCachingCredentialsProvider.setLogins(login);
}
}
but I have the following errors when I upload the data and click the button for user registration:
E/AWSKeyValueStore: com.amazonaws.internal.keyvaluestore.KeyNotFoundException: Error occurred while accessing AndroidKeyStore to retrieve the key for keyAlias: com.amazonaws.android.auth.aesKeyStoreAlias
I/AWSKeyValueStore: Deleting the encryption key identified by the keyAlias: com.amazonaws.android.auth.aesKeyStoreAlias
E/AWSKeyValueStore: Error in retrieving the decryption key used to decrypt the data from the persistent store. Returning null for the requested dataKey = IDENTITY_POOL_ID.identityId
E/AWSKeyValueStore: com.amazonaws.internal.keyvaluestore.KeyNotFoundException: Error occurred while accessing AndroidKeyStore to retrieve the key for keyAlias: com.amazonaws.android.auth.aesKeyStoreAlias
I/AWSKeyValueStore: Deleting the encryption key identified by the keyAlias: com.amazonaws.android.auth.aesKeyStoreAlias
E/AWSKeyValueStore: Error in retrieving the decryption key used to decrypt the data from the persistent store. Returning null for the requested dataKey = IDENTITY_POOL_ID.expirationDate
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
how can i solve?

django-rest-auth with Google: How to post access token properly

I'm really new to using retrofit2. I'm trying to send access token to the backend from mobile app and authenticate the user via Google but I can not do it properly. The backend returns 400.
My code is like this.
views.py
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from rest_auth.registration.views import SocialLoginView
class GoogleLogin(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
urls.py
path('rest-auth/google/', GoogleLogin.as_view()),
And my Java code (I'm using retrofit2)
public interface ApiService {
// login
#POST("/rest-auth/google/")
Call<String> login(#Header("access_token") String accessToken);
MainActivity.java
private void login() {
ApiService service = ApiClient.getService();
service.login(mAuthToken).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (!response.isSuccessful()) {
Toast.makeText(MainActivity.this, "Code:" + response.code(), Toast.LENGTH_LONG).show();
return;
}
Toast.makeText(MainActivity.this, "Success!", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<String> call, Throwable t) {
mTextViewResult.setText(t.getMessage());
}
});
}
mAuthToken is access token. I think I'm wrong with the way to pass the access token to backend. I might be wrong with retrofit2 part. What am I wrong with this?
Update
I found a thing. The access token I get in Android and the access token I get when I login via website is apparently different. I deleted the user and input the access token in the html form manually, the request is accepted.
So I guess there is a problem with access token I get in Android but I have no idea how I can fix this.

Upload files into s3 using AWS Lambda function (Java)

I am currently making a react native application with aws service. I have few doubts about AWS Service use case and I searched and read about AWS service with my use cases but I didn't get any exact solution.
Here is my question,
I have to store photos and videos into S3 buckets. So I am making a simple mobile application that has access for getting photos and videos from gallery and making a API call to trigger AWS Lambda function (written in Java) to upload those photos and videos into the respective S3 buckets. But my question is, whenever I try to store all those photos and videos into S3 bucket using AWS Lambda function I keep getting no such file or directory exception. I know the reason why I am getting this exception because those photos and Videos are only available in local storage not in AWS cloud (ref Upload Image into AWS S3 bucket using Aws Lambda). So Is there any way to overcome this error? or else I need to get EC2 instance to store all the photos and videos?
My sample Lambda Function code (Upload Image into S3 bucket)
package com.amazonaws.lambda.demo;
import java.io.File;
import java.io.IOException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
public class LambdaFunctionHandler implements RequestHandler<String, PutObjectResult> {
#SuppressWarnings("deprecation")
public PutObjectResult UploadFile(String imageURI) throws IOException {
PutObjectResult resultObj = new PutObjectResult();
AWSCredentials credentials = new BasicAWSCredentials("Ak", "Sk");
//String clientRegion = "region";
String bucketName = "bucket_name";
String fileObjKeyName = "sample_image_pic.jpg";
try {
AmazonS3 s3Client = new AmazonS3Client(credentials);
// Upload a file as a new object with ContentType and title specified.
resultObj = s3Client.putObject(new PutObjectRequest(bucketName, fileObjKeyName, new File(imageURI)));
}
catch(AmazonServiceException e) {
// The call was transmitted successfully, but Amazon S3 couldn't process
// it, so it returned an error response.
e.printStackTrace();
}
catch(SdkClientException e) {
// Amazon S3 couldn't be contacted for a response, or the client
// couldn't parse the response from Amazon S3.
e.printStackTrace();
}
return resultObj;
}
#Override
public PutObjectResult handleRequest(String imageURI, Context context) {
PutObjectResult result = null;
try {
result = UploadFile(imageURI);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
Thanks,

Implementing digital signature on Weblogic ServiceControl Client

Our application is a consumer of a web service that has asked us to implement digital signature (X.509 based) in our request SOAP header. We need to have in the header tags like <ds:SignedInfo>, <wsse:BinarySecurityToken>, <ds:CanonicalizationMethod>. It's actually a lot similar to the xml here.
Now, as a client we are not using clientgen. Nor is the server side willing to make this into a WS-Policy. I searched a lot in the Oracle documentation but it seems to end at the assumption that the server side needs to have this policy enforced to the web service. That can't happen. We can't use client side policy too because the examples I came across at Oracle's website seem to suggest that it only works for client code generated via clientgen while our code uses the ServiceControl.
Just today I came across WSS4J but I am not sure if that is the answer to what I am searching for. It certainly seems plausible but will it work in my scenario (considering that we have Weblogic ServiceController) while all examples for WSS4J seem to use Axis.
I have spent last few days searching on this and I am getting to the point of frustration. Please help!
Thanks,
Ak
I have faced the same problem and finally we are using the Apache CXF library for creating the client and written some interceptors for it. In our case the web service is having authentication header and it is X509 enabled. The below code works for me, I am sharing this with you:-
For generating Web Service Client offline, you can save the xml of the wsdl in your localmachine and then use wsconsume/wsdl2java command for creating the stub.
In the below code you can skip addSoapHeader part if there is no userName and pwd set for the web service
in SOAP Header.
TestClient.java:-
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.xml.bind.JAXBException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import javax.xml.ws.soap.AddressingFeature;
import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.headers.Header;
import org.apache.cxf.jaxb.JAXBDataBinding;
import org.apache.cxf.ws.addressing.AddressingProperties;
import org.apache.cxf.ws.addressing.AttributedURIType;
import org.apache.cxf.ws.addressing.EndpointReferenceType;
import org.apache.cxf.ws.addressing.VersionTransformer;
import org.apache.cxf.ws.addressing.impl.AddressingPropertiesImpl;
import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
import org.apache.ws.security.handler.WSHandlerConstants;
import com.icbase.tsamplex509.ArrayOfDetailLineItem;
import com.icbase.tsamplex509.ArrayOfInventoryLineItem;
import com.icbase.tsamplex509.AuthHeader;
import com.icbase.tsamplex509.CompleteInventory;
import com.icbase.tsamplex509.DetailLineItem;
import com.icbase.tsamplex509.InventoryLineItem;
import com.icbase.tsamplex509.OrderAdd;
import com.icbase.tsamplex509.OrderStatus;
import com.icbase.tsamplex509.ResultMessage;
import com.icbase.tsamplex509.Service;
import com.icbase.tsamplex509.ServiceSoap;
import com.st.passport.PassportWebServiceHandler;
import com.st.passport.UserInfo;
import com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl;
public class TestClient
{
private static String proxyUser = "javaMagician";
private static String proxyPassword = "myProxyPws";
private static String proxyHost = "sxf4.dlh.ts.com";
private static String proxyPort = "8080";
private static String wsURL = "http://www.wsdoamin.com/tssamplex509/service.asmx?WSDL";
public static void main(String[] args) throws MalformedURLException, Exception
{
Authenticator.setDefault(new ANSAuthenticationHandler(proxyUser,proxyPassword));
System.getProperties().put("http.proxyHost", proxyHost);
System.getProperties().put("http.proxyPort", proxyPort);
Service service = new Service(new URL(wsURL),new QName("http://www.wsdoamin.com/tssamplex509/", "Service"));
ServiceSoap port = service.getServiceSoap(new AddressingFeature(true,true));
Client client = ClientProxy.getClient(port);
enableWSAddressing(client);
enableWsSecurity(client);
addSOAPHeader(client);
System.out.println("Invoking Web Service ...");
//Calling First Web service
CompleteInventory getProductResponse = port.getproduct("*");
System.out.println("Result :: " + getProductResponse.getResultMessage().getResult().name());
System.out.println("Return Message :: " + getProductResponse.getResultMessage().getMessage());
System.out.println("------------------- Inventory -------------------");
}
private static void enableWSAddressing(Client client) {
AddressingProperties maps = new AddressingPropertiesImpl();
EndpointReferenceType ref = new EndpointReferenceType();
AttributedURIType add = new AttributedURIType();
add.setValue("http://www.wsdoamin.com/tssamplex509/getproduct");
ref.setAddress(add);
maps.setReplyTo(ref);
maps.setFaultTo(ref);
maps.exposeAs(VersionTransformer.Names200408.WSA_NAMESPACE_NAME);
client.getRequestContext().put("javax.xml.ws.addressing.context", maps);
}
private static void enableWsSecurity(Client client) {
Properties properties = new Properties();
properties.put("org.apache.ws.security.crypto.provider","org.apache.ws.security.components.crypto.Merlin");
properties.put("org.apache.ws.security.crypto.merlin.keystore.type","jks");
properties.put("org.apache.ws.security.crypto.merlin.keystore.password","changeit");
properties.put("org.apache.ws.security.crypto.merlin.keystore.alias","ts_p&s_ws");
properties.put("org.apache.ws.security.crypto.merlin.file", "cert/TS_P&S_WS.jks");
Map<String, Object> outProps = new HashMap<String, Object>();
outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE);
outProps.put(WSHandlerConstants.USER, "ts_p&s_ws");
outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS,ANSAuthenticationHandler.class.getName());
outProps.put("cryptoProperties", properties);
outProps.put(WSHandlerConstants.SIG_PROP_REF_ID,"cryptoProperties");
outProps.put(WSHandlerConstants.SIG_KEY_ID, "DirectReference");
client.getEndpoint().getOutInterceptors().add(new WSS4JOutInterceptor(outProps));
client.getEndpoint().getOutInterceptors().add(new org.apache.cxf.interceptor.LoggingOutInterceptor());
client.getEndpoint().getInInterceptors().add(new org.apache.cxf.interceptor.LoggingInInterceptor());
}
private static void addSOAPHeader(Client client) throws JAXBException {
List<Header> headers = new ArrayList<Header>();
AuthHeader authHeader = new AuthHeader();
authHeader.setUsername("ts");
authHeader.setPassword("46u43242bw3670");
SoapHeader tokenHeader = new SoapHeader(new QName("http://www.wsdoamin.com/tssamplex509", "AuthHeader"), authHeader,new JAXBDataBinding(AuthHeader.class));
headers.add(tokenHeader);
client.getRequestContext().put(Header.HEADER_LIST, headers);
}
}
ANSAuthenticationHandler.java
import java.io.IOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.apache.ws.security.WSPasswordCallback;
public class ANSAuthenticationHandler extends Authenticator implements CallbackHandler {
private String proxyUser;
private String proxyPassword;
public ANSAuthenticationHandler() {
super();
}
public ANSAuthenticationHandler(String proxyUser, String proxyPassword) {
super();
this.proxyUser = proxyUser;
this.proxyPassword = proxyPassword;
}
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
{
WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];
System.err.println("CallbackHandler providing password for :: "+pc.getIdentifier());
if ("ts_p&s_ws".equals(pc.getIdentifier())) {
pc.setPassword("changeit");
}
}
public PasswordAuthentication getPasswordAuthentication()
{
System.err.println("Feeding username and password for ["+getRequestingPrompt()+"] to ["+getRequestingHost()+":"+getRequestingPort()+"] for ["+getRequestingScheme()+"] scheme");
return (new PasswordAuthentication(proxyUser, proxyPassword.toCharArray()));
}
}

Disable auto generated JAX-WS Status Page

When I deploy and run my web service developed with JAX-WS I can see a summary page with some info on it, something like in this picture:
http://www.mkyong.com/webservices/jax-ws/deploy-jax-ws-web-services-on-tomcat/
For the final implementation we would like to remove this page so that a custom or a blank page is returned while still having access to the web service endpoint.
We are currently running on Tomcat.
There is a field on the WSServlet class that might do what you are looking for: JAXWS_RI_PROPERTY_PUBLISH_STATUS_PAGE (it's value is com.sun.xml.ws.server.http.publishStatusPage).
Looking at the source code from a JAX-WS download it seems that you need to set it as a context parameter in your web.xml file:
<web-app>
<context-param>
<param-name>com.sun.xml.ws.server.http.publishStatusPage</param-name>
<param-value>false</param-value>
</context-param>
...
Seems that HttpAdapter had something similar on it but was taken from an environment variable:
setPublishStatus(
System.getProperty(HttpAdapter.class.getName() + ".publishStatusPage")
.equals("true"));
The code on HttpAdapter is marked deprecated in the javadoc so the context parameter seems the way to go.
I have been trying to solve this for two days, Glassfish 3.1.2.
The only solution was to have
-Dcom.sun.xml.ws.transport.http.HttpAdapter.publishStatusPage=false
I know its old, but wantd to maintain the knowledge. Hope this helps any one with this issue.
I have completed the same task for WebLogic recently.
It was requested to hide/show a status page of a public web service depending on a target environment i.e. hide for production, show for dev.
Nothing of the previous answers worked for me.
The success solution is based on implementation of javax.servlet.Filter.
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.HttpMethod;
#WebFilter(urlPatterns = { "/WeblogicWebService" })
public class FilterStatusSoapPage implements Filter {
#Value("${soap.status.page.disabled}")
private boolean flagDisablePublishStatusPage;
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpRes = (HttpServletResponse) response;
String queryString = httpReq.getQueryString();
if(flagDisablePublishStatusPage)
if(queryString == null || queryString.trim().isEmpty())
if(HttpMethod.GET.matches(httpReq.getMethod())) {
httpRes.setStatus(HttpServletResponse.SC_OK);
httpRes.getWriter().write("Access to status page of Web
Service is not allowed");
httpRes.getWriter().flush();
httpRes.getWriter().close();
return;
}
} catch (Exception e) {
System.err.println("Error on FilterStatusSoapPage filter");
chain.doFilter(request, response);
return;
}
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {}
public void destroy() {}
}