Google API oAuth2.0 -- Consumer is not registered - api

I have oAuth 2.0 code that works with other services (such as LinkedIn and Facebook) but niot Google.
The code fails with 'Consumer is not registered'. It certainly is. That is if this error means what I think it means but I do have the following in https://code.google.com/apis/console.
a project,
and a valid CLIENT_ID entry
Client ID: 107***********4ek7fl.apps.googleusercontent.com
Client secret: Q6KbA**********FRbL
Redirect URIs: urn:ietf:wg:oauth:2.0:oob, htp://{localhost}
The failure occurs when the request is first sent to https://accounts.google.com/o/oauth2/auth
No page is displayed asking the user to authenticate, the Google server returns "Consumer is not registered" in the response body.

I had a similar problem. I am using the scribe oauth java library, https://github.com/fernandezpablo85/scribe-java. It's support of Google is only oauth 1.0, so I had to write my own class that extends org.scribe.builder.api.DefaultApi20 instead of org.scribe.builder.api.DefaultApi10a.

basically here you are:
package org.scribe.builder.api;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.scribe.exceptions.OAuthException;
import org.scribe.extractors.AccessTokenExtractor;
import org.scribe.model.OAuthConfig;
import org.scribe.model.OAuthConstants;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuth20ServiceImpl;
import org.scribe.oauth.OAuthService;
import org.scribe.utils.OAuthEncoder;
import org.scribe.utils.Preconditions;
/**
* Google OAuth2.0
* Released under the same license as scribe (MIT License)
* #author houman001
* This code borrows from and modifies changes made by #yincrash
* #author yincrash
*
*/
public class Google2Api extends DefaultApi20 {
private static final String AUTHORIZE_URL = "https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%s&redirect_uri=%s";
private static final String SCOPED_AUTHORIZE_URL = AUTHORIZE_URL + "&scope=%s";
private static final String SUFFIX_OFFLINE = "&" + OAuthConstants.ACCESS_TYPE + "=" + OAuthConstants.ACCESS_TYPE_OFFLINE
+ "&" + OAuthConstants.APPROVAL_PROMPT + "=" + OAuthConstants.APPROVAL_PROMPT_FORCE;
#Override
public String getAccessTokenEndpoint() {
return "https://accounts.google.com/o/oauth2/token";
}
#Override
public AccessTokenExtractor getAccessTokenExtractor() {
return new AccessTokenExtractor() {
public Token extract(String response) {
Preconditions.checkEmptyString(response, "Response body is incorrect. Can't extract a token from an empty string");
Matcher matcher = Pattern.compile("\"access_token\" : \"([^&\"]+)\"").matcher(response);
if (matcher.find())
{
String token = OAuthEncoder.decode(matcher.group(1));
String refreshToken = "";
Matcher refreshMatcher = Pattern.compile("\"refresh_token\" : \"([^&\"]+)\"").matcher(response);
if (refreshMatcher.find())
refreshToken = OAuthEncoder.decode(refreshMatcher.group(1));
Date expiry = null;
Matcher expiryMatcher = Pattern.compile("\"expires_in\" : ([^,&\"]+)").matcher(response);
if (expiryMatcher.find())
{
int lifeTime = Integer.parseInt(OAuthEncoder.decode(expiryMatcher.group(1)));
expiry = new Date(System.currentTimeMillis() + lifeTime * 1000);
}
Token result = new Token(token, refreshToken, expiry, response);
return result;
}
else
{
throw new OAuthException("Response body is incorrect. Can't extract a token from this: '" + response + "'", null);
}
}
};
}
#Override
public String getAuthorizationUrl(OAuthConfig config) {
// Append scope if present
if (config.hasScope()) {
String format = config.isOffline() ? SCOPED_AUTHORIZE_URL + SUFFIX_OFFLINE : SCOPED_AUTHORIZE_URL;
return String.format(format, config.getApiKey(),
OAuthEncoder.encode(config.getCallback()),
OAuthEncoder.encode(config.getScope()));
} else {
String format = config.isOffline() ? AUTHORIZE_URL + SUFFIX_OFFLINE : AUTHORIZE_URL;
return String.format(format, config.getApiKey(),
OAuthEncoder.encode(config.getCallback()));
}
}
#Override
public Verb getAccessTokenVerb() {
return Verb.POST;
}
#Override
public OAuthService createService(OAuthConfig config) {
return new GoogleOAuth2Service(this, config);
}
private static class GoogleOAuth2Service extends OAuth20ServiceImpl {
private DefaultApi20 api;
private OAuthConfig config;
public GoogleOAuth2Service(DefaultApi20 api, OAuthConfig config) {
super(api, config);
this.api = api;
this.config = config;
}
#Override
public Token getAccessToken(Token requestToken, Verifier verifier) {
OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
switch (api.getAccessTokenVerb()) {
case POST:
request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
// API Secret is optional
if (config.getApiSecret() != null && config.getApiSecret().length() > 0)
request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
if (requestToken == null) {
request.addBodyParameter(OAuthConstants.CODE, verifier.getValue());
request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
request.addBodyParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.GRANT_TYPE_AUTHORIZATION_CODE);
} else {
request.addBodyParameter(OAuthConstants.REFRESH_TOKEN, requestToken.getSecret());
request.addBodyParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.GRANT_TYPE_REFRESH_TOKEN);
}
break;
case GET:
default:
request.addQuerystringParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
// API Secret is optional
if (config.getApiSecret() != null && config.getApiSecret().length() > 0)
request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
request.addQuerystringParameter(OAuthConstants.CODE, verifier.getValue());
request.addQuerystringParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
if(config.hasScope()) request.addQuerystringParameter(OAuthConstants.SCOPE, config.getScope());
}
Response response = request.send();
return api.getAccessTokenExtractor().extract(response.getBody());
}
}
}
from https://raw.githubusercontent.com/codolutions/scribe-java/master/src/main/java/org/scribe/builder/api/Google2Api.java

Related

Unable to initialize AdaptersAPI Object in MobileFirst V8.0 adapter which is leading to NullPointerException

I am developing the adapter in MFP V8. Below is my code to validate username and password:
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import com.ibm.mfp.adapter.api.AdaptersAPI;
import com.ibm.mfp.adapter.api.ConfigurationAPI;
import com.ibm.mfp.security.checks.base.UserAuthenticationSecurityCheck;
import com.ibm.mfp.server.registration.external.model.AuthenticatedUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
#Api(value = "Sample Adapter Resource")
#Path("/resource")
public class UserValidationSecurityCheck extends UserAuthenticationSecurityCheck{
private String displayName;
private String errorMsg;
private HashMap<String,Object> adapterReponse = null;
#Context
AdaptersAPI adaptersAPI;
#Override
protected AuthenticatedUser createUser() {
return new AuthenticatedUser(displayName, displayName, this.getName(),adapterReponse);
}
#Override
protected boolean validateCredentials(Map<String, Object> credentials) {
if(credentials!=null && credentials.containsKey("username") && credentials.containsKey("password")){
if (credentials.get("username")!=null && credentials.get("password")!=null) {
String username = credentials.get("username").toString();
String password = credentials.get("password").toString();
if (username.equals(password)) {
JSONObject loginParams = new JSONObject();
loginParams.put("username", username);
loginParams.put("password", password);
HttpUriRequest httpUriRequest = adaptersAPI.createJavascriptAdapterRequest("LoginAndWeeklyCertAdapter1", "login", loginParams);
try {
HttpResponse httpResponse = adaptersAPI.executeAdapterRequest(httpUriRequest);
adapterReponse = adaptersAPI.getResponseAsJSON(httpResponse);
System.out.println(adapterReponse.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
} else {
errorMsg = "Wrong Credentials";
}
}
}
else{
errorMsg = "Credentials not set properly";
}
return false;
}
public boolean isLoggedIn(){
return getState().equals(STATE_SUCCESS);
}
public AuthenticatedUser getRegisteredUser() {
return registrationContext.getRegisteredUser();
}
#Override
protected Map<String, Object> createChallenge() {
Map<String, Object> challenge = new HashMap<String, Object>();
challenge.put("errorMsg", errorMsg);
challenge.put("remainingAttempts", getRemainingAttempts());
return challenge;
}
#ApiOperation(value = "Returns 'Hello from resource'", notes = "A basic example of a resource returning a constant string.")
#ApiResponses(value = { #ApiResponse(code = 200, message = "Hello message returned") })
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getResourceData() {
// log message to server log
logger.info("Logging info message...");
return "Hello from resource";
}
}
When I am submitting the challenge answer I am getting NullPointerException in following line:
HttpUriRequest httpUriRequest = adaptersAPI.createJavascriptAdapterRequest("LoginAndWeeklyCertAdapter1", "login");
because adaptersAPI is null. Do I have to do any extra configuration in order to make that work? How can I initialize AdaptersAPI object?
Note: The login method and the security check both are in same adapter.
Update
I investigated more of time into it and updated the code to given above and observed the following:
1. When validateCredentials() is getting called after submitting the challenge response then I am getting null value in AdapterAPI object.
2. Where as, when I am calling the getResourceData() using the mobilefirst swagger tool then I am getting an object of AdapterAPI.
We cannot inject the adapters API into a security check object(by design - not a bug). The only way we can go is to extract the logic from Adapter into a Java code, without using adapters API.

How to authenticate with mbean bypassing jmx.access file when using JAAS module

I amfacing one issue with mbean authentication. Issue is i need to always change my mbean jmx.access file to match with different users for authorization rule. Somehow i need to bypass this jmx.access file and authenticate using my custom JAAS login module only which call the rest api at backend.
Please suggest.
Also to do this any other approach better than this is appreciated!
Here is my all code
public class SystemConfigManagement {
private static final int DEFAULT_NO_THREADS = 10;
private static final String DEFAULT_SCHEMA = "default";
private static String response = null;
public static void main(String[] args) throws MalformedObjectNameException, InterruptedException,
InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException {
// Get the MBean server
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
// register the MBean
SystemConfig mBean = new SystemConfig(DEFAULT_NO_THREADS, DEFAULT_SCHEMA);
ObjectName name = new ObjectName("com.sigma.jmx:type=SystemConfig");
mbs.registerMBean(mBean, name);
do {
Thread.sleep(3000);
System.out.println("Thread Count=" + mBean.getThreadCount() + ":::Schema Name="
+ mBean.getSchemaName());
if (mBean.getSchemaName().equalsIgnoreCase("NewSchema")) {
System.out.println("Yes, you got right shcema name with token " + mBean.getToken());
response = RestClient.callPost("/validate-token", mBean.getToken(), "{}");
System.out.println("Toekn validation response " + response);
if (response.contains("\"valid\":true")) {
System.out.println("You are Logged In....");
} else {
System.out.println("Your Token is invalid, you cannot login...");
}
} else {
System.out.println("Schema name is invalid");
}
} while (mBean.getThreadCount() != 0);
}
}
JAAS login Module
package com.sigma.loginmodule;
import java.util.*;
import java.io.IOException;
import javax.management.remote.JMXPrincipal;
import javax.security.auth.*;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;
import javax.security.auth.spi.*;
import com.sigma.loginmodule.SamplePrincipal;
public class SampleLoginModule implements LoginModule {
private Subject subject;
private CallbackHandler callbackHandler;
private Map sharedState;
private Map options;
// configurable option
private boolean debug = false;
private boolean succeeded = false;
private boolean commitSucceeded = false;
// username and password
private String username;
private char[] password;
private JMXPrincipal user;
// testUser's SamplePrincipal
private SamplePrincipal userPrincipal;
public SampleLoginModule() {
System.out.println("Login Module - constructor called");
}
public boolean abort() throws LoginException {
System.out.println("Login Module - abort called");
if (succeeded == false) {
return false;
} else if (succeeded == true && commitSucceeded == false) {
// login succeeded but overall authentication failed
succeeded = false;
username = null;
if (password != null) {
for (int i = 0; i < password.length; i++)
password[i] = ' ';
password = null;
}
userPrincipal = null;
} else {
// overall authentication succeeded and commit succeeded,
// but someone else's commit failed
logout();
}
return true;
// return false;
}
public boolean commit() throws LoginException {
System.out.println("Login Module - commit called");
subject.getPrincipals().add(user);
return succeeded;
}
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState,
Map<String, ?> options) {
System.out.println("Login Module - initialize called");
this.subject = subject;
this.callbackHandler = callbackHandler;
this.sharedState = sharedState;
this.options = options;
// System.out.println("testOption value: " + (String) options.get("testOption"));
debug = "true".equalsIgnoreCase((String) options.get("debug"));
succeeded = false;
}
public boolean login() throws LoginException {
System.out.println("Login Module - login called");
if (callbackHandler == null) {
throw new LoginException("Oops, callbackHandler is null");
}
Callback[] callbacks = new Callback[2];
callbacks[0] = new NameCallback("name:");
callbacks[1] = new PasswordCallback("password:", false);
try {
callbackHandler.handle(callbacks);
} catch (IOException e) {
throw new LoginException("Oops, IOException calling handle on callbackHandler");
} catch (UnsupportedCallbackException e) {
throw new LoginException("Oops, UnsupportedCallbackException calling handle on callbackHandler");
}
NameCallback nameCallback = (NameCallback) callbacks[0];
PasswordCallback passwordCallback = (PasswordCallback) callbacks[1];
String name = nameCallback.getName();
String password = new String(passwordCallback.getPassword());
if ("sohanb".equals(name) && "welcome".equals(password)) {
System.out.println("Success! You get to log in!");
user = new JMXPrincipal(name);
succeeded = true;
return succeeded;
} else {
System.out.println("Failure! You don't get to log in");
succeeded = false;
throw new FailedLoginException("Sorry! No login for you.");
}
// return true;
}
public boolean logout() throws LoginException {
System.out.println("Login Module - logout called");
return false;
}
}
JMX client code :
package client;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import com.sigma.SystemConfigMBean;
public class SystemConfigClient {
public static final String HOST = "localhost";
public static final String PORT = "8888";
public static void main(String[] args) throws IOException, MalformedObjectNameException {
JMXServiceURL url =
new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + HOST + ":" + PORT + "/jmxrmi");
//service:jmx:rmi:///jndi/rmi://localhost:8888/jmxrmi
// for passing credentials for password
Map<String, String[]> env = new HashMap<>();
String[] credentials = { "sohanb", "welcome" };
env.put(JMXConnector.CREDENTIALS, credentials);
JMXConnector jmxConnector = JMXConnectorFactory.connect(url,env);
MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection();
//ObjectName should be same as your MBean name
ObjectName mbeanName = new ObjectName("com.sigma.jmx:type=SystemConfig");
//Get MBean proxy instance that will be used to make calls to registered MBean
SystemConfigMBean mbeanProxy =
(SystemConfigMBean) MBeanServerInvocationHandler.newProxyInstance(
mbeanServerConnection, mbeanName, SystemConfigMBean.class, true);
//let's make some calls to mbean through proxy and see the results.
System.out.println("Current SystemConfig::" + mbeanProxy.doConfig());
String autenticate = RestClient.authenticate("handong", "welcome", true);
System.out.println("Got autenticate Toekn id as " + autenticate);
mbeanProxy.setToken(autenticate);
mbeanProxy.setSchemaName("NewSchema");
mbeanProxy.setThreadCount(5);
System.out.println("New SystemConfig::" + mbeanProxy.doConfig());
//let's terminate the mbean by making thread count as 0
// mbeanProxy.setThreadCount(0);
//close the connection
jmxConnector.close();
}
}
Sample JAAS file:
Sample {
com.sigma.loginmodule.SampleLoginModule required debug=true ;
};
I can see only way to resolve this is to write your own custom JAAS autheticator which implements JMXAuthenticator .
Code snippet of my main authenticate method used for authentication.
This method call invoke my login module passed in constructor of JAAS authenticator,
#SuppressWarnings("unchecked")
public final Subject authenticate(final Object credentials) throws SecurityException {
Map<String, Object> myCredentials = new HashMap<String, Object>();
if (credentials instanceof String[]) {
// JConsole sends the credentials as string array
// credentials[0] is the username
// credentials[1] is the password
String[] args = (String[]) credentials;
if (args.length == 2) {
myCredentials.put(USERNAME, args[0]);
char[] pw = null;
if (args[1] != null) {
pw = args[1].toCharArray();
}
myCredentials.put(PASSWORD, pw);
} else {
throw new SecurityException();
}
} else if (credentials instanceof Map) {
myCredentials.putAll((Map) credentials);
if (sslEnabled && myCredentials.containsKey(CERTIFICATE)) {
throw new SecurityException();
}
} else {
throw new SecurityException();
}
LoginContext lc = null;
try {
lc = new LoginContext(systemName, new CredentialCallbackHandler(systemName, myCredentials));
System.out.println("JAAS authenticator called ...");
} catch (LoginException le) {
le.printStackTrace();
}
try {
lc.login();
try {
Subject.doAsPrivileged(lc.getSubject(), new PrintCodeBaseAndPrincipalsAction(), null);
} catch (PrivilegedActionException ex) {
if (ex.getException() instanceof SecurityException) {
throw (SecurityException) ex.getException();
} else {
throw new SecurityException(ex.getException());
}
}
return lc.getSubject();
} catch (LoginException ex) {
throw new SecurityException(ex);
} catch (SecurityException ex) {
throw ex;
} catch (Throwable ex) {
throw new SecurityException(ex);
}
}
Here is how i invoke and set my JAAS authenticator constructor ,
Map<String, Object> env = new HashMap<String, Object>();
JAASJMXAuthenticator authenticator = new JAASJMXAuthenticator(jaasConfigName, false);
if (authenticator != null) {
System.out.println("JAASJMXAuthenticator is not null");
env.put(JMXConnectorServer.AUTHENTICATOR, authenticator);
}
Hope this helps someone in future. I can provide full code sample if asked.
Cheers!

MvvmCross HTTP DownloadCache with authentication

In my app, the user need to be authenticated on the server to download data using WebAPIs.
The MvvmCross DownloadCache plugin seems to handle only basic HTTP GET queries. I can't add my authentication token in the url as it's a big SAML token.
How can I add a HTTP header to queries done through DownloadCache plugin ?
With the current version I think I should inject my own IMvxHttpFileDownloader but I'm looking for an easier solution. Injecting my own MvxFileDownloadRequest would be better (not perfect) but it doesn't have an interface...
I'm able to do it registering a custom IWebRequestCreate for a custom scheme (http-auth://).
It's a bit ugly to transform urls from my datasource but it does the job.
public class AuthenticationWebRequestCreate : IWebRequestCreate
{
public const string HttpPrefix = "http-auth";
public const string HttpsPrefix = "https-auth";
private static string EncodeCredential(string userName, string password)
{
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string credential = userName + ":" + password;
return Convert.ToBase64String(encoding.GetBytes(credential));
}
public static void RegisterBasicAuthentication(string userName, string password)
{
var authenticateValue = "Basic " + EncodeCredential(userName, password);
AuthenticationWebRequestCreate requestCreate = new AuthenticationWebRequestCreate(authenticateValue);
Register(requestCreate);
}
public static void RegisterSamlAuthentication(string token)
{
var authenticateValue = "SAML2 " + token;
AuthenticationWebRequestCreate requestCreate = new AuthenticationWebRequestCreate(authenticateValue);
Register(requestCreate);
}
private static void Register(AuthenticationWebRequestCreate authenticationWebRequestCreate)
{
WebRequest.RegisterPrefix(HttpPrefix, authenticationWebRequestCreate);
WebRequest.RegisterPrefix(HttpsPrefix, authenticationWebRequestCreate);
}
private readonly string _authenticateValue;
public AuthenticationWebRequestCreate(string authenticateValue)
{
_authenticateValue = authenticateValue;
}
public WebRequest Create(System.Uri uri)
{
UriBuilder uriBuilder = new UriBuilder(uri);
switch (uriBuilder.Scheme)
{
case HttpPrefix:
uriBuilder.Scheme = "http";
break;
case HttpsPrefix:
uriBuilder.Scheme = "https";
break;
default:
break;
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriBuilder.Uri);
request.Headers[HttpRequestHeader.Authorization] = _authenticateValue;
return request;
}
}

Safari Push Notifications

I would like to implement push notifications for my website (obviously only in compatible browser as Safari 7).
I have read the Apple documentation and I have successfully created my package containing my icon.iconset, my certificate.p12, manifest.json and a website.json.
Now I would like to ask the permission to the user when I first visit the website. If he allows it, I should send the package.
Everything is pretty clear but I don't know how to go on.
How do I create my push package out of my files? How do I precisely sign it? The package should be always the same so I could sign it on my mac and upload to my server only one package.
If you have experience with this technology, please let me know :)
I have successfully create push package to ask permission on safari web push notifications using REST API in java. Also I have follow steps which provide by Apple officials on there sites.
Please follow below steps to create push package.
Create your web push notification P12 certificate from your apple account.
Create your REST API using https for pushPackage which contain icon.iconset, your certificate.p12, manifest.json and a website.json. p12 certificate must be web push notification certificate.
How to create push package:- Please refer below java code. I have create push package using java servlet. which provide 2 web service end points.
v1/pushpackage/webpushID
v1/log
Servlet which process your push package request which send by safari push notification method
SafariPushPakageAPI.java
/*
Push Package REST API handler
*/
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import com.safari.Packager;
public class SafariPushPakageAPI extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
public static String ServerPath = null;
private static final String REQUEST_PERMISSION = "/v1/pushPackages/YOUR_WEB_PUSH_ID";
private static final String REQUEST_ERRORLOG = "/v1/log";
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doRequest(request, response);
}
// /v1/pushPackages/webpushID
// /v1/log
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doRequest(request, response);
}
private void doRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("===>> SAFARI PUSH NOTIFICATION REQUEST");
String path = request.getPathInfo();
System.out.println("PATH ===>> "+path);
if(path == null){
doRequestPermission(request, response);
}else if (path.equalsIgnoreCase(REQUEST_PERMISSION)){
doRequestPermission(request, response);
}else if (path.equalsIgnoreCase(REQUEST_ERRORLOG)){
doRequestShowErrorLog(request, response);
}else{
doRequestPermission(request, response);
}
}
private void doRequestPermission(HttpServletRequest request,HttpServletResponse response) {
try{
System.out.println("INSIDE REQUEST PERMISSION ==>>>");
System.out.println(IOUtils.toString(request.getReader()));
String authToken = StringUtils.isBlank(request.getParameter("token")) ? "UserTokenRT124DFGH" : StringUtils.trimToEmpty(request.getParameter("token"));
System.out.println("=>>>>>>>>>> USER TOKEN =>>>>>>>>>> "+authToken);
#SuppressWarnings("deprecation")
String packagePath =request.getRealPath("pushPackage.raw/icon.iconset/"); // LOCATION WHERE YOUR PUSH PACKAGE FOLDER CONTAIN LOGOS AND website.json file
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;filename=\"pushpackage.zip\"");
OutputStream out = response.getOutputStream();
out.write(Packager.createPackageFile(authToken,packagePath));
response.flushBuffer();
}catch(IOException ioe){
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private void doRequestShowErrorLog(HttpServletRequest request,HttpServletResponse response) {
try{
System.out.println("ERROR LOG STARTED");
System.out.println(IOUtils.toString(request.getReader()));
System.out.println("END");
}catch(Exception e){
e.printStackTrace();
}
}
}
Packager.java
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;
/**
*
* #author Ritesh
*/
public class Packager {
final static String CERTIFICATE_PATH="PATH TO YOUR 12 CERTIFICATE";
final static String CERTIFICATE_PASS="PASSWORD";
static String getJSON(String authenticationToken) throws Exception {
JSONObject obj = new JSONObject();
obj.put("websiteName", "WEB SITE NAME");
obj.put("websitePushID", "WEB PUSH ID");
obj.put("allowedDomains", new JSONArray());
obj.getJSONArray("allowedDomains").put("https://TEST.EXAMPLE.net");//LIST OF DOMAINS ALLOW
obj.put("urlFormatString", "https://TEST.EXAMPLE.net/%#");
obj.put("authenticationToken", authenticationToken);
obj.put("webServiceURL", "https://API.EXAMPLE.COM");//callback URL WITHOUT WEB SERVICE ENDPOINT NAME
return obj.toString();
}
public static byte[] createPackageFile(String authenticationToken, String path) throws Exception {
System.out.println("packaging safari file with token: " + authenticationToken);
ZipHandler zip = new ZipHandler();
File dir = new File(path);
for (File file : dir.listFiles()) {
InputStream is = new FileInputStream(file);
byte[] bytes = IOUtils.toByteArray(is);
zip.addFile("icon.iconset", file.getName(),bytes );
}
zip.addFile("", "website.json", getJSON(authenticationToken).getBytes());
byte[] manifest = zip.manifest();
zip.addFile("", "manifest.json", manifest);
zip.addFile("", "signature", sign(manifest));
return zip.getBytes();
}
static byte[] sign(byte bytesToSign[]) throws Exception {
return new PKCS7Signer().sign(CERTIFICATE_PATH,CERTIFICATE_PASS, bytesToSign);
}
/**
* Servlet handler , should listen on the callback URL (as in webServiceURL)
* #param requestPath
* #param req
* #param servletRequest
* #param servletResponse
* #throws Exception
*/
public static void main(String[] args) throws Exception {
Packager.createPackageFile("SafriNotifcation","");
}
}
PKCS7Signer.java which create your signature file.
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Security;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.CMSTypedData;
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.bouncycastle.util.Store;
public final class PKCS7Signer {
static {
try{
Security.addProvider(new BouncyCastleProvider());
}catch(Exception e){
e.printStackTrace();
}
}
private KeyStore getKeystore(String storeLocation, String storePasswd) throws Exception {
if (storeLocation == null) {
System.out.println("Could not find store file (.p12)");
return null;
}
// First load the keystore object by providing the p12 file path
KeyStore clientStore = KeyStore.getInstance("PKCS12");
// replace testPass with the p12 password/pin
clientStore.load(new FileInputStream(storeLocation), storePasswd.toCharArray());
return clientStore;
}
private X509CertificateHolder getCert(KeyStore keystore, String alias) throws Exception {
java.security.cert.Certificate c = keystore.getCertificate(alias);
return new X509CertificateHolder(c.getEncoded());
}
private PrivateKey getPrivateKey(KeyStore keystore, String alias, String storePasswd) throws Exception {
return (PrivateKey) keystore.getKey(alias, storePasswd.toCharArray());
}
public byte[] sign(String storeLocation, String storePasswd, byte[] dataToSign) throws Exception {
KeyStore clientStore = getKeystore(storeLocation, storePasswd);
if (clientStore == null) {
return null;
}
Enumeration aliases = clientStore.aliases();
String alias = "";
while (aliases.hasMoreElements()) {
alias = (String) aliases.nextElement();
if (clientStore.isKeyEntry(alias)) {
break;
}
}
CMSTypedData msg = new CMSProcessableByteArray(dataToSign); // Data to sign
X509CertificateHolder x509Certificate = getCert(clientStore, alias);
List certList = new ArrayList();
certList.add(x509Certificate); // Adding the X509 Certificate
Store certs = new JcaCertStore(certList);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
// Initializing the the BC's Signer
ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(
getPrivateKey(clientStore, alias, storePasswd));
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder()
.setProvider("BC").build()).build(sha1Signer, x509Certificate));
// adding the certificate
gen.addCertificates(certs);
// Getting the signed data
CMSSignedData sigData = gen.generate(msg, false);
return sigData.getEncoded();
}
}
please note used latest bouncy castle jars for create signature file
bcprov-jdk15on-157.jar
bcpkix-jdk15on-157.jar
Write your javascript on your client side page.it contains simple java script to get permissions.
///
// For safari
var domain="YOUR WEB PUSH ID";
function safariIniti() {
var pResult = window.safari.pushNotification.permission(domain);
if(pResult.permission === 'default') {
//request permission
requestPermissions();
} else if (pResult.permission === 'granted') {
console.log("Permission for " + domain + " is " + pResult.permission);
var token = pResult.deviceToken;
// Show subscription for debug
console.log('Subscription details:'+token);
} else if(pResult.permission === 'denied') {
console.log("Permission for " + domain + " is " + pResult.permission);
}
}
function getToken(){
// always start with a letter (for DOM friendlyness)
var idstr=String.fromCharCode(Math.floor((Math.random()*25)+65));
do {
// between numbers and characters (48 is 0 and 90 is Z (42-48 = 90)
var ascicode=Math.floor((Math.random()*42)+48);
if (ascicode<58 || ascicode>64){
// exclude all chars between : (58) and # (64)
idstr+=String.fromCharCode(ascicode);
}
} while (idstr.length<32);
return (idstr);
}
function requestPermissions() {
var tokenVal = getToken();
window.safari.pushNotification.requestPermission('WEb service url without end points',domain,{token:tokenVal},
function(subscription) {
console.log(subscription.permission);
console.log("PERMISSION ====>> "+subscription.permission);
if(subscription.permission === 'granted') {
//TODO
}
else if(subscription.permission === 'denied') {
// TODO:
}
});
}
Apple provides a php file that you can use to create your push package including the signature. https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NotificationProgrammingGuideForWebsites/CompanionFile.zip
Alternatively, you can use the push_package gem, https://github.com/SymmetricInfinity/push_package, which we developed when implementing safari push notifications for zeropush.com. More details are available at https://zeropush.com/blog/implementing-safari-push-notifications-in-osx-mavericks.
Follow this apple documentation and github repo, they include sufficient information required to create a safari push notifications.

Scribe and Atlassian rest

I'm trying to use Scribe to use Atlassian Jira using example from here:
https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+OAuth+authentication
Anyone have any luck?
Here's what I got:
public class JiraAPI extends DefaultApi10a {
static final String BASE = "http://xasdf:8080/plugins/servlet";
#Override
public String getAccessTokenEndpoint()
{
return BASE + "/oauth/access-token";
}
#Override
public String getAuthorizationUrl(Token requestToken)
{
return BASE + "/oauth/authorize?oauth_token="+requestToken.getToken();
}
#Override
public String getRequestTokenEndpoint()
{
return BASE + "/oauth/request-token";
}
#Override
public SignatureService getSignatureService() {
return new RSASha1SignatureService(getPrivateKey());
}
private static PrivateKey getPrivateKey()
{
String str = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMPQ5BCMxlUq2TYy\n"+
"iRIoEUsz6HGTJhHuasS2nx1Se4Co3lxwxyubVdFj8AuhHNJSmJvjlpbTsGOjLZpr\n"+
"HyDEDdJmf1Fensh1MhUnBZ4a7uLrZrKzFHHJdamX9pxapB89vLeHlCot9hVXdrZH\n"+
"nNtg6FdmRKH/8gbs8iDyIayFvzYDAgMBAAECgYA+c9MpTBy9cQsR9BAvkEPjvkx2\n"+
"XL4ZnfbDgpNA4Nuu7yzsQrPjPomiXMNkkiAFHH67yVxwAlgRjyuuQlgNNTpKvyQt\n"+
"XcHxffnU0820VmE23M+L7jg2TlB3+rUnEDmDvCoyjlwGDR6lNb7t7Fgg2iR+iaov\n"+
"0iVzz+l9w0slRlyGsQJBAPWXW2m3NmFgqfDxtw8fsKC2y8o17/cnPjozRGtWb8LQ\n"+
"g3VCb8kbOFHOYNGazq3M7+wD1qILF2h/HecgK9eQrZ0CQQDMHXoJMfKKbrFrTKgE\n"+
"zyggO1gtuT5OXYeFewMEb5AbDI2FfSc2YP7SHij8iQ2HdukBrbTmi6qxh3HmIR58\n"+
"I/AfAkEA0Y9vr0tombsUB8cZv0v5OYoBZvCTbMANtzfb4AOHpiKqqbohDOevLQ7/\n"+
"SpvgVCmVaDz2PptcRAyEBZ5MCssneQJAB2pmvaDH7Ambfod5bztLfOhLCtY5EkXJ\n"+
"n6rZcDbRaHorRhdG7m3VtDKOUKZ2DF7glkQGV33phKukErVPUzlHBwJAScD9TqaG\n"+
"wJ3juUsVtujV23SnH43iMggXT7m82STpPGam1hPfmqu2Z0niePFo927ogQ7H1EMJ\n"+
"UHgqXmuvk2X/Ww==";
try
{
KeyFactory fac = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(str.getBytes()));
return fac.generatePrivate(privKeySpec);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
Scribe has always been easy with other OAuth based providers, but this provider always "oauth_problem=signature_invalid" from debug:
generating signature...
base string is: POST&http%3A%2F%2Fxasdf%3A8080%2Fplugins%2Fservlet%2Foauth%2Frequest-token&oauth_callback%3Doob%26oauth_consumer_key%3Dhardcoded-consumer%26oauth_nonce%3D1556398454%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3D1357151719%26oauth_version%3D1.0
signature is: AJugUeZGup5dZvjNjx6bec6OrAszZVK+pMrTzahZbbzKzGkbli7okBy2KO5ww+OtqqnHWRgyzfWnQ0k6R5U0JzjR4QiOANJuwV8Un1NTZsrK32daefCp2uZ6W2d2Y/fmIl3toyCjAx41c3oJ78572vVFmBGihHUTUOYTlFP1X3M=
appended additional OAuth parameters: { oauth_callback -> oob , oauth_signature -> AJugUeZGup5dZvjNjx6bec6OrAszZVK+pMrTzahZbbzKzGkbli7okBy2KO5ww+OtqqnHWRgyzfWnQ0k6R5U0JzjR4QiOANJuwV8Un1NTZsrK32daefCp2uZ6W2d2Y/fmIl3toyCjAx41c3oJ78572vVFmBGihHUTUOYTlFP1X3M= , oauth_version -> 1.0 , oauth_nonce -> 1556398454 , oauth_signature_method -> RSA-SHA1 , oauth_consumer_key -> hardcoded-consumer , oauth_timestamp -> 1357151719 }
using Http Header signature
sending request...
response status code: 401
Exception in thread "main" org.scribe.exceptions.OAuthException: Response body is incorrect. Can't extract token and secret from this: 'oauth_signature=AJugUeZGup5dZvjNjx6bec6OrAszZVK%2BpMrTzahZbbzKzGkbli7okBy2KO5ww%2BOtqqnHWRgyzfWnQ0k6R5U0JzjR4QiOANJuwV8Un1NTZsrK32daefCp2uZ6W2d2Y%2FfmIl3toyCjAx41c3oJ78572vVFmBGihHUTUOYTlFP1X3M%3D&oauth_signature_base_string=POST%26http%253A%252F%252Ftracker%253A8080%252Fplugins%252Fservlet%252Foauth%252Frequest-token%26oauth_callback%253Doob%2526oauth_consumer_key%253Dhardcoded-consumer%2526oauth_nonce%253D1556398454%2526oauth_signature_method%253DRSA-SHA1%2526oauth_timestamp%253D1357151719%2526oauth_version%253D1.0&oauth_problem=signature_invalid&oauth_signature_method=RSA-SHA1'
response body: oauth_signature=AJugUeZGup5dZvjNjx6bec6OrAszZVK%2BpMrTzahZbbzKzGkbli7okBy2KO5ww%2BOtqqnHWRgyzfWnQ0k6R5U0JzjR4QiOANJuwV8Un1NTZsrK32daefCp2uZ6W2d2Y%2FfmIl3toyCjAx41c3oJ78572vVFmBGihHUTUOYTlFP1X3M%3D&oauth_signature_base_string=POST%26http%253A%252F%252Ftracker%253A8080%252Fplugins%252Fservlet%252Foauth%252Frequest-token%26oauth_callback%253Doob%2526oauth_consumer_key%253Dhardcoded-consumer%2526oauth_nonce%253D1556398454%2526oauth_signature_method%253DRSA-SHA1%2526oauth_timestamp%253D1357151719%2526oauth_version%253D1.0&oauth_problem=signature_invalid&oauth_signature_method=RSA-SHA1
at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:41)
As far as I can tell, you cannot use Scribe with JIRA/Atlassian OAuth, since Scribe does not support RSA-SHA1 signatures, but this is the only Signature available in Atlassian's OAuth providers.
The only Java library, that I could find, which supports this method is the one used in the example code linked in the questions - the net.oauth one.
I have this working using scribe 1.3.6 using the provided RSASha1SignatureService, here's how I'm extracting the private key (from a PKCS#8 PEM file, the one with the BEGIN PRIVATE KEY header, not the BEGIN RSA PRIVATE KEY, which is the SSLeay format)
package com.company.client.api;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import org.scribe.builder.api.DefaultApi10a;
import org.scribe.builder.api.DefaultApi20;
import org.scribe.model.OAuthConfig;
import org.scribe.model.Token;
import org.scribe.services.RSASha1SignatureService;
import org.scribe.services.SignatureService;
public class JiraApi extends DefaultApi10a {
private static final String AUTHORIZE_URL = "http://localhost:8080/plugins/servlet/oauth/authorize?oauth_token=%s";
private static final String REQUEST_TOKEN_RESOURCE = "http://localhost:8080/plugins/servlet/oauth/request-token";
private static final String ACCESS_TOKEN_RESOURCE = "http://localhost:8080/plugins/servlet/oauth/access-token";
#Override
public String getAccessTokenEndpoint() {
return ACCESS_TOKEN_RESOURCE;
}
#Override
public String getRequestTokenEndpoint() {
return REQUEST_TOKEN_RESOURCE;
}
#Override
public String getAuthorizationUrl(Token requestToken) {
return String.format(AUTHORIZE_URL, requestToken.getToken());
}
#Override
public SignatureService getSignatureService() {
return new RSASha1SignatureService(getPrivateKey());
}
private PrivateKey getPrivateKey() {
try {
byte[] key = Base64.getDecoder().decode(JiraClientImpl.privateKey); // this is the PEM encoded PKCS#8 private key
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(keySpec);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}