separate sdk & connectors

separate sdk & connectors
This commit is contained in:
MaxKey 2020-07-10 08:43:34 +08:00
parent 1f80ed3d7e
commit 57ce60fdd8
220 changed files with 17 additions and 13295 deletions

View File

@ -10,7 +10,6 @@ dependencies {
compile project(":maxkey-core") compile project(":maxkey-core")
compile project(":maxkey-persistence") compile project(":maxkey-persistence")
compile project(":maxkey-client-sdk")
compile project(":maxkey-protocols:maxkey-protocol-oauth-2.0") compile project(":maxkey-protocols:maxkey-protocol-oauth-2.0")
compile project(":maxkey-protocols:maxkey-protocol-saml-2.0") compile project(":maxkey-protocols:maxkey-protocol-saml-2.0")

View File

@ -1,25 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="bin/main" path="src/main/java">
<attributes>
<attribute name="gradle_scope" value="main"/>
<attribute name="gradle_used_by_scope" value="main,test"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="bin/test" path="src/test/java">
<attributes>
<attribute name="gradle_scope" value="test"/>
<attribute name="gradle_used_by_scope" value="test"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="bin/main" path="src/main/resources">
<attributes>
<attribute name="gradle_scope" value="main"/>
<attribute name="gradle_used_by_scope" value="main,test"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/>
</classpath>

View File

@ -1 +0,0 @@
/build/

View File

@ -1,40 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>maxkey-client-sdk</name>
<comment>maxkey-client-sdk</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.boot.validation.springbootbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
</natures>
</projectDescription>

View File

@ -1,11 +0,0 @@
build.commands=org.eclipse.jdt.core.javabuilder
connection.arguments=
connection.gradle.distribution=GRADLE_DISTRIBUTION(WRAPPER)
connection.java.home=null
connection.jvm.arguments=
connection.project.dir=..
containers=org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7/
derived.resources=.gradle,build
eclipse.preferences.version=1
natures=org.eclipse.jdt.core.javanature
project.path=\:maxkey-client-sdk

View File

@ -1,2 +0,0 @@
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@ -1,113 +0,0 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.builder.cleanOutputFolder=clean
org.eclipse.jdt.core.builder.duplicateResourceTask=warning
org.eclipse.jdt.core.builder.invalidClasspath=abort
org.eclipse.jdt.core.builder.recreateModifiedClassFileInOutputFolder=ignore
org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch
org.eclipse.jdt.core.circularClasspath=warning
org.eclipse.jdt.core.classpath.exclusionPatterns=enabled
org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled
org.eclipse.jdt.core.classpath.outputOverlappingAnotherSource=error
org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled
org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull
org.eclipse.jdt.core.compiler.annotation.nonnull.secondary=
org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault
org.eclipse.jdt.core.compiler.annotation.nonnullbydefault.secondary=
org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable
org.eclipse.jdt.core.compiler.annotation.nullable.secondary=
org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.maxProblemPerUnit=100
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
org.eclipse.jdt.core.compiler.problem.deadCode=warning
org.eclipse.jdt.core.compiler.problem.deprecation=warning
org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled
org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore
org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled
org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning
org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore
org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning
org.eclipse.jdt.core.compiler.problem.nonnullTypeVariableFromLegacyInvocation=warning
org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error
org.eclipse.jdt.core.compiler.problem.nullReference=warning
org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error
org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning
org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
org.eclipse.jdt.core.compiler.problem.pessimisticNullAnalysisForFreeTypeVariables=warning
org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore
org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore
org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled
org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled
org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled
org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning
org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentType=warning
org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentTypeStrict=disabled
org.eclipse.jdt.core.compiler.problem.unlikelyEqualsArgumentType=info
org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore
org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore
org.eclipse.jdt.core.compiler.problem.unusedImport=warning
org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore
org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore
org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
org.eclipse.jdt.core.compiler.source=1.8
org.eclipse.jdt.core.incompatibleJDKLevel=ignore
org.eclipse.jdt.core.incompleteClasspath=error

View File

@ -1,2 +0,0 @@
eclipse.preferences.version=1
org.eclipse.jdt.launching.PREF_STRICTLY_COMPATIBLE_JRE_NOT_AVAILABLE=warning

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="maxkey-client-sdk">
<wb-resource deploy-path="/" source-path="/src/main/java"/>
<wb-resource deploy-path="/" source-path="/src/test/java"/>
<wb-resource deploy-path="/" source-path="/src/main/resources"/>
</wb-module>
</project-modules>

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<fixed facet="java"/>
<fixed facet="jst.utility"/>
<installed facet="jst.utility" version="1.0"/>
<installed facet="java" version="1.8"/>
</faceted-project>

File diff suppressed because one or more lines are too long

View File

@ -1,12 +0,0 @@
description = "maxkey-client-sdk"
dependencies {
/*compile group: 'commons-io', name: 'commons-io', version: '2.6'
compile group: 'commons-logging', name: 'commons-logging', version: '1.2'
compile group: 'log4j', name: 'log4j', version: '1.2.17'
compile group: 'org.slf4j', name: 'slf4j-api', version: '1.5.11'
compile group: 'commons-codec', name: 'commons-codec', version: '1.14'
compile group: 'com.nimbusds', name: 'nimbus-jose-jwt', version: '8.10'
compile group: 'com.google.code.gson', name: 'gson', version: '2.8.6'
*/
}

View File

@ -1,139 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.crypto;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.commons.codec.binary.Base64;
/**
* Base64 Utils
*
* @author Crystal.Sea
*
*/
public final class Base64Utils {
public static String encodeBase64(byte[] simple){
String cipher=BytesUtils.bytes2String(Base64.encodeBase64(simple));
return cipher;
}
public static byte[] decoderBase64(String cipher){
byte[] simple=Base64.decodeBase64(cipher);
return simple;
}
public static String encode(String simple){
return encodeBase64(simple.getBytes());
}
public static String encoder(byte[] simple){
return encodeBase64(simple);
}
public static String decode(String cipher){
return BytesUtils.bytes2String(decoderBase64(cipher));
}
public static byte[] decoder(String cipher){
return decoderBase64(cipher);
}
/**
*encode file to base64 Code String
* @param fileName file path
* @return *
* @throws Exception
*/
public static String fileToBase64(String fileName) throws Exception {
File file = new File(fileName);;
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
inputFile.read(buffer);
inputFile.close();
return encodeBase64(buffer);
}
/**
* base64 Code decode String save to targetPath
* @param base64Code
* @param targetPath
* @throws Exception
*/
public static void decodeBase64ToFile(String base64Code, String targetPath)
throws Exception {
byte[] buffer = decoderBase64(base64Code);
FileOutputStream out = new FileOutputStream(targetPath);
out.write(buffer);
out.close();
}
/**
* base64 code save to file
* @param base64Code
* @param targetPath
* @throws Exception
*/
public static void base64ToFile(String base64Code, String targetPath)
throws Exception {
byte[] buffer = base64Code.getBytes();
FileOutputStream out = new FileOutputStream(targetPath);
out.write(buffer);
out.close();
}
public static String base64UrlEncode(byte[] simple) {
String s = new String(Base64.encodeBase64(simple)); // Regular base64
// encoder
s = s.split("=")[0]; // Remove any trailing '='s
s = s.replace('+', '-'); // 62nd char of encoding
s = s.replace('/', '_'); // 63rd char of encoding
return s;
}
public static byte[] base64UrlDecode(String cipher) {
String s = cipher;
s = s.replace('-', '+'); // 62nd char of encoding
s = s.replace('_', '/'); // 63rd char of encoding
switch (s.length() % 4) { // Pad with trailing '='s
case 0:
break; // No pad chars in this case
case 2:
s += "==";
break; // Two pad chars
case 3:
s += "=";
break; // One pad char
default:
System.err.println("Illegal base64url String!");
}
return Base64.decodeBase64(s); // Standard base64 decoder
}
}

View File

@ -1,29 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.crypto;
public final class BytesUtils {
public static String bytes2String(byte[] bytesArray) {
String result = "";
for (Byte bts : bytesArray) {
result += (char) bts.intValue();
}
return result;
}
}

View File

@ -1,80 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
package org.maxkey.client.crypto;
import java.io.UnsupportedEncodingException;
/**
* @author Crystal.Sea
*
*/
public final class HexUtils {
static final byte[] HEX_CHAR_TABLE = {
(byte) '0', (byte) '1',(byte) '2',(byte) '3', (byte) '4',(byte) '5', (byte) '6', (byte) '7',
(byte) '8', (byte) '9',(byte) 'a', (byte) 'b',(byte) 'c',(byte) 'd', (byte) 'e', (byte) 'f'
};
public static String hex2String(byte[] b) {
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}
public static String bytes2HexString(byte[] raw) {
byte[] hex = new byte[2 * raw.length];
int index = 0;
for (byte b : raw) {
int v = b & 0xFF;
hex[index++] = HEX_CHAR_TABLE[v >>> 4];
hex[index++] = HEX_CHAR_TABLE[v & 0xF];
}
String s = "";
try {
s = new String(hex, "ASCII");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return s;
}
public static byte[] hex2Bytes(char[] hex) {
int length = hex.length / 2;
byte[] raw = new byte[length];
for (int i = 0; i < length; i++) {
int high = Character.digit(hex[i * 2], 16);
int low = Character.digit(hex[i * 2 + 1], 16);
int value = (high << 4) | low;
if (value > 127)
value -= 256;
raw[i] = (byte) value;
}
return raw;
}
public static byte[] hex2Bytes(String hex) {
return hex2Bytes(hex.toCharArray());
}
}

View File

@ -1,250 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
package org.maxkey.client.crypto;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.logging.LogFactory;
import org.maxkey.client.utils.StringGenerator;
/**
* Reciprocal cipher or Symmetric-key algorithm
*
* algorithm Support DES,DESede,Blowfish and AES
*
* default key value use ReciprocalUtils.defaultKey
*
* generateKey is generate random key for algorithm
*
* @author Crystal.Sea
*
*/
public final class ReciprocalUtils {
private static final String defaultKey= "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; //
public final class Algorithm {
public static final String DES = "DES";
public static final String DESede = "DESede";
public static final String Blowfish = "Blowfish";
public static final String AES = "AES";
}
public static byte[] encode(byte[] simpleBytes, SecretKey secretKey,String algorithm) {
// Create the ciphers
Cipher ecipher;
byte[] byteFinal = null;
try {
ecipher = Cipher.getInstance(secretKey.getAlgorithm());
// Encode the string into bytes using utf-8
ecipher.init(Cipher.ENCRYPT_MODE, secretKey);
// Encrypt
byteFinal = ecipher.doFinal(simpleBytes);
return byteFinal;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param simple
* @param secretKey
* must length
* @return
* @throws Exception
*/
public static byte[] encode(String simple, String secretKey,String algorithm) {
if (keyLengthCheck(secretKey, algorithm)) {
SecretKey key = generatorKey(secretKey, algorithm);
try {
return encode(simple.getBytes("UTF-8"), key, algorithm);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return null;
}
public static byte[] decoder(byte[] ciphersBytes, SecretKey secretKey,String algorithm) {
Cipher cipher;
byte[] byteFinal = null;
try {
cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byteFinal = cipher.doFinal(ciphersBytes);
// String simple=new String(byteFinal, "UTF8" );
// return simple;
return byteFinal;
} catch (Exception e) {
e.printStackTrace();
} finally {
cipher = null;
}
return null;
}
public static String decoder(byte[] ciphersBytes, String secretKey,String algorithm) {
if (keyLengthCheck(secretKey, algorithm)) {
SecretKey key = generatorKey(secretKey, algorithm);
try {
return new String(decoder(ciphersBytes, key, algorithm), "UTF8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return null;
}
private static SecretKey generatorDefaultKey(String algorithm) {
try {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
KeyGenerator _generator = KeyGenerator.getInstance(algorithm);
_generator.init(new SecureRandom(defaultKey.getBytes()));
SecretKey key = _generator.generateKey();
_generator = null;
return key;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static SecretKey generatorKey(String secretKey, String algorithm) {
try {
SecretKey key = new SecretKeySpec(secretKey.getBytes(), algorithm);
return key;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static boolean keyLengthCheck(String secretKey,String algorithm){
boolean lengthCheck=false;
if(algorithm.equals(Algorithm.DES)){
if(secretKey.length()==8){
lengthCheck=true;
}else{
LogFactory.getLog(ReciprocalUtils.class).debug("key length is "+secretKey.getBytes().length+" ,must lequal 8");
}
}else if(algorithm.equals(Algorithm.DESede)){
if(secretKey.length()==24){
lengthCheck=true;
}else{
LogFactory.getLog(ReciprocalUtils.class).debug("key length is "+secretKey.getBytes().length+" ,must equal 24");
}
}else if(algorithm.equals(Algorithm.AES)){
if(secretKey.length()==16){
lengthCheck=true;
}else{
LogFactory.getLog(ReciprocalUtils.class).debug("key length is "+secretKey.getBytes().length+" ,must equal 16");
}
}else if(algorithm.equals(Algorithm.Blowfish)){
if(secretKey.length()<= 16){
lengthCheck=true;
}else{
LogFactory.getLog(ReciprocalUtils.class).debug("key length is "+secretKey.getBytes().length+" ,must be less then 16");
}
}
return lengthCheck;
}
public static byte[] encodeByDefaultKey(String simple, String algorithm) {
SecretKey key = generatorDefaultKey(algorithm);
return encode(simple.getBytes(), key, algorithm);
}
public static String encode2HexByDefaultKey(String simple, String algorithm) {
byte[] byteFinal = encodeByDefaultKey(simple, algorithm);
String cipherHex = HexUtils.bytes2HexString(byteFinal);
return cipherHex;
}
public static byte[] decoderByDefaultKey(byte[] byteCiphers,String algorithm) {
SecretKey key = generatorDefaultKey(algorithm);
return decoder(byteCiphers, key, algorithm);
}
public static String decoderHexByDefaultKey(String ciphers, String algorithm) {
byte[] byteSimple = HexUtils.hex2Bytes(ciphers);
byte[] byteFinal = decoderByDefaultKey(byteSimple, algorithm);
String simple = null;
try {
simple = new String(byteFinal, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return simple;
}
/**
* encode by defaultKey with Algorithm.AES
*
* @param simple
* @return Hex
*/
public static String encode(String simple) {
return encode2HexByDefaultKey(simple, Algorithm.AES);
}
/**
* decoder by defaultKey with Algorithm.AES
*
* @param ciphers is HEX
*
* @return
*/
public static String decoder(String ciphers) {
return decoderHexByDefaultKey(ciphers, Algorithm.AES);
}
public static String generateKey(String algorithm){
if(algorithm.equals(Algorithm.DES)){
return (new StringGenerator(8)).randomGenerate();
}else if(algorithm.equals(Algorithm.AES)){
return (new StringGenerator(16)).randomGenerate();
}else if(algorithm.equals(Algorithm.Blowfish)){
return (new StringGenerator(16)).randomGenerate();
}else if(algorithm.equals(Algorithm.DESede)){
return (new StringGenerator(24)).randomGenerate();
}else{
return (new StringGenerator()).uniqueGenerate();
}
}
}

View File

@ -1,106 +0,0 @@
package org.maxkey.client.http;
/*
public class ApacheHttpClient{
private final CloseableHttpAsyncClient client;
public ApacheHttpClient() {
this(ApacheHttpClientConfig.defaultConfig());
}
public ApacheHttpClient(ApacheHttpClientConfig config) {
this(config.getHttpAsyncClientBuilder());
}
public ApacheHttpClient(HttpAsyncClientBuilder builder) {
this(builder.build());
}
public ApacheHttpClient(CloseableHttpAsyncClient client) {
this.client = client;
this.client.start();
}
@Override
public void close() throws IOException {
client.close();
}
@Override
public <T> Future<T> executeAsync(String userAgent, Map<String, String> headers, Verb httpVerb, String completeUrl,
byte[] bodyContents, OAuthAsyncRequestCallback<T> callback, OAuthRequest.ResponseConverter<T> converter) {
final HttpEntity entity = bodyContents == null ? null : new ByteArrayEntity(bodyContents);
return doExecuteAsync(userAgent, headers, httpVerb, completeUrl, entity, callback, converter);
}
@Override
public <T> Future<T> executeAsync(String userAgent, Map<String, String> headers, Verb httpVerb, String completeUrl,
MultipartPayload bodyContents, OAuthAsyncRequestCallback<T> callback,
OAuthRequest.ResponseConverter<T> converter) {
throw new UnsupportedOperationException("ApacheHttpClient does not support MultipartPayload yet.");
}
@Override
public <T> Future<T> executeAsync(String userAgent, Map<String, String> headers, Verb httpVerb, String completeUrl,
String bodyContents, OAuthAsyncRequestCallback<T> callback, OAuthRequest.ResponseConverter<T> converter) {
final HttpEntity entity = bodyContents == null ? null : new StringEntity(bodyContents, StandardCharsets.UTF_8);
return doExecuteAsync(userAgent, headers, httpVerb, completeUrl, entity, callback, converter);
}
@Override
public <T> Future<T> executeAsync(String userAgent, Map<String, String> headers, Verb httpVerb, String completeUrl,
File bodyContents, OAuthAsyncRequestCallback<T> callback, OAuthRequest.ResponseConverter<T> converter) {
final HttpEntity entity = bodyContents == null ? null : new FileEntity(bodyContents);
return doExecuteAsync(userAgent, headers, httpVerb, completeUrl, entity, callback, converter);
}
private <T> Future<T> doExecuteAsync(String userAgent, Map<String, String> headers, Verb httpVerb,
String completeUrl, HttpEntity entity, OAuthAsyncRequestCallback<T> callback,
OAuthRequest.ResponseConverter<T> converter) {
final RequestBuilder builder = getRequestBuilder(httpVerb);
builder.setUri(completeUrl);
if (httpVerb.isPermitBody()) {
if (!headers.containsKey(CONTENT_TYPE)) {
builder.addHeader(CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
}
builder.setEntity(entity);
}
for (Map.Entry<String, String> header : headers.entrySet()) {
builder.addHeader(header.getKey(), header.getValue());
}
if (userAgent != null) {
builder.setHeader(OAuthConstants.USER_AGENT_HEADER_NAME, userAgent);
}
final OAuthAsyncCompletionHandler<T> handler = new OAuthAsyncCompletionHandler<>(callback, converter);
final Future<HttpResponse> future = client.execute(builder.build(), handler);
return new ApacheHttpFuture<>(future, handler);
}
private static RequestBuilder getRequestBuilder(Verb httpVerb) {
switch (httpVerb) {
case GET:
return RequestBuilder.get();
case PUT:
return RequestBuilder.put();
case DELETE:
return RequestBuilder.delete();
case HEAD:
return RequestBuilder.head();
case POST:
return RequestBuilder.post();
case PATCH:
return RequestBuilder.patch();
case TRACE:
return RequestBuilder.trace();
case OPTIONS:
return RequestBuilder.options();
default:
throw new IllegalArgumentException("message build error: unknown verb type");
}
}
}*/

View File

@ -1,83 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.http;
import org.maxkey.client.crypto.Base64Utils;
/**
* @author Crystal.Sea
*
*/
public class AuthorizationHeader {
public static String AUTHORIZATION_HEADERNAME="Authorization";
public static String BASIC="Basic ";
public static String BEARER="Bearer ";
public static String createBasic( String username, String password ){
String authUserPass = username + ":" + password;
String encodedAuthUserPass = Base64Utils.encode(authUserPass );
return BASIC + encodedAuthUserPass;
}
public static String [] resolveBasic( String basic ){
if(isBasic(basic)){
String[] userPass =basic.split(" ");
String decodeUserPass = Base64Utils.decode(userPass[1] );
return decodeUserPass.split(":");
}else{
return null;
}
}
public static boolean isBasic( String basic ){
if(basic.startsWith(BASIC )){
return true;
}else{
return false;
}
}
public static String resolveBearer( String bearer ){
if(isBearer(bearer)){
return bearer.split(" ")[1];
}else{
return null;
}
}
public static String createBearer(String bearer){
return BEARER +bearer;
}
public static boolean isBearer( String bearer ){
if(bearer.startsWith(BEARER )){
return true;
}else{
return false;
}
}
}

View File

@ -1,26 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.http;
/**
* An enumeration containing the most common HTTP Verbs.
*/
public enum HttpVerb {
GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE, PATCH
}

View File

@ -1,71 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.http;
import org.maxkey.client.utils.HttpEncoder;
public class Parameter implements Comparable<Parameter> {
private final String key;
private final String value;
public Parameter(String key, String value) {
this.key = key;
this.value = value;
}
public String asUrlEncodedPair() {
return HttpEncoder.encode(key).concat("=").concat(HttpEncoder.encode(value));
}
@Override
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (other == this) {
return true;
}
if (!(other instanceof Parameter)) {
return false;
}
final Parameter otherParam = (Parameter) other;
return otherParam.getKey().equals(key) && otherParam.getValue().equals(value);
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
@Override
public int hashCode() {
return key.hashCode() + value.hashCode();
}
@Override
public int compareTo(Parameter parameter) {
final int keyDiff = key.compareTo(parameter.getKey());
return keyDiff == 0 ? value.compareTo(parameter.getValue()) : keyDiff;
}
}

View File

@ -1,122 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.http;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.maxkey.client.utils.HttpEncoder;
import org.maxkey.client.utils.Preconditions;
public class ParameterList {
private static final char QUERY_STRING_SEPARATOR = '?';
private static final String PARAM_SEPARATOR = "&";
private static final String PAIR_SEPARATOR = "=";
private static final String EMPTY_STRING = "";
private final List<Parameter> params;
public ParameterList() {
params = new ArrayList<>();
}
ParameterList(List<Parameter> params) {
this.params = new ArrayList<>(params);
}
public ParameterList(Map<String, String> map) {
this();
if (map != null && !map.isEmpty()) {
for (Map.Entry<String, String> entry : map.entrySet()) {
params.add(new Parameter(entry.getKey(), entry.getValue()));
}
}
}
public void add(String key, String value) {
params.add(new Parameter(key, value));
}
public String appendTo(String url) {
Preconditions.checkNotNull(url, "Cannot append to null URL");
final String queryString = asFormUrlEncodedString();
if (queryString.equals(EMPTY_STRING)) {
return url;
} else {
return url
+ (url.indexOf(QUERY_STRING_SEPARATOR) == -1 ? QUERY_STRING_SEPARATOR : PARAM_SEPARATOR)
+ queryString;
}
}
public String asOauthBaseString() {
return HttpEncoder.encode(asFormUrlEncodedString());
}
public String asFormUrlEncodedString() {
if (params.isEmpty()) {
return EMPTY_STRING;
}
final StringBuilder builder = new StringBuilder();
for (Parameter p : params) {
builder.append(PARAM_SEPARATOR).append(p.asUrlEncodedPair());
}
return builder.substring(1);
}
public void addAll(ParameterList other) {
params.addAll(other.getParams());
}
public void addQuerystring(String queryString) {
if (queryString != null && !queryString.isEmpty()) {
for (String param : queryString.split(PARAM_SEPARATOR)) {
try{
final String[] pair = param.split(PAIR_SEPARATOR);
final String key = HttpEncoder.decode(pair[0]);
final String value = pair.length > 1 ? HttpEncoder.decode(pair[1]) : EMPTY_STRING;
params.add(new Parameter(key, value));
}catch(Exception e){
}
}
}
}
public boolean contains(Parameter param) {
return params.contains(param);
}
public int size() {
return params.size();
}
public List<Parameter> getParams() {
return params;
}
public ParameterList sort() {
final ParameterList sorted = new ParameterList(params);
Collections.sort(sorted.getParams());
return sorted;
}
}

View File

@ -1,492 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.http;
import java.io.*;
import java.net.*;
import java.nio.charset.*;
import java.util.*;
import java.util.concurrent.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.maxkey.client.oauth.exceptions.*;
import org.maxkey.client.utils.HttpsTrusts;
import org.maxkey.client.utils.JsonUtils;
/**
* Represents an HTTP Request object
*
*/
public class Request
{
private static Log _log = LogFactory.getLog(Request. class );
public static final String DEFAULT_CONTENT_TYPE = "application/x-www-form-urlencoded";
private static final String CONTENT_LENGTH = "Content-Length";
private static final String CONTENT_TYPE = "Content-Type";
private static RequestTuner NOOP = new RequestTuner() {
@Override public void tune(Request request){}
};
private String url;
private HttpVerb verb;
private ParameterList querystringParams;
private ParameterList bodyParams;
private Map<String, String> headers;
private String payload = null;
private HttpURLConnection connection;
private String charset;
private byte[] bytePayload = null;
private boolean connectionKeepAlive = false;
private boolean followRedirects = true;
private Long connectTimeout = null;
private Long readTimeout = null;
private String realm;
/**
* Creates a new Http Request
*
* @param verb Http Verb (GET, POST, etc)
* @param url url with optional querystring parameters.
*/
public Request(HttpVerb verb, String url)
{
this.verb = verb;
this.url = url;
this.querystringParams = new ParameterList();
this.bodyParams = new ParameterList();
this.headers = new HashMap<String, String>();
}
/**
* Execute the request and return a {@link Response}
*
* @return Http Response
* @throws RuntimeException
* if the connection cannot be created.
*/
public Response send(RequestTuner tuner)
{
try
{
createConnection();
return doSend(tuner);
}
catch (Exception e)
{
throw new OAuthConnectionException(e);
}
}
public Response send()
{
return send(NOOP);
}
private void createConnection() throws IOException
{
String completeUrl = getCompleteUrl();
_log.debug("verb method : "+verb);
_log.debug("completeUrl : "+completeUrl);
if (connection == null)
{
System.setProperty("http.keepAlive", connectionKeepAlive ? "true" : "false");
connection = (HttpURLConnection) new URL(completeUrl).openConnection();
if(completeUrl.trim().startsWith("https")){
HttpsTrusts.beforeConnection();
}
connection.setInstanceFollowRedirects(followRedirects);
}
}
/**
* Returns the complete url (host + resource + encoded querystring parameters).
*
* @return the complete url.
*/
public String getCompleteUrl()
{
return querystringParams.appendTo(url);
}
Response doSend(RequestTuner tuner) throws IOException
{
connection.setRequestMethod(this.verb.name());
if (connectTimeout != null)
{
connection.setConnectTimeout(connectTimeout.intValue());
}
if (readTimeout != null)
{
connection.setReadTimeout(readTimeout.intValue());
}
addHeaders(connection);
if (verb.equals(HttpVerb.PUT) || verb.equals(HttpVerb.POST))
{
addBody(connection, getByteBodyContents());
}
tuner.tune(this);
return new Response(connection);
}
void addHeaders(HttpURLConnection conn)
{
for (String key : headers.keySet())
conn.setRequestProperty(key, headers.get(key));
}
void addBody(HttpURLConnection conn, byte[] content) throws IOException
{
conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(content.length));
// Set default content type if none is set.
if (conn.getRequestProperty(CONTENT_TYPE) == null)
{
conn.setRequestProperty(CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
}
conn.setDoOutput(true);
conn.getOutputStream().write(content);
}
/**
* Add an HTTP Header to the Request
*
* @param key the header name
* @param value the header value
*/
public void addHeader(String key, String value)
{
this.headers.put(key, value);
}
/**
* Add a body Parameter (for POST/ PUT Requests)
*
* @param key the parameter name
* @param value the parameter value
*/
public void addBodyParameter(String key, String value)
{
this.bodyParams.add(key, value);
}
/**
* Add a QueryString parameter
*
* @param key the parameter name
* @param value the parameter value
*/
public void addQuerystringParameter(String key, String value)
{
this.querystringParams.add(key, value);
}
public void addParameter(String key, String value) {
if (hasBodyContent()) {
bodyParams.add(key, value);
} else {
querystringParams.add(key, value);
}
}
protected boolean hasBodyContent() {
return verb == HttpVerb.PUT || verb == HttpVerb.POST;
}
/**
* Add body payload.
*
* This method is used when the HTTP body is not a form-url-encoded string,
* but another thing. Like for example XML.
*
* Note: The contents are not part of the OAuth signature
*
* @param payload the body of the request
*/
public void addPayload(String payload)
{
this.payload = payload;
}
/**
* Overloaded version for byte arrays
*
* @param payload
*/
public void addPayload(byte[] payload)
{
this.bytePayload = payload.clone();
}
/**
* set REST Content
*
* @param content
*/
public void addRestContent(String content)
{
this.payload = content;
}
/**
* set REST Content
*
* @param content
*/
public void addRestObject(Object content)
{
try {
this.bytePayload = JsonUtils.gson2Json(content).getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* set REST Content
*
* @param content
*/
public void addRestContent(byte[] content)
{
this.bytePayload = content.clone();
}
/**
* Get a {@link ParameterList} with the query string parameters.
*
* @return a {@link ParameterList} containing the query string parameters.
* @throws OAuthException if the request URL is not valid.
*/
public ParameterList getQueryStringParams()
{
try
{
ParameterList result = new ParameterList();
String queryString = new URL(url).getQuery();
result.addQuerystring(queryString);
result.addAll(querystringParams);
return result;
}
catch (MalformedURLException mue)
{
throw new OAuthException("Malformed URL", mue);
}
}
/**
* Obtains a {@link ParameterList} of the body parameters.
*
* @return a {@link ParameterList}containing the body parameters.
*/
public ParameterList getBodyParams()
{
return bodyParams;
}
/**
* Obtains the URL of the HTTP Request.
*
* @return the original URL of the HTTP Request
*/
public String getUrl()
{
return url;
}
/**
* Returns the URL without the port and the query string part.
*
* @return the OAuth-sanitized URL
public String getSanitizedUrl()
{
return url.replaceAll("\\?.*", "").replace("\\:\\d{4}", "");
}
*/
/**
* Returns the URL without the port and the query string part.
*
* @return the OAuth-sanitized URL
*/
public String getSanitizedUrl() {
if (url.startsWith("http://") && (url.endsWith(":80") || url.contains(":80/"))) {
return url.replaceAll("\\?.*", "").replaceAll(":80", "");
} else if (url.startsWith("https://") && (url.endsWith(":443") || url.contains(":443/"))) {
return url.replaceAll("\\?.*", "").replaceAll(":443", "");
} else {
return url.replaceAll("\\?.*", "");
}
}
/**
* Returns the body of the request
*
* @return form encoded string
* @throws OAuthException if the charset chosen is not supported
*/
public String getBodyContents()
{
try
{
return new String(getByteBodyContents(),getCharset());
}
catch(UnsupportedEncodingException uee)
{
throw new OAuthException("Unsupported Charset: "+charset, uee);
}
}
byte[] getByteBodyContents()
{
if (bytePayload != null) return bytePayload;
String body = (payload != null) ? payload : bodyParams.asFormUrlEncodedString();
_log.debug("getByteBodyContents : "+body);
try
{
return body.getBytes(getCharset());
}
catch(UnsupportedEncodingException uee)
{
throw new OAuthException("Unsupported Charset: "+getCharset(), uee);
}
}
/**
* Returns the HTTP Verb
*
* @return the verb
*/
public HttpVerb getVerb()
{
return verb;
}
public void setRealm(String realm) {
this.realm = realm;
}
public String getRealm() {
return realm;
}
/**
* Returns the connection headers as a {@link Map}
*
* @return map of headers
*/
public Map<String, String> getHeaders()
{
return headers;
}
/**
* Returns the connection charset. Defaults to {@link Charset} defaultCharset if not set
*
* @return charset
*/
public String getCharset()
{
return charset == null ? Charset.defaultCharset().name() : charset;
}
/**
* Sets the connect timeout for the underlying {@link HttpURLConnection}
*
* @param duration duration of the timeout
*
* @param unit unit of time (milliseconds, seconds, etc)
*/
public void setConnectTimeout(int duration, TimeUnit unit)
{
this.connectTimeout = unit.toMillis(duration);
}
/**
* Sets the read timeout for the underlying {@link HttpURLConnection}
*
* @param duration duration of the timeout
*
* @param unit unit of time (milliseconds, seconds, etc)
*/
public void setReadTimeout(int duration, TimeUnit unit)
{
this.readTimeout = unit.toMillis(duration);
}
/**
* Set the charset of the body of the request
*
* @param charsetName name of the charset of the request
*/
public void setCharset(String charsetName)
{
this.charset = charsetName;
}
/**
* Sets whether the underlying Http Connection is persistent or not.
*
* @see http://download.oracle.com/javase/1.5.0/docs/guide/net/http-keepalive.html
* @param connectionKeepAlive
*/
@Deprecated
public void setConnectionKeepAlive(boolean connectionKeepAlive){
this.connectionKeepAlive = connectionKeepAlive;
}
/**
*
* @param connectionKeepAlive
* true or false
*/
public void setConnectionKeepAlive(String connectionKeepAlive){
System.setProperty("http.keepAlive", connectionKeepAlive);
}
/**
* Sets whether the underlying Http Connection follows redirects or not.
*
* Defaults to true (follow redirects)
*
* @see http://docs.oracle.com/javase/6/docs/api/java/net/HttpURLConnection.html#setInstanceFollowRedirects(boolean)
* @param followRedirects
*/
public void setFollowRedirects(boolean followRedirects)
{
this.followRedirects = followRedirects;
}
/*
* We need this in order to stub the connection object for test cases
*/
void setConnection(HttpURLConnection connection)
{
this.connection = connection;
}
@Override
public String toString()
{
return String.format("@Request(%s %s)", getVerb(), getUrl());
}
}

View File

@ -1,23 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.http;
public abstract class RequestTuner
{
public abstract void tune(Request request);
}

View File

@ -1,149 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.http;
import java.io.*;
import java.net.*;
import java.util.*;
import org.maxkey.client.oauth.exceptions.*;
import org.maxkey.client.utils.StreamUtils;
/**
* Represents an HTTP Response.
*
* @author Pablo Fernandez
*/
public class Response {
private int code;
private String message;
private String body;
private InputStream stream;
private Map<String, String> headers;
public Response(int code, String message, Map<String, String> headers, String body, InputStream stream) {
this.code = code;
this.headers = headers;
this.body = body;
this.message = message;
this.stream = stream;
}
Response(HttpURLConnection connection) throws IOException {
try {
connection.connect();
code = connection.getResponseCode();
message = connection.getResponseMessage();
headers = parseHeaders(connection);
stream = isSuccessful() ? connection.getInputStream() : connection.getErrorStream();
} catch (UnknownHostException e) {
throw new OAuthException("The IP address of a host could not be determined.", e);
}
}
private String parseBodyContents() throws IOException {
if ("gzip".equals(getHeader("Content-Encoding"))) {
body = StreamUtils.getGzipStreamContents(getStream());
} else {
body = StreamUtils.getStreamContents(getStream());
}
return body;
}
private Map<String, String> parseHeaders(HttpURLConnection conn) {
final Map<String, String> headers = new HashMap<>();
for (String key : conn.getHeaderFields().keySet()) {
headers.put(key, conn.getHeaderFields().get(key).get(0));
}
return headers;
}
public final boolean isSuccessful() {
return getCode() >= 200 && getCode() < 400;
}
public String getBody() {
try {
return body == null ? parseBodyContents() : body;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
/**
* Obtains the meaningful stream of the HttpUrlConnection, either inputStream or errorInputStream, depending on the
* status code
*
* @return input stream / error stream
*/
public InputStream getStream() {
return stream;
}
/**
* Obtains the HTTP status code
*
* @return the status code
*/
public final int getCode() {
return code;
}
/**
* Obtains the HTTP status message. Returns <code>null</code> if the message can not be discerned from the response
* (not valid HTTP)
*
* @return the status message
*/
public String getMessage() {
return message;
}
/**
* Obtains a {@link Map} containing the HTTP Response Headers
*
* @return headers
*/
public Map<String, String> getHeaders() {
return headers;
}
/**
* Obtains a single HTTP Header value, or null if undefined
*
* @param name the header name.
*
* @return header value or null.
*/
public String getHeader(String name) {
return headers.get(name);
}
@Override
public String toString() {
return "Response{" +
"code=" + code +
", message='" + message + '\'' +
", body='" + body + '\'' +
", headers=" + headers +
'}';
}
}

View File

@ -1,142 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.http;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.maxkey.client.http.AuthorizationHeader;
import org.maxkey.client.http.HttpVerb;
import org.maxkey.client.http.Response;
import org.maxkey.client.utils.Preconditions;
public class RestClient {
private static Log _log = LogFactory.getLog(RestClient. class );
//action method
private HttpVerb method = HttpVerb.GET;
//request Service
private Request request;
public RestClient(String url) {
Preconditions.checkEmptyString(url, "Invalid request url");
request = new Request(method, url);
}
/**
* 鏋勯<EFBFBD>犳柟娉<EFBFBD>
*
* @param method 璇锋眰鏂规硶
* @param url 璇锋眰url
*/
public RestClient(String url,HttpVerb method) {
Preconditions.checkEmptyString(url, "Invalid request url");
if(method != null) {
this.method = method;
}
request = new Request(method, url);
}
/**
* 娣诲姞璇锋眰鍙傛暟
*
* @param name 鍙傛暟鍚<EFBFBD>
* @param value 鍙傛暟鍊<EFBFBD>
*/
public void addParameter(String name,String value) {
Preconditions.checkEmptyString(name, "parameter name is null");
Preconditions.checkNotNull(request, "RestClient is null");
if(HttpVerb.GET == method) {
request.addQuerystringParameter(name, value);
} else if(HttpVerb.POST == method) {
request.addBodyParameter(name, value);
}
}
/**
* 娣诲姞璇锋眰Header
*
* @param name 鍙傛暟鍚<EFBFBD>
* @param value 鍙傛暟鍊<EFBFBD>
*/
public void addHeader(String name,String value) {
Preconditions.checkEmptyString(name, "parameter name is null");
Preconditions.checkNotNull(request, "OAuthRequest is null");
request.addHeader(name, value);
}
/**
* 鍙戦<EFBFBD>姹傦紝鑾峰彇杩斿洖鐨勬暟鎹<EFBFBD>
*
* @return Response 鏈嶅姟绔繑鍥炵殑鏁版嵁
*/
public Response execute() {
return request.send();
}
public void addBasicAuthorization(String username,String password) {
Preconditions.checkEmptyString(username, "parameter username is null");
Preconditions.checkEmptyString(password, "parameter password is null");
Preconditions.checkNotNull(request, "RestClient is null");
request.addHeader(AuthorizationHeader.AUTHORIZATION_HEADERNAME, AuthorizationHeader.createBasic(username, password));
}
public void addBearerAuthorization(String bearer) {
Preconditions.checkEmptyString(bearer, "parameter bearer is null");
Preconditions.checkNotNull(request, "RestClient is null");
request.addHeader(AuthorizationHeader.AUTHORIZATION_HEADERNAME, AuthorizationHeader.createBearer(bearer));
}
/**
* set REST Content
*
* @param content
*/
public void addRestContent(String content)
{
this.request.addRestContent(content) ;
}
/**
* set REST Content
*
* @param content
*/
public void addRestObject(Object content)
{
this.request.addRestObject(content);
}
/**
* set REST Content
*
* @param content
*/
public void addRestContent(byte[] content)
{
this.request.addRestContent(content);
}
}

View File

@ -1,24 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.http;
public enum SignatureType
{
Header,
QueryString
}

View File

@ -1,25 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
/**
* @author Administrator
*
*/
package org.maxkey.client.http;

View File

@ -1,79 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.ltpa;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.maxkey.client.crypto.Base64Utils;
import org.maxkey.client.crypto.ReciprocalUtils;
import org.maxkey.client.utils.JsonUtils;
public class LtpaUtils {
public static String readLtpa(HttpServletRequest request,String ltpaDomain,String ltpaName){
Cookie[] cookies = request.getCookies();
if(cookies!=null) {
for (int i = 0; i < cookies.length; i++) {
if(cookies[i].getName().equalsIgnoreCase(ltpaName)){
return cookies[i].getValue();
}
}
}
return null;
}
public static String decode(String ltpaString,String algorithmKey, String algorithm){
String token=ReciprocalUtils.decoder(Base64Utils.base64UrlDecode(ltpaString), algorithmKey, algorithm);
try {
token=new String(Hex.decodeHex(token.toCharArray()),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (DecoderException e) {
e.printStackTrace();
}
return token;
}
@SuppressWarnings("unchecked")
public static HashMap<String,Object> parseLtpaJson(String token){
HashMap<String,Object> tokenMap=new HashMap<String,Object>();
tokenMap=JsonUtils.gson2Object(token, tokenMap.getClass());
return tokenMap;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String token="ICHQ%2F1Tdzw214UNw9fKEjRNFbvOlGdXyxVjF9I7kwEo%3D";
String tokenString=LtpaUtils.decode(token, "x8zPbCya", ReciprocalUtils.Algorithm.DES);
System.out.println(tokenString);
}
}

View File

@ -1,216 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.maxkey.client.http.AuthorizationHeader;
import org.maxkey.client.http.HttpVerb;
import org.maxkey.client.http.Response;
import org.maxkey.client.oauth.domain.OIDCUserInfo;
import org.maxkey.client.oauth.domain.UserInfo;
import org.maxkey.client.oauth.model.OAuthConstants;
import org.maxkey.client.oauth.model.OAuthRequest;
import org.maxkey.client.oauth.model.Token;
import org.maxkey.client.utils.JsonUtils;
import org.maxkey.client.utils.Preconditions;
public class OAuthClient {
private static Log log = LogFactory.getLog(OAuthClient. class );
private static final String DEFAULT_WEB_URL = "http://sso.maxkey.org/maxkey";
public static String OAUTH_V20_USERINFO_URI=DEFAULT_WEB_URL+"/api/oauth/v20/me";
public static String OAUTH_V10A_USERINFO_URI=DEFAULT_WEB_URL+"/api/oauth/v10a/me";
public static String OPENID_CONNECT_V10A_USERINFO_URI=DEFAULT_WEB_URL+"/api/connect/v10/userinfo";
//action method
private HttpVerb method = HttpVerb.GET;
//request Service
private OAuthRequest request;
public OAuthClient(String url) {
Preconditions.checkEmptyString(url, "Invalid request url");
request = new OAuthRequest(method, url);
}
public OAuthClient(String url,String accessToken) {
Preconditions.checkEmptyString(url, "Invalid request url");
request = new OAuthRequest(method, url);
addParameter(OAuthConstants.ACCESS_TOKEN, accessToken);
}
/**
* 鏋勯<EFBFBD>犳柟娉<EFBFBD>
*
* @param method 璇锋眰鏂规硶
* @param url 璇锋眰url
*/
public OAuthClient(String url,HttpVerb method) {
Preconditions.checkEmptyString(url, "Invalid request url");
if(method != null) {
this.method = method;
}
request = new OAuthRequest(method, url);
}
/**
* 灏哸ccess token闄勫姞鍒拌姹傚弬鏁颁腑
*
* @param accessToken
*/
public void signAccessToken(Token accessToken) {
Preconditions.checkNotNull(request, "OAuthRequest is null");
addParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getToken());
}
/**
* 娣诲姞璇锋眰鍙傛暟
*
* @param name 鍙傛暟鍚<EFBFBD>
* @param value 鍙傛暟鍊<EFBFBD>
*/
public void addParameter(String name,String value) {
Preconditions.checkEmptyString(name, "parameter name is null");
Preconditions.checkNotNull(request, "OAuthRequest is null");
if(HttpVerb.GET == method) {
request.addQuerystringParameter(name, value);
} else if(HttpVerb.POST == method) {
request.addBodyParameter(name, value);
}
}
/**
* 娣诲姞璇锋眰Header
*
* @param name 鍙傛暟鍚<EFBFBD>
* @param value 鍙傛暟鍊<EFBFBD>
*/
public void addHeader(String name,String value) {
Preconditions.checkEmptyString(name, "parameter name is null");
Preconditions.checkNotNull(request, "OAuthRequest is null");
request.addHeader(name, value);
}
/**
* 鍙戦<EFBFBD>姹傦紝鑾峰彇杩斿洖鐨勬暟鎹<EFBFBD>
*
* @return Response 鏈嶅姟绔繑鍥炵殑鏁版嵁
*/
public Response execute() {
return request.send();
}
public Token requestAccessToken(){
String tokenString=execute().getBody();
Token token =JsonUtils.gson2Object(tokenString, Token.class);
log.debug("Request token : "+token);
return token;
}
public void addBasicAuthorization(String username,String password) {
Preconditions.checkEmptyString(username, "parameter username is null");
Preconditions.checkEmptyString(password, "parameter password is null");
Preconditions.checkNotNull(request, "OAuthRequest is null");
request.addHeader(AuthorizationHeader.AUTHORIZATION_HEADERNAME, AuthorizationHeader.createBasic(username, password));
}
public void addBearerAuthorization(String bearer) {
Preconditions.checkEmptyString(bearer, "parameter bearer is null");
Preconditions.checkNotNull(request, "OAuthRequest is null");
request.addHeader(AuthorizationHeader.AUTHORIZATION_HEADERNAME, AuthorizationHeader.createBearer(bearer));
}
public UserInfo getUserInfo(String accessToken){
addParameter(OAuthConstants.ACCESS_TOKEN, accessToken);
Response response = execute();
log.debug("Request UserInfo : "+response.getBody());
UserInfo userInfo = (UserInfo) JsonUtils.gson2Object(response.getBody(), UserInfo.class);
userInfo.setResponseString(response.getBody());
if(userInfo.getError() != null && !"".equals(userInfo.getError().trim())) {
}
log.debug("UserInfo : "+userInfo);
return userInfo;
}
public OIDCUserInfo getOIDCUserInfo(String accessToken){
addHeader("Authorization", accessToken);
Response response = execute();
log.debug("Request OIDCUserInfo : "+response.getBody());
OIDCUserInfo userInfo = (OIDCUserInfo) JsonUtils.gson2Object(response.getBody(), OIDCUserInfo.class);
userInfo.setResponseString(response.getBody());
if(userInfo.getError() != null && !"".equals(userInfo.getError().trim())) {
}
log.debug("UserInfo : "+userInfo);
return userInfo;
}
/**
* set REST Content
*
* @param content
*/
public void addRestContent(String content)
{
this.request.addRestContent(content) ;
}
/**
* set REST Content
*
* @param content
*/
public void addRestObject(Object content)
{
this.request.addRestObject(content);
}
/**
* set REST Content
*
* @param content
*/
public void addRestContent(byte[] content)
{
this.request.addRestContent(content);
}
}

View File

@ -1,188 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.builder;
import java.io.*;
import org.maxkey.client.http.SignatureType;
import org.maxkey.client.oauth.builder.api.*;
import org.maxkey.client.oauth.exceptions.*;
import org.maxkey.client.oauth.model.*;
import org.maxkey.client.oauth.oauth.*;
import org.maxkey.client.utils.Preconditions;
/**
* Implementation of the Builder pattern, with a fluent interface that creates a
* {@link OAuthService}
*
* @author Pablo Fernandez
*
*/
public class ServiceBuilder
{
private String apiKey;
private String apiSecret;
private String callback;
private Api api;
private String scope;
private SignatureType signatureType;
private OutputStream debugStream;
/**
* Default constructor
*/
public ServiceBuilder()
{
this.callback = OAuthConstants.OUT_OF_BAND;
this.signatureType = SignatureType.Header;
this.debugStream = null;
}
/**
* Configures the {@link Api}
*
* @param apiClass the class of one of the existent {@link Api}s on org.scribe.api package
* @return the {@link ServiceBuilder} instance for method chaining
*/
public ServiceBuilder provider(Class<? extends Api> apiClass)
{
this.api = createApi(apiClass);
return this;
}
private Api createApi(Class<? extends Api> apiClass)
{
Preconditions.checkNotNull(apiClass, "Api class cannot be null");
Api api;
try
{
api = apiClass.newInstance();
}
catch(Exception e)
{
throw new OAuthException("Error while creating the Api object", e);
}
return api;
}
/**
* Configures the {@link Api}
*
* Overloaded version. Let's you use an instance instead of a class.
*
* @param api instance of {@link Api}s
* @return the {@link ServiceBuilder} instance for method chaining
*/
public ServiceBuilder provider(Api api)
{
Preconditions.checkNotNull(api, "Api cannot be null");
this.api = api;
return this;
}
/**
* Adds an OAuth callback url
*
* @param callback callback url. Must be a valid url or 'oob' for out of band OAuth
* @return the {@link ServiceBuilder} instance for method chaining
*/
public ServiceBuilder callback(String callback)
{
Preconditions.checkNotNull(callback, "Callback can't be null");
this.callback = callback;
return this;
}
/**
* Configures the api key
*
* @param apiKey The api key for your application
* @return the {@link ServiceBuilder} instance for method chaining
*/
public ServiceBuilder apiKey(String apiKey)
{
Preconditions.checkEmptyString(apiKey, "Invalid Api key");
this.apiKey = apiKey;
return this;
}
/**
* Configures the api secret
*
* @param apiSecret The api secret for your application
* @return the {@link ServiceBuilder} instance for method chaining
*/
public ServiceBuilder apiSecret(String apiSecret)
{
Preconditions.checkEmptyString(apiSecret, "Invalid Api secret");
this.apiSecret = apiSecret;
return this;
}
/**
* Configures the OAuth scope. This is only necessary in some APIs (like Google's).
*
* @param scope The OAuth scope
* @return the {@link ServiceBuilder} instance for method chaining
*/
public ServiceBuilder scope(String scope)
{
Preconditions.checkEmptyString(scope, "Invalid OAuth scope");
this.scope = scope;
return this;
}
/**
* Configures the signature type, choose between header, querystring, etc. Defaults to Header
*
* @param scope The OAuth scope
* @return the {@link ServiceBuilder} instance for method chaining
*/
public ServiceBuilder signatureType(SignatureType type)
{
Preconditions.checkNotNull(type, "Signature type can't be null");
this.signatureType = type;
return this;
}
public ServiceBuilder debugStream(OutputStream stream)
{
Preconditions.checkNotNull(stream, "debug stream can't be null");
this.debugStream = stream;
return this;
}
public ServiceBuilder debug()
{
this.debugStream(System.out);
return this;
}
/**
* Returns the fully configured {@link OAuthService}
*
* @return fully configured {@link OAuthService}
*/
public OAuthService build()
{
Preconditions.checkNotNull(api, "You must specify a valid api through the provider() method");
Preconditions.checkEmptyString(apiKey, "You must provide an api key");
Preconditions.checkEmptyString(apiSecret, "You must provide an api secret");
return api.createService(new OAuthConfig(apiKey, apiSecret, callback, signatureType, scope, debugStream));
}
}

View File

@ -1,43 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.builder.api;
import org.maxkey.client.oauth.model.*;
import org.maxkey.client.oauth.oauth.*;
/**
* Contains all the configuration needed to instantiate a valid {@link OAuthService}
*
* @author Pablo Fernandez
*
*/
public interface Api
{
/**
* Creates an {@link OAuthService}
*
* @param apiKey your application api key
* @param apiSecret your application api secret
* @param callback the callback url (or 'oob' for out of band OAuth)
* @param scope the OAuth scope
*
* @return fully configured {@link OAuthService}
*/
OAuthService createService(OAuthConfig config);
}

View File

@ -1,91 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.builder.api;
import org.maxkey.client.http.HttpVerb;
import org.maxkey.client.oauth.extractors.*;
import org.maxkey.client.oauth.model.*;
import org.maxkey.client.oauth.oauth.*;
/**
* Default implementation of the OAuth protocol, version 2.0 (draft 11)
*
* This class is meant to be extended by concrete implementations of the API,
* providing the endpoints and endpoint-http-verbs.
*
* If your Api adheres to the 2.0 (draft 11) protocol correctly, you just need to extend
* this class and define the getters for your endpoints.
*
* If your Api does something a bit different, you can override the different
* extractors or services, in order to fine-tune the process. Please read the
* javadocs of the interfaces to get an idea of what to do.
*
* @author Diego Silveira
*
*/
public abstract class DefaultApi20 implements Api
{
/**
* Returns the access token extractor.
*
* @return access token extractor
*/
public AccessTokenExtractor getAccessTokenExtractor()
{
return new TokenExtractor20Impl();
}
/**
* Returns the verb for the access token endpoint (defaults to GET)
*
* @return access token endpoint verb
*/
public HttpVerb getAccessTokenVerb()
{
return HttpVerb.GET;
}
/**
* Returns the URL that receives the access token requests.
*
* @return access token URL
*/
public abstract String getAccessTokenEndpoint();
public abstract String getGrantType() ;
/**
* Returns the URL where you should redirect your users to authenticate
* your application.
*
* @param config OAuth 2.0 configuration param object
* @return the URL where you should redirect your users
*/
public abstract String getAuthorizationUrl(OAuthConfig config);
/**
* {@inheritDoc}
*/
public OAuthService createService(OAuthConfig config)
{
return new OAuth20ServiceImpl(this, config);
}
}

View File

@ -1,83 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.builder.api;
import org.maxkey.client.http.HttpVerb;
import org.maxkey.client.oauth.extractors.AccessTokenExtractor;
import org.maxkey.client.oauth.extractors.GsonJsonTokenExtractor;
import org.maxkey.client.oauth.model.OAuthConfig;
import org.maxkey.client.utils.HttpEncoder;
import org.maxkey.client.utils.Preconditions;
public class MaxkeyApi20 extends DefaultApi20 {
//approval_prompt:force or auto
private static final String DEFAULT_WEB_URL = "https://sso.maxkey.top/maxkey";
private static final String AUTHORIZATION_URL = "%s/oauth/v20/authorize?client_id=%s&response_type=code&redirect_uri=%s&approval_prompt=auto";
private static final String SCOPED_AUTHORIZE_URL = String.format("%s&scope=%%s", AUTHORIZATION_URL);
public MaxkeyApi20() {
}
@Override
public String getAccessTokenEndpoint() {
return getWebUrl() + "/oauth/v20/token?grant_type=authorization_code";
}
@Override
public String getAuthorizationUrl(OAuthConfig config) {
Preconditions.checkValidUrl(config.getCallback(), "Must provide a valid url as callback. Secure does not support OOB");
if(config.hasScope()) {
return String.format(SCOPED_AUTHORIZE_URL, getWebUrl(),config.getApiKey(), HttpEncoder.encode(config.getCallback()), HttpEncoder.encode(config.getScope()));
} else {
return String.format(AUTHORIZATION_URL, getWebUrl(),config.getApiKey(), HttpEncoder.encode(config.getCallback()));
}
}
@Override
public HttpVerb getAccessTokenVerb() {
return HttpVerb.POST;
}
@Override
public AccessTokenExtractor getAccessTokenExtractor() {
return new GsonJsonTokenExtractor();
}
private String getWebUrl() {
String webUrl = null;
if(webUrl == null || "".equals(webUrl)) {
webUrl = DEFAULT_WEB_URL;
}
return webUrl;
}
@Override
public String getGrantType() {
// TODO Auto-generated method stub
return "authorization_code";
}
}

View File

@ -1,101 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.builder.api;
import org.maxkey.client.http.HttpVerb;
import org.maxkey.client.oauth.extractors.AccessTokenExtractor;
import org.maxkey.client.oauth.extractors.GsonJsonTokenExtractor;
import org.maxkey.client.oauth.model.OAuthConfig;
/**
* OAuth 2.0 api.
*/
public class MaxkeyPasswordApi20 extends DefaultApi20 {
private String accessTokenUrl;
private String grantType = "password";
private String scope = "&scope=%s";
private String accessTokenMethod = "POST";
private static final String AUTHORIZE_PARAM = "&client_id=%s&client_secret=%s&username=%s&password=%s";
public MaxkeyPasswordApi20(String accessTokenUrl) {
super();
this.accessTokenUrl = accessTokenUrl;
}
@Override
public HttpVerb getAccessTokenVerb() {
if (accessTokenMethod != null
&& accessTokenMethod.toUpperCase().equals("POST")) {
return HttpVerb.POST;
} else {
return HttpVerb.GET;
}
}
@Override
public AccessTokenExtractor getAccessTokenExtractor() {
return new GsonJsonTokenExtractor();
}
@Override
public String getAccessTokenEndpoint() {
if (accessTokenUrl.indexOf("?") > 0) {
return accessTokenUrl + "&grant_type=" + grantType+ AUTHORIZE_PARAM;
} else {
return accessTokenUrl + "?grant_type=" + grantType+ AUTHORIZE_PARAM;
}
}
public String getAuthorizationUrl(OAuthConfig config,String username,String password) {
return String.format(getAccessTokenEndpoint(),
config.getApiKey(),
config.getApiSecret(),
username,
password);
}
public String getAccessTokenUrl() {
return accessTokenUrl;
}
public void setAccessTokenUrl(String accessTokenUrl) {
this.accessTokenUrl = accessTokenUrl;
}
@Override
public String toString() {
return "OAuthApi20 [accessTokenUrl=" + accessTokenUrl + ", grantType="
+ grantType + ", scope=" + scope + "]";
}
@Override
public String getAuthorizationUrl(OAuthConfig config) {
return "";
}
@Override
public String getGrantType() {
// TODO Auto-generated method stub
return "authorization_code";
}
}

View File

@ -1,151 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.builder.api;
import org.maxkey.client.http.HttpVerb;
import org.maxkey.client.oauth.extractors.*;
import org.maxkey.client.oauth.model.*;
import org.maxkey.client.utils.HttpEncoder;
/**
* OAuth 2.0 api.
*/
public class OAuthApi20 extends DefaultApi20
{
//private static final String AUTHORIZE_URL = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code";
//private static final String SCOPED_AUTHORIZE_URL = AUTHORIZE_URL + "&scope=%s";
private String authorizeUrl;
private String accessTokenUrl;
private String grantType="authorization_code";
private String scope="&scope=%s";
private String accessTokenMethod="POST";
public OAuthApi20(String authorizeUrl, String accessTokenUrl) {
super();
this.authorizeUrl = authorizeUrl;
this.accessTokenUrl = accessTokenUrl;
}
public OAuthApi20(String authorizeUrl, String accessTokenUrl,String accessTokenMethod) {
super();
this.authorizeUrl = authorizeUrl;
this.accessTokenUrl = accessTokenUrl;
this.accessTokenMethod=accessTokenMethod;
}
public OAuthApi20(String authorizeUrl, String accessTokenUrl,String grantType,String accessTokenMethod) {
super();
this.authorizeUrl = authorizeUrl;
this.accessTokenUrl = accessTokenUrl;
this.grantType = grantType;
this.accessTokenMethod=accessTokenMethod;
}
public OAuthApi20(String authorizeUrl, String accessTokenUrl,String grantType, String accessTokenMethod,String scope) {
super();
this.authorizeUrl = authorizeUrl;
this.accessTokenUrl = accessTokenUrl;
this.grantType = grantType;
this.accessTokenMethod=accessTokenMethod;
this.scope = scope;
}
@Override
public HttpVerb getAccessTokenVerb(){
if(accessTokenMethod!= null &&accessTokenMethod.toUpperCase().equals("POST")){
return HttpVerb.POST;
}else{
return HttpVerb.GET;
}
}
@Override
public AccessTokenExtractor getAccessTokenExtractor(){
if(accessTokenUrl.indexOf("qq")>-1){
return new QQTokenExtractor();
}
return new GsonJsonTokenExtractor();
}
@Override
public String getAccessTokenEndpoint(){
if(accessTokenUrl.indexOf("?")>0){
return accessTokenUrl+"&grant_type="+grantType;
}else{
return accessTokenUrl+"?grant_type="+grantType;
}
}
@Override
public String getAuthorizationUrl(OAuthConfig config){
// Append scope if present
//dingtalk
if(authorizeUrl.indexOf("oapi.dingtalk.com")>-1) {
if (config.hasScope()){
return String.format(authorizeUrl+scope, config.getApiKey(), config.getCallback(), HttpEncoder.encode(config.getScope()));
}
else{
return String.format(authorizeUrl, config.getApiKey(), config.getCallback());
}
}else {
if (config.hasScope()){
return String.format(authorizeUrl+scope, config.getApiKey(), HttpEncoder.encode(config.getCallback()), HttpEncoder.encode(config.getScope()));
}
else{
return String.format(authorizeUrl, config.getApiKey(), HttpEncoder.encode(config.getCallback()));
}
}
}
public String getAuthorizeUrl() {
return authorizeUrl;
}
public void setAuthorizeUrl(String authorizeUrl) {
this.authorizeUrl = authorizeUrl;
}
public String getAccessTokenUrl() {
return accessTokenUrl;
}
public void setAccessTokenUrl(String accessTokenUrl) {
this.accessTokenUrl = accessTokenUrl;
}
public String getGrantType() {
return grantType;
}
public void setGrantType(String grantType) {
this.grantType = grantType;
}
@Override
public String toString() {
return "OAuthApi20 [authorizeUrl=" + authorizeUrl + ", accessTokenUrl="
+ accessTokenUrl + ", grantType=" + grantType + ", scope="
+ scope + "]";
}
}

View File

@ -1,340 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.UUID;
import org.apache.log4j.Logger;
/**
* BaseDomain for connsec's domain
*
* @author Crystal.sea
*
*/
public class BaseDomain implements Serializable{
/**
*
*/
private static final long serialVersionUID = -6290127045507211154L;
protected final static Logger logger = Logger.getLogger(BaseDomain.class);
/**
* Domain id
*/
protected String id;
protected String tid;
protected String tname;
/**
* description
*/
protected String description;
protected int status;
protected int sortOrder;
protected String createdBy;
protected Date createdDate;
protected String modifiedBy;
protected Date modifiedDate;
protected String startDate;
protected String endDate;
protected String error;
protected String error_description;
protected String responseString;
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getError_description() {
return error_description;
}
public void setError_description(String error_description) {
this.error_description = error_description;
}
public BaseDomain() {
}
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the status
*/
public int getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(int status) {
this.status = status;
}
/**
* @return the tid
*/
public String getTid() {
return tid;
}
/**
* @param tid the tid to set
*/
public void setTid(String tid) {
this.tid = tid;
}
/**
* @return the tname
*/
public String getTname() {
return tname;
}
/**
* @param tname the tname to set
*/
public void setTname(String tname) {
this.tname = tname;
}
/**
* @return the sortOrder
*/
public int getSortOrder() {
return sortOrder;
}
/**
* @param sortOrder the sortOrder to set
*/
public void setSortOrder(int sortOrder) {
this.sortOrder = sortOrder;
}
/**
* @return the createdBy
*/
public String getCreatedBy() {
return createdBy;
}
/**
* @param createdBy the createdBy to set
*/
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
/**
* @return the createdDate
*/
public Date getCreatedDate() {
return createdDate;
}
/**
* @param createdDate the createdDate to set
*/
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
/**
* @return the modifiedBy
*/
public String getModifiedBy() {
return modifiedBy;
}
/**
* @param modifiedBy the modifiedBy to set
*/
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
/**
* @return the modifiedDate
*/
public Date getModifiedDate() {
return modifiedDate;
}
/**
* @param modifiedDate the modifiedDate to set
*/
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the startDate
*/
public String getStartDate() {
return startDate;
}
/**
* @param startDate the startDate to set
*/
public void setStartDate(String startDate) {
this.startDate = startDate;
}
/**
* @return the endDate
*/
public String getEndDate() {
return endDate;
}
/**
* @param endDate the endDate to set
*/
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public void genId() {
this.id=UUID.randomUUID().toString().toLowerCase();
}
public String getResponseString() {
return responseString;
}
public void setResponseString(String responseString) {
this.responseString = responseString;
}
@Override
public String toString() {
return "BaseDomain [id=" + id + ", tid=" + tid + ", tname=" + tname
+ ", status=" + status + ", sortOrder=" + sortOrder
+ ", createdBy=" + createdBy + ", createdDate=" + createdDate
+ ", modifiedBy=" + modifiedBy + ", modifiedDate="
+ modifiedDate + ", description=" + description
+ ", startDate=" + startDate + ", endDate=" + endDate + "]";
}
}

View File

@ -1,40 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.domain;
public class BaseEntity {
private String error;
private String error_description;
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getError_description() {
return error_description;
}
public void setError_description(String error_description) {
this.error_description = error_description;
}
}

View File

@ -1,71 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.domain;
public class OIDCAddress {
public String country;
public String region;
public String locality;
public String street_address;
public String formatted;
public String postal_code;
/**
*
*/
public OIDCAddress() {
// TODO Auto-generated constructor stub
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getLocality() {
return locality;
}
public void setLocality(String locality) {
this.locality = locality;
}
public String getStreet_address() {
return street_address;
}
public void setStreet_address(String street_address) {
this.street_address = street_address;
}
public String getFormatted() {
return formatted;
}
public void setFormatted(String formatted) {
this.formatted = formatted;
}
public String getPostal_code() {
return postal_code;
}
public void setPostal_code(String postal_code) {
this.postal_code = postal_code;
}
}

View File

@ -1,251 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
package org.maxkey.client.oauth.domain;
/**
* @author Administrator
*
*/
public class OIDCUserInfo {
private String sub;
private String name;
private String preferred_username;
private String given_name;
private String family_name;
private String middle_name;
private String nickname;
private String profile;
private String picture;
private String website;
private String gender;
private String zoneinfo;
private String locale;
private String updated_time;
private String birthdate;
private String email;
private boolean email_verified;
private String phone_number;
private boolean phone_number_verified;
private OIDCAddress address;
protected String error;
protected String error_description;
protected String responseString;
/**
*
*/
public OIDCUserInfo() {
// TODO Auto-generated constructor stub
}
public String getSub() {
return sub;
}
public void setSub(String sub) {
this.sub = sub;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPreferred_username() {
return preferred_username;
}
public void setPreferred_username(String preferred_username) {
this.preferred_username = preferred_username;
}
public String getGiven_name() {
return given_name;
}
public void setGiven_name(String given_name) {
this.given_name = given_name;
}
public String getFamily_name() {
return family_name;
}
public void setFamily_name(String family_name) {
this.family_name = family_name;
}
public String getMiddle_name() {
return middle_name;
}
public void setMiddle_name(String middle_name) {
this.middle_name = middle_name;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getZoneinfo() {
return zoneinfo;
}
public void setZoneinfo(String zoneinfo) {
this.zoneinfo = zoneinfo;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public String getUpdated_time() {
return updated_time;
}
public void setUpdated_time(String updated_time) {
this.updated_time = updated_time;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEmail_verified() {
return email_verified;
}
public void setEmail_verified(boolean email_verified) {
this.email_verified = email_verified;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public boolean isPhone_number_verified() {
return phone_number_verified;
}
public void setPhone_number_verified(boolean phone_number_verified) {
this.phone_number_verified = phone_number_verified;
}
public OIDCAddress getAddress() {
return address;
}
public void setAddress(OIDCAddress address) {
this.address = address;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getError_description() {
return error_description;
}
public void setError_description(String error_description) {
this.error_description = error_description;
}
public String getResponseString() {
return responseString;
}
public void setResponseString(String responseString) {
this.responseString = responseString;
}
}

View File

@ -1,792 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.domain;
import java.util.Arrays;
/**
* @author Crystal.Sea
*
*/
public class UserInfo extends BaseDomain {
/**
*
*/
private static final long serialVersionUID = 6402443942083382236L;
//
protected String username;
/**
* "Employee", "Supplier","Dealer","Contractor",Partner,Customer "Intern",
* "Temp", "External", and "Unknown"
*/
protected String userType;
protected String windowsAccount;
// for user name
protected String displayName;
protected String nickName;
protected String nameZHSpell;
protected String nameZHShortSpell;
protected String givenName;
protected String middleName;
protected String familyName;
protected String honorificPrefix;
protected String honorificSuffix;
protected String formattedName;
protected int married;
protected int gender;
protected String birthDate;
protected byte[] picture;
protected int idType;
protected String idCardNo;
protected String webSite;
protected String startWorkDate;
// for security
protected int authnType;
protected String email;
protected String mobile;
protected int mobileVerified;
protected String lastLoginTime;
protected String lastLoginIp;
protected String lastLogoffTime;
protected int passwordSetType;
protected Integer loginCount;
protected String locale;
protected String timeZone;
protected String preferredLanguage;
// for work
protected String workCountry;
protected String workRegion;// province;
protected String workLocality;// city;
protected String workStreetAddress;
protected String workAddressFormatted;
protected String workEmail;
protected String workPhoneNumber;
protected String workPostalCode;
protected String workFax;
// for home
protected String homeCountry;
protected String homeRegion;// province;
protected String homeLocality;// city;
protected String homeStreetAddress;
protected String homeAddressFormatted;
protected String homeEmail;
protected String homePhoneNumber;
protected String homePostalCode;
protected String homeFax;
// for company
protected String employeeNumber;
protected String costCenter;
protected String organization;
protected String division;
protected String departmentId;
protected String department;
protected String jobTitle;
protected String jobLevel;
protected String managerId;
protected String manager;
protected String assistantId;
protected String assistant;
protected String entryDate;
protected String quitDate;
// for social contact
/**
* QQ WeiXin SinaWeibo Gtalk YiXin IMessage Skype Yahoo MSN Aim ICQ Xmpp
*/
protected String ims;
/*
* for extended Attribute from userType extraAttribute for database
* extraAttributeName & extraAttributeValue for page submit
*/
protected String extraAttribute;
protected int online;
public static class ONLINE {
// 在线
public static int ONLINE = 0;
// 下线
public static int OFFLINE = 1;
}
public static class MARRIED {
// 未知
public static int UNKNOWN = 0;
// 单身
public static int SINGLE = 1;
// 结婚
public static int MARRIED = 2;
// 离异
public static int DIVORCE = 3;
// 丧偶
public static int WIDOWED = 4;
}
public static class GENDER {
// 未知
public static int UNKNOWN = 0;
// 女性
public static int FEMALE = 1;
// 男性
public static int MALE = 2;
}
public static class IDTYPE {
// 未知
public static int UNKNOWN = 0;
// 身份证
public static int IDCARD = 1;
// 护照
public static int PASSPORT = 2;
// 学生证
public static int STUDENTCARD = 3;
// 军人证
public static int MILITARYCARD = 4;
}
public static class AUTHNTYPE {
// 用户名密码
public static int NORMAL = 1;
// 手机
public static int MOBILE = 2;
// 短信
public static int SMS = 3;
// 邮箱
public static int EMAIL = 4;
public static int TIMEBASED_OPT = 5;
public static int COUNTERBASED_OPT = 6;
public static int HOTP_OPT = 7;
public static int RSA_OPT = 8;
// 证书
public static int CERTIFICATE = 9;
// usb证书
public static int USBKEY = 10;
}
/**
*
*/
public UserInfo() {
super();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public String getWindowsAccount() {
return windowsAccount;
}
public void setWindowsAccount(String windowsAccount) {
this.windowsAccount = windowsAccount;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getNameZHSpell() {
return nameZHSpell;
}
public void setNameZHSpell(String nameZHSpell) {
this.nameZHSpell = nameZHSpell;
}
public String getNameZHShortSpell() {
return nameZHShortSpell;
}
public void setNameZHShortSpell(String nameZHShortSpell) {
this.nameZHShortSpell = nameZHShortSpell;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getHonorificPrefix() {
return honorificPrefix;
}
public void setHonorificPrefix(String honorificPrefix) {
this.honorificPrefix = honorificPrefix;
}
public String getHonorificSuffix() {
return honorificSuffix;
}
public void setHonorificSuffix(String honorificSuffix) {
this.honorificSuffix = honorificSuffix;
}
public String getFormattedName() {
return formattedName;
}
public void setFormattedName(String formattedName) {
this.formattedName = formattedName;
}
public int getMarried() {
return married;
}
public void setMarried(int married) {
this.married = married;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
public byte[] getPicture() {
return picture;
}
public void setPicture(byte[] picture) {
this.picture = picture;
}
public int getIdType() {
return idType;
}
public void setIdType(int idType) {
this.idType = idType;
}
public String getIdCardNo() {
return idCardNo;
}
public void setIdCardNo(String idCardNo) {
this.idCardNo = idCardNo;
}
public String getWebSite() {
return webSite;
}
public void setWebSite(String webSite) {
this.webSite = webSite;
}
public String getStartWorkDate() {
return startWorkDate;
}
public void setStartWorkDate(String startWorkDate) {
this.startWorkDate = startWorkDate;
}
public int getAuthnType() {
return authnType;
}
public void setAuthnType(int authnType) {
this.authnType = authnType;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public int getMobileVerified() {
return mobileVerified;
}
public void setMobileVerified(int mobileVerified) {
this.mobileVerified = mobileVerified;
}
public String getLastLoginTime() {
return lastLoginTime;
}
public void setLastLoginTime(String lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
public String getLastLoginIp() {
return lastLoginIp;
}
public void setLastLoginIp(String lastLoginIp) {
this.lastLoginIp = lastLoginIp;
}
public String getLastLogoffTime() {
return lastLogoffTime;
}
public void setLastLogoffTime(String lastLogoffTime) {
this.lastLogoffTime = lastLogoffTime;
}
public int getPasswordSetType() {
return passwordSetType;
}
public void setPasswordSetType(int passwordSetType) {
this.passwordSetType = passwordSetType;
}
public Integer getLoginCount() {
return loginCount;
}
public void setLoginCount(Integer loginCount) {
this.loginCount = loginCount;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public String getTimeZone() {
return timeZone;
}
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}
public String getPreferredLanguage() {
return preferredLanguage;
}
public void setPreferredLanguage(String preferredLanguage) {
this.preferredLanguage = preferredLanguage;
}
public String getWorkCountry() {
return workCountry;
}
public void setWorkCountry(String workCountry) {
this.workCountry = workCountry;
}
public String getWorkRegion() {
return workRegion;
}
public void setWorkRegion(String workRegion) {
this.workRegion = workRegion;
}
public String getWorkLocality() {
return workLocality;
}
public void setWorkLocality(String workLocality) {
this.workLocality = workLocality;
}
public String getWorkStreetAddress() {
return workStreetAddress;
}
public void setWorkStreetAddress(String workStreetAddress) {
this.workStreetAddress = workStreetAddress;
}
public String getWorkAddressFormatted() {
return workAddressFormatted;
}
public void setWorkAddressFormatted(String workAddressFormatted) {
this.workAddressFormatted = workAddressFormatted;
}
public String getWorkEmail() {
return workEmail;
}
public void setWorkEmail(String workEmail) {
this.workEmail = workEmail;
}
public String getWorkPhoneNumber() {
return workPhoneNumber;
}
public void setWorkPhoneNumber(String workPhoneNumber) {
this.workPhoneNumber = workPhoneNumber;
}
public String getWorkPostalCode() {
return workPostalCode;
}
public void setWorkPostalCode(String workPostalCode) {
this.workPostalCode = workPostalCode;
}
public String getWorkFax() {
return workFax;
}
public void setWorkFax(String workFax) {
this.workFax = workFax;
}
public String getHomeCountry() {
return homeCountry;
}
public void setHomeCountry(String homeCountry) {
this.homeCountry = homeCountry;
}
public String getHomeRegion() {
return homeRegion;
}
public void setHomeRegion(String homeRegion) {
this.homeRegion = homeRegion;
}
public String getHomeLocality() {
return homeLocality;
}
public void setHomeLocality(String homeLocality) {
this.homeLocality = homeLocality;
}
public String getHomeStreetAddress() {
return homeStreetAddress;
}
public void setHomeStreetAddress(String homeStreetAddress) {
this.homeStreetAddress = homeStreetAddress;
}
public String getHomeAddressFormatted() {
return homeAddressFormatted;
}
public void setHomeAddressFormatted(String homeAddressFormatted) {
this.homeAddressFormatted = homeAddressFormatted;
}
public String getHomeEmail() {
return homeEmail;
}
public void setHomeEmail(String homeEmail) {
this.homeEmail = homeEmail;
}
public String getHomePhoneNumber() {
return homePhoneNumber;
}
public void setHomePhoneNumber(String homePhoneNumber) {
this.homePhoneNumber = homePhoneNumber;
}
public String getHomePostalCode() {
return homePostalCode;
}
public void setHomePostalCode(String homePostalCode) {
this.homePostalCode = homePostalCode;
}
public String getHomeFax() {
return homeFax;
}
public void setHomeFax(String homeFax) {
this.homeFax = homeFax;
}
public String getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(String employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getCostCenter() {
return costCenter;
}
public void setCostCenter(String costCenter) {
this.costCenter = costCenter;
}
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public String getDepartmentId() {
return departmentId;
}
public void setDepartmentId(String departmentId) {
this.departmentId = departmentId;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getJobLevel() {
return jobLevel;
}
public void setJobLevel(String jobLevel) {
this.jobLevel = jobLevel;
}
public String getManagerId() {
return managerId;
}
public void setManagerId(String managerId) {
this.managerId = managerId;
}
public String getManager() {
return manager;
}
public void setManager(String manager) {
this.manager = manager;
}
public String getAssistantId() {
return assistantId;
}
public void setAssistantId(String assistantId) {
this.assistantId = assistantId;
}
public String getAssistant() {
return assistant;
}
public void setAssistant(String assistant) {
this.assistant = assistant;
}
public String getEntryDate() {
return entryDate;
}
public void setEntryDate(String entryDate) {
this.entryDate = entryDate;
}
public String getQuitDate() {
return quitDate;
}
public void setQuitDate(String quitDate) {
this.quitDate = quitDate;
}
public String getIms() {
return ims;
}
public void setIms(String ims) {
this.ims = ims;
}
public String getExtraAttribute() {
return extraAttribute;
}
public void setExtraAttribute(String extraAttribute) {
this.extraAttribute = extraAttribute;
}
public int getOnline() {
return online;
}
public void setOnline(int online) {
this.online = online;
}
@Override
public String toString() {
return "UserInfo [username=" + username + ", userType=" + userType
+ ", windowsAccount=" + windowsAccount + ", displayName="
+ displayName + ", nickName=" + nickName + ", nameZHSpell="
+ nameZHSpell + ", nameZHShortSpell=" + nameZHShortSpell
+ ", givenName=" + givenName + ", middleName=" + middleName
+ ", familyName=" + familyName + ", honorificPrefix="
+ honorificPrefix + ", honorificSuffix=" + honorificSuffix
+ ", formattedName=" + formattedName + ", married=" + married
+ ", gender=" + gender + ", birthDate=" + birthDate
+ ", picture=" + Arrays.toString(picture) + ", idType="
+ idType + ", idCardNo=" + idCardNo + ", webSite=" + webSite
+ ", startWorkDate=" + startWorkDate + ", authnType="
+ authnType + ", email=" + email + ", mobile=" + mobile
+ ", mobileVerified=" + mobileVerified + ", lastLoginTime="
+ lastLoginTime + ", lastLoginIp=" + lastLoginIp
+ ", lastLogoffTime=" + lastLogoffTime + ", passwordSetType="
+ passwordSetType + ", loginCount=" + loginCount + ", locale="
+ locale + ", timeZone=" + timeZone + ", preferredLanguage="
+ preferredLanguage + ", workCountry=" + workCountry
+ ", workRegion=" + workRegion + ", workLocality="
+ workLocality + ", workStreetAddress=" + workStreetAddress
+ ", workAddressFormatted=" + workAddressFormatted
+ ", workEmail=" + workEmail + ", workPhoneNumber="
+ workPhoneNumber + ", workPostalCode=" + workPostalCode
+ ", workFax=" + workFax + ", homeCountry=" + homeCountry
+ ", homeRegion=" + homeRegion + ", homeLocality="
+ homeLocality + ", homeStreetAddress=" + homeStreetAddress
+ ", homeAddressFormatted=" + homeAddressFormatted
+ ", homeEmail=" + homeEmail + ", homePhoneNumber="
+ homePhoneNumber + ", homePostalCode=" + homePostalCode
+ ", homeFax=" + homeFax + ", employeeNumber=" + employeeNumber
+ ", costCenter=" + costCenter + ", organization="
+ organization + ", division=" + division + ", departmentId="
+ departmentId + ", department=" + department + ", jobTitle="
+ jobTitle + ", jobLevel=" + jobLevel + ", managerId="
+ managerId + ", manager=" + manager + ", assistantId="
+ assistantId + ", assistant=" + assistant + ", entryDate="
+ entryDate + ", quitDate=" + quitDate + ", ims=" + ims
+ ", extraAttribute=" + extraAttribute + ", online=" + online
+ "]";
}
}

View File

@ -1,31 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.exceptions;
/**
* @author: Pablo Fernandez
*/
public class OAuthConnectionException extends OAuthException
{
private static final String MSG = "There was a problem while creating a connection to the remote service.";
public OAuthConnectionException(Exception e)
{
super(MSG, e);
}
}

View File

@ -1,50 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.exceptions;
/**
* Default scribe exception.
* Represents a problem in the OAuth signing process
*
* @author Pablo Fernandez
*/
public class OAuthException extends RuntimeException
{
/**
* Default constructor
* @param message message explaining what went wrong
* @param e original exception
*/
public OAuthException(String message, Exception e)
{
super(message, e);
}
/**
* No-exception constructor. Used when there is no original exception
*
* @param message message explaining what went wrong
*/
public OAuthException(String message)
{
super(message, null);
}
private static final long serialVersionUID = 1L;
}

View File

@ -1,43 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.exceptions;
import org.maxkey.client.oauth.model.*;
/**
* Specialized exception that represents a missing OAuth parameter.
*
* @author Pablo Fernandez
*/
public class OAuthParametersMissingException extends OAuthException
{
private static final long serialVersionUID = 1745308760111976671L;
private static final String MSG = "Could not find oauth parameters in request: %s. "
+ "OAuth parameters must be specified with the addOAuthParameter() method";
/**
* Default constructor.
*
* @param request OAuthRequest that caused the error
*/
public OAuthParametersMissingException(OAuthRequest request)
{
super(String.format(MSG, request));
}
}

View File

@ -1,41 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.exceptions;
/**
* Specialized exception that represents a problem in the signature
*
* @author Pablo Fernandez
*/
public class OAuthSignatureException extends OAuthException
{
private static final long serialVersionUID = 1L;
private static final String MSG = "Error while signing string: %s";
/**
* Default constructor
*
* @param stringToSign plain string that gets signed (HMAC-SHA, etc)
* @param e original exception
*/
public OAuthSignatureException(String stringToSign, Exception e)
{
super(String.format(MSG, stringToSign), e);
}
}

View File

@ -1,36 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.extractors;
import org.maxkey.client.oauth.model.*;
/**
* Simple command object that extracts a {@link Token} from a String
*
* @author Pablo Fernandez
*/
public interface AccessTokenExtractor
{
/**
* Extracts the access token from the contents of an Http Response
*
* @param response the contents of the response
* @return OAuth access token
*/
public Token extract(String response);
}

View File

@ -1,38 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.extractors;
import org.maxkey.client.oauth.model.*;
/**
* Simple command object that extracts a base string from a {@link OAuthRequest}
*
* @author Pablo Fernandez
*/
public interface BaseStringExtractor
{
/**
* Extracts an url-encoded base string from the {@link OAuthRequest}.
*
* See <a href="http://oauth.net/core/1.0/#anchor14">the oauth spec</a> for more info on this.
*
* @param request the OAuthRequest
* @return the url-encoded base string
*/
String extract(OAuthRequest request);
}

View File

@ -1,68 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.extractors;
import org.maxkey.client.http.ParameterList;
import org.maxkey.client.oauth.exceptions.*;
import org.maxkey.client.oauth.model.*;
import org.maxkey.client.utils.HttpEncoder;
import org.maxkey.client.utils.Preconditions;
/**
* Default implementation of {@link BaseStringExtractor}. Conforms to OAuth 1.0a
*
* @author Pablo Fernandez
*
*/
public class BaseStringExtractorImpl implements BaseStringExtractor
{
private static final String AMPERSAND_SEPARATED_STRING = "%s&%s&%s";
/**
* {@inheritDoc}
*/
public String extract(OAuthRequest request)
{
checkPreconditions(request);
String verb = HttpEncoder.encode(request.getVerb().name());
String url = HttpEncoder.encode(request.getSanitizedUrl());
String params = getSortedAndEncodedParams(request);
return String.format(AMPERSAND_SEPARATED_STRING, verb, url, params);
}
private String getSortedAndEncodedParams(OAuthRequest request)
{
ParameterList params = new ParameterList();
params.addAll(request.getQueryStringParams());
params.addAll(request.getBodyParams());
params.addAll(new ParameterList(request.getOauthParameters()));
return params.sort().asOauthBaseString();
}
private void checkPreconditions(OAuthRequest request)
{
Preconditions.checkNotNull(request, "Cannot extract base string from null object");
if (request.getOauthParameters() == null || request.getOauthParameters().size() <= 0)
{
throw new OAuthParametersMissingException(request);
}
}
}

View File

@ -1,49 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.extractors;
import org.maxkey.client.oauth.exceptions.*;
import org.maxkey.client.oauth.model.*;
import org.maxkey.client.utils.JsonUtils;
import org.maxkey.client.utils.Preconditions;
public class GsonJsonTokenExtractor implements AccessTokenExtractor {
public Token extract(String response) {
System.out.println("extract a token from : " + response);
Preconditions.checkEmptyString(response,"Cannot extract a token from a null or empty String");
try {
Token token;
try {
token = JsonUtils.gson2Object(response, Token.class);
} catch (Exception e) {
token = JsonUtils.gson2Object("{\""+ response.replace("&", "\",\"").replace("=","\":\"") + "\"}", Token.class);
}
if (token != null) {
token.setRawResponse(response);
token.setToken(token.getAccess_token());
}
return token;
} catch (Exception e) {
throw new OAuthException("Cannot extract an acces token. Response was: " + response);
}
}
}

View File

@ -1,36 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.extractors;
import org.maxkey.client.oauth.model.*;
/**
* Simple command object that generates an OAuth Authorization header to include in the request.
*
* @author Pablo Fernandez
*/
public interface HeaderExtractor
{
/**
* Generates an OAuth 'Authorization' Http header to include in requests as the signature.
*
* @param request the OAuthRequest to inspect and generate the header
* @return the Http header value
*/
String extract(OAuthRequest request);
}

View File

@ -1,69 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.extractors;
import java.util.*;
import org.maxkey.client.oauth.exceptions.*;
import org.maxkey.client.oauth.model.*;
import org.maxkey.client.utils.HttpEncoder;
import org.maxkey.client.utils.Preconditions;
/**
* Default implementation of {@link HeaderExtractor}. Conforms to OAuth 1.0a
*
* @author Pablo Fernandez
*
*/
public class HeaderExtractorImpl implements HeaderExtractor
{
private static final String PARAM_SEPARATOR = ", ";
private static final String PREAMBLE = "OAuth ";
public static final int ESTIMATED_PARAM_LENGTH = 20;
/**
* {@inheritDoc}
*/
public String extract(OAuthRequest request)
{
checkPreconditions(request);
Map<String, String> parameters = request.getOauthParameters();
StringBuilder header = new StringBuilder(parameters.size() * ESTIMATED_PARAM_LENGTH);
header.append(PREAMBLE);
for (Map.Entry<String, String> entry : parameters.entrySet())
{
if(header.length() > PREAMBLE.length())
{
header.append(PARAM_SEPARATOR);
}
header.append(String.format("%s=\"%s\"", entry.getKey(), HttpEncoder.encode(entry.getValue())));
}
return header.toString();
}
private void checkPreconditions(OAuthRequest request)
{
Preconditions.checkNotNull(request, "Cannot extract a header from a null object");
if (request.getOauthParameters() == null || request.getOauthParameters().size() <= 0)
{
throw new OAuthParametersMissingException(request);
}
}
}

View File

@ -1,44 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.extractors;
import java.util.regex.*;
import org.maxkey.client.oauth.exceptions.*;
import org.maxkey.client.oauth.model.*;
import org.maxkey.client.utils.Preconditions;
public class JsonTokenExtractor implements AccessTokenExtractor
{
private Pattern accessTokenPattern = Pattern.compile("\"access_token\":\\s*\"(\\S*?)\"");
public Token extract(String response)
{
Preconditions.checkEmptyString(response, "Cannot extract a token from a null or empty String");
Matcher matcher = accessTokenPattern.matcher(response);
if(matcher.find())
{
return new Token(matcher.group(1), "", response);
}
else
{
throw new OAuthException("Cannot extract an acces token. Response was: " + response);
}
}
}

View File

@ -1,53 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.extractors;
import java.util.HashMap;
import org.apache.log4j.Logger;
import org.maxkey.client.oauth.exceptions.*;
import org.maxkey.client.oauth.model.*;
import org.maxkey.client.utils.Preconditions;
public class QQTokenExtractor implements AccessTokenExtractor
{
final static Logger log = Logger.getLogger(QQTokenExtractor.class);
public Token extract(String response){
log.debug("extract a token from : "+response);
Preconditions.checkEmptyString(response, "Cannot extract a token from a null or empty String");
try{
String [] fields=response.split("&");
HashMap<String,Object> tokenMap=new HashMap<String,Object>();
for(String field : fields){
String [] sfield=field.split("=");
if(sfield.length==2){
tokenMap.put(sfield[0], sfield[1]);
}
}
log.debug("token map : "+tokenMap);
Token token =new Token(tokenMap.get("access_token").toString(),"",response,tokenMap);
return token;
}
catch(Exception e){
throw new OAuthException("Cannot extract an acces token. Response was: " + response);
}
}
}

View File

@ -1,36 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.extractors;
import org.maxkey.client.oauth.model.*;
/**
* Simple command object that extracts a {@link Token} from a String
*
* @author Pablo Fernandez
*/
public interface RequestTokenExtractor
{
/**
* Extracts the request token from the contents of an Http Response
*
* @param response the contents of the response
* @return OAuth access token
*/
public Token extract(String response);
}

View File

@ -1,62 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.extractors;
import java.io.UnsupportedEncodingException;
import java.util.regex.*;
import org.maxkey.client.oauth.exceptions.*;
import org.maxkey.client.oauth.model.*;
import org.maxkey.client.utils.HttpEncoder;
import org.maxkey.client.utils.Preconditions;
/**
* Default implementation of {@AccessTokenExtractor}. Conforms to OAuth 2.0
*
*/
public class TokenExtractor20Impl implements AccessTokenExtractor
{
private static final String TOKEN_REGEX = "access_token=([^&]+)";
private static final String EMPTY_SECRET = "";
/**
* {@inheritDoc}
*/
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(TOKEN_REGEX).matcher(response);
if (matcher.find())
{
String token;
try {
token = HttpEncoder.decode(matcher.group(1));
return new Token(token, EMPTY_SECRET, response);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
else
{
throw new OAuthException("Response body is incorrect. Can't extract a token from this: '" + response + "'", null);
}
}
}

View File

@ -1,64 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.extractors;
import java.io.UnsupportedEncodingException;
import java.util.regex.*;
import org.maxkey.client.oauth.exceptions.*;
import org.maxkey.client.oauth.model.*;
import org.maxkey.client.utils.HttpEncoder;
import org.maxkey.client.utils.Preconditions;
/**
* Default implementation of {@RequestTokenExtractor} and {@AccessTokenExtractor}. Conforms to OAuth 1.0a
*
* The process for extracting access and request tokens is similar so this class can do both things.
*
* @author Pablo Fernandez
*/
public class TokenExtractorImpl implements RequestTokenExtractor, AccessTokenExtractor
{
private static final Pattern TOKEN_REGEX = Pattern.compile("oauth_token=([^&]+)");
private static final Pattern SECRET_REGEX = Pattern.compile("oauth_token_secret=([^&]*)");
/**
* {@inheritDoc}
*/
public Token extract(String response){
Preconditions.checkEmptyString(response, "Response body is incorrect. Can't extract a token from an empty string");
String token = extract(response, TOKEN_REGEX);
String secret = extract(response, SECRET_REGEX);
return new Token(token, secret, response);
}
private String extract(String response, Pattern p){
Matcher matcher = p.matcher(response);
if (matcher.find() && matcher.groupCount() >= 1){
try {
return HttpEncoder.decode(matcher.group(1));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}else{
throw new OAuthException("Response body is incorrect. Can't extract token and secret from this: '" + response + "'", null);
}
}
}

View File

@ -1,109 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.model;
import java.io.*;
import org.maxkey.client.http.SignatureType;
/**
* Parameter object that groups OAuth config values
*
* @author Pablo Fernandez
*/
public class OAuthConfig {
private final String apiKey;
private final String apiSecret;
private final String callback;
private final SignatureType signatureType;
private final String scope;
private String approvalPrompt; // 授权方式:force or auto
private String responseType; // 返回类型:codepasswrodtoken
private final OutputStream debugStream;
public OAuthConfig(String key, String secret) {
this(key, secret, null, null, null, null);
}
public OAuthConfig(String key, String secret, String callback) {
this(key, secret, callback, null, null, null);
}
public OAuthConfig(String key, String secret, String callback,
SignatureType type, String scope, OutputStream stream) {
this.apiKey = key;
this.apiSecret = secret;
this.callback = callback;
this.signatureType = type;
this.scope = scope;
this.debugStream = stream;
}
public String getApiKey() {
return apiKey;
}
public String getApiSecret() {
return apiSecret;
}
public String getCallback() {
return callback;
}
public SignatureType getSignatureType() {
return signatureType;
}
public String getScope() {
return scope;
}
public boolean hasScope() {
return scope != null;
}
public String getApprovalPrompt() {
return approvalPrompt;
}
public void setApprovalPrompt(String approvalPrompt) {
this.approvalPrompt = approvalPrompt;
}
public String getResponseType() {
return responseType;
}
public void setResponseType(String responseType) {
this.responseType = responseType;
}
public void log(String message) {
if (debugStream != null) {
message = message + "\n";
try {
debugStream.write(message.getBytes("UTF8"));
} catch (Exception e) {
throw new RuntimeException(
"there were problems while writting to the debug stream",
e);
}
}
}
}

View File

@ -1,63 +0,0 @@
/*
Copyright 2010 Pablo Fernandez
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.maxkey.client.oauth.model;
/**
* This class contains OAuth constants, used project-wide
*/
public interface OAuthConstants {
String TIMESTAMP = "oauth_timestamp";
String SIGN_METHOD = "oauth_signature_method";
String SIGNATURE = "oauth_signature";
String CONSUMER_SECRET = "oauth_consumer_secret";
String CONSUMER_KEY = "oauth_consumer_key";
String CALLBACK = "oauth_callback";
String VERSION = "oauth_version";
String NONCE = "oauth_nonce";
String REALM = "realm";
String PARAM_PREFIX = "oauth_";
String TOKEN = "oauth_token";
String TOKEN_SECRET = "oauth_token_secret";
String OUT_OF_BAND = "oob";
String VERIFIER = "oauth_verifier";
String HEADER = "Authorization";
String SCOPE = "scope";
String BASIC = "Basic";
// OAuth 2.0
String ACCESS_TOKEN = "access_token";
String CLIENT_ID = "client_id";
String CLIENT_SECRET = "client_secret";
String REDIRECT_URI = "redirect_uri";
String CODE = "code";
String REFRESH_TOKEN = "refresh_token";
String GRANT_TYPE = "grant_type";
String AUTHORIZATION_CODE = "authorization_code";
String STATE = "state";
String USERNAME = "username";
String PASSWORD = "password";
String RESPONSE_TYPE = "response_type";
String RESPONSE_TYPE_CODE = "code";
//not OAuth specific
String USER_AGENT_HEADER_NAME = "User-Agent";
public static final Token EMPTY_TOKEN = new Token("", "");
}

View File

@ -1,94 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.model;
import java.util.*;
import org.maxkey.client.http.HttpVerb;
import org.maxkey.client.http.Request;
/**
* The representation of an OAuth HttpRequest.
*
* Adds OAuth-related functionality to the {@link Request}
*
* @author Pablo Fernandez
*/
public class OAuthRequest extends Request
{
private static final String OAUTH_PREFIX = "oauth_";
private Map<String, String> oauthParameters;
/**
* Default constructor.
*
* @param verb Http verb/method
* @param url resource URL
*/
public OAuthRequest(HttpVerb verb, String url)
{
super(verb, url);
this.oauthParameters = new HashMap<String, String>();
}
/**
* Adds an OAuth parameter.
*
* @param key name of the parameter
* @param value value of the parameter
*
* @throws IllegalArgumentException if the parameter is not an OAuth parameter
*/
public void addOAuthParameter(String key, String value)
{
oauthParameters.put(checkKey(key), value);
}
public void addParameter(String key, String value)
{
oauthParameters.put(key, value);
}
private String checkKey(String key)
{
if (key.startsWith(OAUTH_PREFIX) || key.equals(OAuthConstants.SCOPE))
{
return key;
}
else
{
throw new IllegalArgumentException(String.format("OAuth parameters must either be '%s' or start with '%s'", OAuthConstants.SCOPE, OAUTH_PREFIX));
}
}
/**
* Returns the {@link Map} containing the key-value pair of parameters.
*
* @return parameters as map
*/
public Map<String, String> getOauthParameters()
{
return oauthParameters;
}
@Override
public String toString()
{
return String.format("@OAuthRequest(%s, %s)", getVerb(), getUrl());
}
}

View File

@ -1,305 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.model;
import java.io.*;
import java.util.Map;
import org.maxkey.client.utils.Preconditions;
/**
* Represents an OAuth 2 Access token.
* <p>
* http://tools.ietf.org/html/rfc6749#section-5.1
*
* @see <a href="https://tools.ietf.org/html/rfc6749#section-4.1.4">OAuth 2 Access Token Specification</a></p>
*/
public class Token implements Serializable {
private static final long serialVersionUID = 715000866082812683L;
/*
* for return from Provider
*/
private String rawResponse;
private Map<String, Object> responseObject;
/*
* for OAuth 1.0a & OAuth 2.0
*/
/**
* access_token
* <p>
* REQUIRED. The access token issued by the authorization server.</p>
*/
private String access_token;
private String token;
private String secret;
/**
* refresh_token
* <p>
* OPTIONAL. The refresh token, which can be used to obtain new access tokens using the same authorization grant as
* described in http://tools.ietf.org/html/rfc6749#section-6</p>
*/
private String refresh_token;
/**
* expires_in
* <p>
* RECOMMENDED. The lifetime in seconds of the access token. For example, the value "3600" denotes that the access
* token will expire in one hour from the time the response was generated. If omitted, the authorization server
* SHOULD provide the expiration time via other means or document the default value.</p>
*/
private String expires_in;
/**
* scope
* <p>
* OPTIONAL, if identical to the scope requested by the client; otherwise, REQUIRED. The scope of the access token
* as described by http://tools.ietf.org/html/rfc6749#section-3.3</p>
*/
private String scope;
private String signature;
/*
* for OpenID Connect
*/
/**
* token_type
* <p>
* REQUIRED. The type of the token issued as described in http://tools.ietf.org/html/rfc6749#section-7.1 Value is
* case insensitive.</p>
*/
private String token_type;
private String id_token;
/**
* https://self-issued.me
*/
private String sub_jwk;
/*
* for error
*/
private String error;
private String error_description;
/**
*
*/
public Token() {
rawResponse = null;
}
/**
* Default constructor
*
* @param token
* token value. Can't be null.
* @param secret
* token secret. Can't be null.
*/
public Token(String token, String secret) {
this(token, secret, null);
}
public Token(String token, String secret, String rawResponse) {
Preconditions.checkNotNull(token, "Token can't be null");
Preconditions.checkNotNull(secret, "Secret can't be null");
this.token = token;
this.secret = secret;
this.rawResponse = rawResponse;
this.responseObject = null;
}
public Token(String token, String secret, String rawResponse,
Map<String, Object> responseObject) {
this.token = token;
this.secret = secret;
this.rawResponse = rawResponse;
this.responseObject = responseObject;
}
public String getAccess_token() {
if(access_token==null||access_token.equals("")){
access_token=this.token;
}
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public Map<String, Object> getResponseObject() {
return responseObject;
}
public void setResponseObject(Map<String, Object> responseObject) {
this.responseObject = responseObject;
}
public String getToken() {
if(token==null){
token=this.access_token;
}
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
public String getExpires_in() {
return expires_in;
}
public void setExpires_in(String expires_in) {
this.expires_in = expires_in;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public String getToken_type() {
return token_type;
}
public void setToken_type(String token_type) {
this.token_type = token_type;
}
public String getId_token() {
return id_token;
}
public void setId_token(String id_token) {
this.id_token = id_token;
}
public String getSub_jwk() {
return sub_jwk;
}
public void setSub_jwk(String sub_jwk) {
this.sub_jwk = sub_jwk;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getError_description() {
return error_description;
}
public void setError_description(String error_description) {
this.error_description = error_description;
}
public void setRawResponse(String rawResponse) {
this.rawResponse = rawResponse;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getRawResponse() {
if (rawResponse == null) {
throw new IllegalStateException(
"This token object was not constructed by scribe and does not have a rawResponse");
}
return rawResponse;
}
@Override
public String toString() {
return "Token [rawResponse=" + rawResponse + ", responseObject="
+ responseObject + ", access_token=" + access_token
+ ", token=" + token + ", secret=" + secret
+ ", refresh_token=" + refresh_token + ", expires_in="
+ expires_in + ", signature=" + signature + ", token_type="
+ token_type + ", id_token=" + id_token + ", sub_jwk="
+ sub_jwk + ", error=" + error + ", error_description="
+ error_description + "]";
}
/**
* Returns true if the token is empty (token = "", secret = "")
*/
public boolean isEmpty() {
return "".equals(this.token) && "".equals(this.secret);
}
/**
* Factory method that returns an empty token (token = "", secret = "").
*
* Useful for two legged OAuth.
*/
public static Token empty() {
return new Token("", "");
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Token that = (Token) o;
return token.equals(that.token) && secret.equals(that.secret);
}
@Override
public int hashCode() {
return 31 * token.hashCode() + secret.hashCode();
}
}

View File

@ -1,47 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.model;
import org.maxkey.client.utils.Preconditions;
/**
* Represents an OAuth verifier code.
*
* @author Pablo Fernandez
*/
public class Verifier
{
private final String value;
/**
* Default constructor.
*
* @param value verifier value
*/
public Verifier(String value)
{
Preconditions.checkNotNull(value, "Must provide a valid string as verifier");
this.value = value;
}
public String getValue()
{
return value;
}
}

View File

@ -1,122 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.oauth;
import org.maxkey.client.http.HttpVerb;
import org.maxkey.client.http.Response;
import org.maxkey.client.oauth.builder.api.*;
import org.maxkey.client.oauth.model.*;
public class OAuth20ServiceImpl implements OAuthService
{
private static final String VERSION = "2.0";
private final DefaultApi20 api;
private final OAuthConfig config;
/**
* Default constructor
*
* @param api OAuth2.0 api information
* @param config OAuth 2.0 configuration param object
*/
public OAuth20ServiceImpl(DefaultApi20 api, OAuthConfig config)
{
this.api = api;
this.config = config;
}
/**
* Default constructor
*
* @param clientId
* @param clientSecret
* @param redirectUri
*/
public OAuth20ServiceImpl(String clientId, String clientSecret,String redirectUri)
{
this.api=new MaxkeyApi20();
this.config =new OAuthConfig(clientId,clientSecret,redirectUri);
}
/**
* {@inheritDoc}
*/
public Token getAccessToken(Token requestToken, Verifier verifier)
{
OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
if(api.getAccessTokenVerb().equals(HttpVerb.GET)){
request.addQuerystringParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
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());
}else{
request.getBodyParams().add(OAuthConstants.CLIENT_ID, config.getApiKey());
request.getBodyParams().add(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
request.getBodyParams().add(OAuthConstants.CODE, verifier.getValue());
request.getBodyParams().add(OAuthConstants.REDIRECT_URI, config.getCallback());
request.getBodyParams().add(OAuthConstants.GRANT_TYPE, api.getGrantType());
if(config.hasScope())request.getBodyParams().add(OAuthConstants.SCOPE, config.getScope());
}
Response response = request.send();
return api.getAccessTokenExtractor().extract(response.getBody());
}
/**
* {@inheritDoc}
*/
public Token getRequestToken()
{
throw new UnsupportedOperationException("Unsupported operation, please use 'getAuthorizationUrl' and redirect your users there");
}
/**
* {@inheritDoc}
*/
public String getVersion()
{
return VERSION;
}
/**
* {@inheritDoc}
*/
public void signRequest(Token accessToken, OAuthRequest request)
{
request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getToken());
}
/**
* {@inheritDoc}
*/
public String getAuthorizationUrl(Token requestToken)
{
return api.getAuthorizationUrl(config);
}
@Override
public void signAccessTokenRequest(Token accessToken, OAuthRequest request) {
// TODO Auto-generated method stub
request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getToken());
}
}

View File

@ -1,87 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.oauth;
import org.maxkey.client.http.HttpVerb;
import org.maxkey.client.http.Response;
import org.maxkey.client.oauth.builder.ServiceBuilder;
import org.maxkey.client.oauth.builder.api.MaxkeyPasswordApi20;
import org.maxkey.client.oauth.model.OAuthConfig;
import org.maxkey.client.oauth.model.OAuthRequest;
import org.maxkey.client.oauth.model.Token;
/**
* OAuth 2.0 api.
*/
public class OAuthPasswordService {
private OAuthConfig config;
private MaxkeyPasswordApi20 passwordApi20;
public OAuthPasswordService() {
super();
}
public OAuthPasswordService(OAuthConfig config,MaxkeyPasswordApi20 passwordApi20) {
super();
this.passwordApi20=passwordApi20;
this.config = config;
}
public Token getAccessToken(String username, String password) {
try {
String accessTokenUrl=passwordApi20.getAuthorizationUrl(config, username, password);
System.out.println(accessTokenUrl);
OAuthRequest oauthRequest = new OAuthRequest(HttpVerb.GET,accessTokenUrl);
Response response = oauthRequest.send();
return passwordApi20.getAccessTokenExtractor().extract(response.getBody());
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
public Response sendRequest(Token accessToken,HttpVerb requestMethod,String requestUrl) {
OAuthRequest oauthRequest = new OAuthRequest(requestMethod, requestUrl);
ServiceBuilder builder = new ServiceBuilder().provider(passwordApi20)
.apiKey(config.getApiKey())
.apiSecret(config.getApiSecret())
.callback(config.getCallback());
OAuthService oAuthService=builder.build();
oAuthService.signRequest(accessToken, oauthRequest);
return oauthRequest.send();
}
public OAuthConfig getConfig() {
return config;
}
public void setConfig(OAuthConfig config) {
this.config = config;
}
public MaxkeyPasswordApi20 getPasswordApi20() {
return passwordApi20;
}
public void setPasswordApi20(MaxkeyPasswordApi20 passwordApi20) {
this.passwordApi20 = passwordApi20;
}
}

View File

@ -1,73 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.oauth;
import org.maxkey.client.oauth.model.*;
/**
* The main Scribe object.
*
* A facade responsible for the retrieval of request and access tokens and for the signing of HTTP requests.
*
* @author Pablo Fernandez
*/
public interface OAuthService
{
/**
* Retrieve the request token.
*
* @return request token
*/
public Token getRequestToken();
/**
* Retrieve the access token
*
* @param requestToken request token (obtained previously)
* @param verifier verifier code
* @return access token
*/
public Token getAccessToken(Token requestToken, Verifier verifier);
/**
* Signs am OAuth request
*
* @param accessToken access token (obtained previously)
* @param request request to sign
*/
public void signRequest(Token accessToken, OAuthRequest request);
public void signAccessTokenRequest(Token accessToken, OAuthRequest request);
/**
* Returns the OAuth version of the service.
*
* @return oauth version as string
*/
public String getVersion();
/**
* Returns the URL where you should redirect your users to authenticate
* your application.
*
* @param requestToken the request token you need to authorize
* @return the URL where you should redirect your users
*/
public String getAuthorizationUrl(Token requestToken);
}

View File

@ -1,53 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.services;
public abstract class Base64Encoder
{
private static Base64Encoder instance;
public static synchronized Base64Encoder getInstance()
{
if (instance == null)
{
instance = createEncoderInstance();
}
return instance;
}
private static Base64Encoder createEncoderInstance()
{
if (CommonsEncoder.isPresent())
{
return new CommonsEncoder();
}
else
{
return new DatatypeConverterEncoder();
}
}
public static String type()
{
return getInstance().getType();
}
public abstract String encode(byte[] bytes);
public abstract String getType();
}

View File

@ -1,59 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.services;
import org.apache.commons.codec.binary.*;
import org.maxkey.client.oauth.exceptions.*;
import java.io.UnsupportedEncodingException;
public class CommonsEncoder extends Base64Encoder
{
@Override
public String encode(byte[] bytes)
{
try
{
return new String(Base64.encodeBase64(bytes), "UTF-8");
}
catch (UnsupportedEncodingException e)
{
throw new OAuthSignatureException("Can't perform base64 encoding", e);
}
}
@Override
public String getType()
{
return "CommonsCodec";
}
public static boolean isPresent()
{
try
{
Class.forName("org.apache.commons.codec.binary.Base64");
return true;
}
catch (ClassNotFoundException e)
{
return false;
}
}
}

View File

@ -1,35 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.services;
import javax.xml.bind.*;
public class DatatypeConverterEncoder extends Base64Encoder
{
@Override
public String encode(byte[] bytes)
{
return DatatypeConverter.printBase64Binary(bytes);
}
@Override
public String getType()
{
return "DatatypeConverter";
}
}

View File

@ -1,79 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.services;
import javax.crypto.*;
import javax.crypto.spec.*;
import org.maxkey.client.oauth.exceptions.*;
import org.maxkey.client.utils.HttpEncoder;
import org.maxkey.client.utils.Preconditions;
/**
* HMAC-SHA1 implementation of {@SignatureService}
*
* @author Pablo Fernandez
*
*/
public class HMACSha1SignatureService implements SignatureService
{
private static final String EMPTY_STRING = "";
private static final String CARRIAGE_RETURN = "\r\n";
private static final String UTF8 = "UTF-8";
private static final String HMAC_SHA1 = "HmacSHA1";
private static final String METHOD = "HMAC-SHA1";
/**
* {@inheritDoc}
*/
public String getSignature(String baseString, String apiSecret, String tokenSecret)
{
try
{
Preconditions.checkEmptyString(baseString, "Base string cant be null or empty string");
Preconditions.checkEmptyString(apiSecret, "Api secret cant be null or empty string");
return doSign(baseString, HttpEncoder.encode(apiSecret) + '&' + HttpEncoder.encode(tokenSecret));
}
catch (Exception e)
{
throw new OAuthSignatureException(baseString, e);
}
}
private String doSign(String toSign, String keyString) throws Exception
{
SecretKeySpec key = new SecretKeySpec((keyString).getBytes(UTF8), HMAC_SHA1);
Mac mac = Mac.getInstance(HMAC_SHA1);
mac.init(key);
byte[] bytes = mac.doFinal(toSign.getBytes(UTF8));
return bytesToBase64String(bytes).replace(CARRIAGE_RETURN, EMPTY_STRING);
}
private String bytesToBase64String(byte[] bytes)
{
return Base64Encoder.getInstance().encode(bytes);
}
/**
* {@inheritDoc}
*/
public String getSignatureMethod()
{
return METHOD;
}
}

View File

@ -1,59 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.services;
import org.maxkey.client.oauth.exceptions.*;
import org.maxkey.client.utils.HttpEncoder;
import org.maxkey.client.utils.Preconditions;
/**
* plaintext implementation of {@SignatureService}
*
* @author Pablo Fernandez
*
*/
public class PlaintextSignatureService implements SignatureService
{
private static final String METHOD = "PLAINTEXT";
/**
* {@inheritDoc}
*/
public String getSignature(String baseString, String apiSecret, String tokenSecret)
{
try
{
Preconditions.checkEmptyString(apiSecret, "Api secret cant be null or empty string");
return HttpEncoder.encode(apiSecret) + '&' + HttpEncoder.encode(tokenSecret);
}
catch (Exception e)
{
throw new OAuthSignatureException(baseString, e);
}
}
/**
* {@inheritDoc}
*/
public String getSignatureMethod()
{
return METHOD;
}
}

View File

@ -1,70 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.services;
import java.security.*;
import org.maxkey.client.oauth.exceptions.*;
/**
* A signature service that uses the RSA-SHA1 algorithm.
*/
public class RSASha1SignatureService implements SignatureService
{
private static final String METHOD = "RSA-SHA1";
private static final String RSA_SHA1 = "SHA1withRSA";
private static final String UTF8 = "UTF-8";
private PrivateKey privateKey;
public RSASha1SignatureService(PrivateKey privateKey)
{
this.privateKey = privateKey;
}
/**
* {@inheritDoc}
*/
public String getSignature(String baseString, String apiSecret, String tokenSecret)
{
try
{
Signature signature = Signature.getInstance(RSA_SHA1);
signature.initSign(privateKey);
signature.update(baseString.getBytes(UTF8));
return bytesToBase64String(signature);
}
catch (Exception e)
{
throw new OAuthSignatureException(baseString, e);
}
}
private String bytesToBase64String(Signature signature) throws SignatureException
{
return Base64Encoder.getInstance().encode(signature.sign());
}
/**
* {@inheritDoc}
*/
public String getSignatureMethod()
{
return METHOD;
}
}

View File

@ -1,45 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.services;
/**
* Signs a base string, returning the OAuth signature
*
* @author Pablo Fernandez
*
*/
public interface SignatureService
{
/**
* Returns the signature
*
* @param baseString url-encoded string to sign
* @param apiSecret api secret for your app
* @param tokenSecret token secret (empty string for the request token step)
*
* @return signature
*/
public String getSignature(String baseString, String apiSecret, String tokenSecret);
/**
* Returns the signature method/algorithm
*
* @return
*/
public String getSignatureMethod();
}

View File

@ -1,42 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.services;
/**
* Unix epoch timestamp generator.
*
* This class is useful for stubbing in tests.
*
* @author Pablo Fernandez
*/
public interface TimestampService
{
/**
* Returns the unix epoch timestamp in seconds
*
* @return timestamp
*/
public String getTimestampInSeconds();
/**
* Returns a nonce (unique value for each request)
*
* @return nonce
*/
public String getNonce();
}

View File

@ -1,85 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.services;
import java.util.*;
/**
* Implementation of {@link TimestampService} using plain java classes.
*
* @author Pablo Fernandez
*/
public class TimestampServiceImpl implements TimestampService
{
private Timer timer;
/**
* Default constructor.
*/
public TimestampServiceImpl()
{
timer = new Timer();
}
/**
* {@inheritDoc}
*/
public String getNonce()
{
Long ts = getTs();
return String.valueOf(ts + timer.getRandomInteger());
}
/**
* {@inheritDoc}
*/
public String getTimestampInSeconds()
{
return String.valueOf(getTs());
}
private Long getTs()
{
return timer.getMilis() / 1000;
}
void setTimer(Timer timer)
{
this.timer = timer;
}
/**
* Inner class that uses {@link System} for generating the timestamps.
*
* @author Pablo Fernandez
*/
static class Timer
{
private final Random rand = new Random();
Long getMilis()
{
return System.currentTimeMillis();
}
Integer getRandomInteger()
{
return rand.nextInt();
}
}
}

View File

@ -1,25 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
/**
* @author Administrator
*
*/
package org.maxkey.client;

View File

@ -1,69 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.tokenbase;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.maxkey.client.crypto.Base64Utils;
import org.maxkey.client.crypto.ReciprocalUtils;
import org.maxkey.client.utils.JsonUtils;
public class TokenUtils {
public static String decode(String tokenString,String algorithmKey, String algorithm){
String token=ReciprocalUtils.decoder(Base64Utils.base64UrlDecode(tokenString), algorithmKey, algorithm);
try {
token=new String(Hex.decodeHex(token.toCharArray()),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (DecoderException e) {
e.printStackTrace();
}
return token;
}
public static String [] parseSimpleBasedToken(String token){
return new String[] {token.substring(0, token.indexOf("@@")),
token.substring(token.indexOf("@@")+2)};
}
@SuppressWarnings("unchecked")
public static HashMap<String,Object> parseJsonBasedToken(String token){
HashMap<String,Object> tokenMap=new HashMap<String,Object>();
tokenMap=JsonUtils.gson2Object(token, tokenMap.getClass());
return tokenMap;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String token="634d23bf64c20ae937eb9b81dbe9c30969d2d569c8c6c3b9d8089bff8c910c07722ca1f4137132fefb380fb8dd011e71e5b1df84b73088629b85f07a3559c7d9";
// ZpqjxUOX3QuE8rwl6etstU0z2WO%2Flpo5
String tokenString=TokenUtils.decode(token, "x8zPbCya", ReciprocalUtils.Algorithm.DES);
System.out.println(tokenString);
}
}

View File

@ -1,66 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonUtils {
/**
* Transform json string to java bean object use Gson
* @param <T>
* @param json
* @param Class
* @return Object
*/
public static <T> T gson2Object(String json,Class<T> cls){
T newBean = (new Gson()).fromJson(json, cls);
return newBean;
}
/**
* Transform java bean object to json string use Gson
* @param bean
* @return string
*/
public static String gson2Json(Object bean){
String json="";
// convert java object to JSON format,
// and returned as JSON formatted string
json = (new Gson()).toJson(bean);
return json;
}
/**
* prettyJson use Gson
* @param bean
* @return String
*/
public static String gsonPretty(Object bean){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(bean);
return json;
}
}

View File

@ -1,42 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.utils;
import java.util.Map;
public abstract class MapUtils {
public static <K, V> String toString(Map<K, V> map) {
if (map == null) {
return "";
}
if (map.isEmpty()) {
return "{}";
}
final StringBuilder result = new StringBuilder();
for (Map.Entry<K, V> entry : map.entrySet()) {
result.append(", ")
.append(entry.getKey().toString())
.append(" -> ")
.append(entry.getValue().toString())
.append(' ');
}
return "{" + result.append('}').substring(1);
}
}

View File

@ -1,80 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.utils;
import java.io.UnsupportedEncodingException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class PathUtils {
private final Log log = LogFactory.getLog(getClass());
private static PathUtils instance = null;
private String classPath;
public static synchronized PathUtils getInstance() {
if (instance == null) {
instance = new PathUtils();
instance.log.debug("getInstance()" +" new ConfigFile instance");
}
return instance;
}
public PathUtils() {
try {
classPath = java.net.URLDecoder.decode(PathUtils.class.getResource("PathUtilsFile.properties").getFile(),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String fileProtocol=PathUtils.class.getResource("PathUtilsFile.properties").getProtocol();
log.info("getWebRoot getProtocol:"+PathUtils.class.getResource("PathUtilsFile.properties").getProtocol());
if(fileProtocol.equalsIgnoreCase("file")){
// /D:/SoftWare/apache-tomcat-5.5.30/webapps/app
if(classPath.indexOf("file:")==0){
classPath=classPath.substring(5, classPath.length());
}
}else if(fileProtocol.equalsIgnoreCase("jar")){
// file:/D:/SoftWare/apache-tomcat-5.5.30/webapps/app
if(classPath.indexOf("file:")==0){
classPath=classPath.substring(5, classPath.length());
}
}else if(fileProtocol.equalsIgnoreCase("wsjar")){
if(classPath.indexOf("file:")==0){
classPath=classPath.substring(5, classPath.length());
}
}else if(classPath.equalsIgnoreCase("file:")){
classPath=classPath.substring(5, classPath.length());
}
/// /WEB-INF/
if(classPath.indexOf("/WEB-INF/")!=-1){
classPath=classPath.substring(0, classPath.indexOf("/WEB-INF/"));
}
log.info("getWebRoot() webApp root Path : "+classPath);
}
public String getWebInf(){
return classPath+"/WEB-INF/";
}
public String getClassPath(){
return classPath+"/WEB-INF/classes/";
}
}

View File

@ -1,93 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.utils;
import java.util.Locale;
import java.util.regex.Pattern;
import org.maxkey.client.oauth.model.OAuthConstants;
/**
* Utils for checking preconditions and invariants
*/
public abstract class Preconditions {
private static final String DEFAULT_MESSAGE = "Received an invalid parameter";
// scheme = alpha *( alpha | digit | "+" | "-" | "." )
private static final String URL_REGEXP = "^[a-zA-Z][a-zA-Z0-9+.-]*://\\S+";
/**
* Checks that an object is not null.
*
* @param object any object
* @param errorMsg error message
*
* @throws IllegalArgumentException if the object is null
*/
public static void checkNotNull(Object object, String errorMsg) {
check(object != null, errorMsg);
}
/**
* Checks that a string is not null or empty
*
* @param string any string
* @param errorMsg error message
*
* @throws IllegalArgumentException if the string is null or empty
*/
public static void checkEmptyString(String string, String errorMsg) {
check(string != null && !string.trim().isEmpty(), errorMsg);
}
/**
* Checks that a URL is valid
*
* @param url any string
* @param errorMsg error message
*/
public static void checkValidUrl(String url, String errorMsg) {
checkEmptyString(url, errorMsg);
check(isUrl(url), errorMsg);
}
/**
* Checks that a URL is a valid OAuth callback
*
* @param url any string
* @param errorMsg error message
*/
public static void checkValidOAuthCallback(String url, String errorMsg) {
checkEmptyString(url, errorMsg);
if (url.toLowerCase(Locale.getDefault()).compareToIgnoreCase(OAuthConstants.OUT_OF_BAND) != 0) {
check(isUrl(url), errorMsg);
}
}
private static boolean isUrl(String url) {
return Pattern.compile(URL_REGEXP).matcher(url).matches();
}
private static void check(boolean requirements, String error) {
if (!requirements) {
throw new IllegalArgumentException(error == null || error.trim().length() <= 0 ? DEFAULT_MESSAGE : error);
}
}
}

View File

@ -1,66 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.zip.GZIPInputStream;
/**
* Utils to deal with Streams.
*/
public abstract class StreamUtils {
/**
* Returns the stream contents as an UTF-8 encoded string
*
* @param is input stream
* @return string contents
* @throws java.io.IOException in any. SocketTimeout in example
*/
public static String getStreamContents(InputStream is) throws IOException {
Preconditions.checkNotNull(is, "Cannot get String from a null object");
final char[] buffer = new char[0x10000];
final StringBuilder out = new StringBuilder();
try (Reader in = new InputStreamReader(is, "UTF-8")) {
int read;
do {
read = in.read(buffer, 0, buffer.length);
if (read > 0) {
out.append(buffer, 0, read);
}
} while (read >= 0);
}
return out.toString();
}
/**
* Return String content from a gzip stream
*
* @param is input stream
* @return string contents
* @throws java.io.IOException in any. SocketTimeout in example
*/
public static String getGzipStreamContents(InputStream is) throws IOException {
Preconditions.checkNotNull(is, "Cannot get String from a null object");
final GZIPInputStream gis = new GZIPInputStream(is);
return getStreamContents(gis);
}
}

View File

@ -1,156 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.utils;
import java.lang.management.ManagementFactory;
import java.security.SecureRandom;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import org.maxkey.client.crypto.Base64Utils;
public class StringGenerator {
private static final int MAX_PID = 65536;
private char[] DEFAULT_CODEC = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
public static final char[] DEFAULT_CODE_NUMBER = "1234567890".toCharArray();
public static final char[] DEFAULT_CODE_LOWERCASE = "abcdefghijklmnopqrstuvwxyz".toCharArray();
public static final char[] DEFAULT_CODE_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
public static final char[] DEFAULT_CODE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
public static final char[] DEFAULT_CODE_NUMBER_LETTERS = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
public static int processId;
private static final String uuidRegex = "^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$";
private Random random = new SecureRandom();
private int length;
static {
final String jvmName = ManagementFactory.getRuntimeMXBean().getName();
int index = jvmName.indexOf('@');
if (index < 1)
throw new RuntimeException("Could not get PID");
try {
processId= Integer.parseInt(jvmName.substring(0, index)) % MAX_PID;
} catch (NumberFormatException e) {
throw new RuntimeException("Could not get PID");
}
}
/**
* Create a generator with the default length (6).
*/
public StringGenerator() {
this(6);
}
/**
* Create a generator of random strings of the length provided
*
* @param length the length of the strings generated
*/
public StringGenerator(int length) {
this.length = length;
}
public StringGenerator(char[] defaultCode,int length) {
this.DEFAULT_CODEC=defaultCode;
this.length = length;
}
public String randomGenerate() {
byte[] verifierBytes = new byte[length];
random.nextBytes(verifierBytes);
return getString(verifierBytes);
}
public String uuidGenerate() {
return UUID.randomUUID().toString().toLowerCase();
}
public String uniqueGenerate() {
StringBuffer uniqueString=new StringBuffer("");
this.length=9;
String randomString =randomGenerate();
uniqueString.append(randomString.subSequence(0, 4));
Date currentDate=new Date();
DateFormat dateFormat = new SimpleDateFormat("ddMMyyyyHHmmssSSS");
String dateString=Base64Utils.encodeBase64(dateFormat.format(currentDate).getBytes());
dateString=dateString.substring(0, dateString.length()-1);
uniqueString.append(dateString);
uniqueString.append(randomString.subSequence(5, 8));
return uniqueString.toString();
}
/**
* Convert these random bytes to a verifier string. The length of the byte array can be
* {@link #setLength(int) configured}. The default implementation mods the bytes to fit into the
* ASCII letters 1-9, A-Z, a-z .
*
* @param verifierBytes The bytes.
* @return The string.
*/
protected String getString(byte[] verifierBytes) {
char[] chars = new char[verifierBytes.length];
for (int i = 0; i < verifierBytes.length; i++) {
chars[i] = DEFAULT_CODEC[((verifierBytes[i] & 0xFF) % DEFAULT_CODEC.length)];
}
return new String(chars);
}
/**
* The random value generator used to create token secrets.
*
* @param random The random value generator used to create token secrets.
*/
public void setRandom(Random random) {
this.random = random;
}
/**
* The length of string to generate.
*
* @param length the length to set
*/
public void setLength(int length) {
this.length = length;
}
public static boolean uuidMatches(String uuidString) {
return uuidString.matches(uuidRegex);
}
}

View File

@ -1,119 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.web.authn;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.maxkey.client.oauth.OAuthClient;
import org.maxkey.client.oauth.builder.ServiceBuilder;
import org.maxkey.client.oauth.builder.api.MaxkeyApi20;
import org.maxkey.client.oauth.domain.UserInfo;
import org.maxkey.client.oauth.model.Token;
import org.maxkey.client.oauth.model.Verifier;
import org.maxkey.client.oauth.oauth.OAuthService;
/**
*
* @author Crystal.Sea
*/
public class AuthenticationFilter implements Filter {
private static Log log = LogFactory.getLog(AuthenticationFilter. class );
private static final String UUID_REGEX = "^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$";
public static final String CONST_MAXKEY_USERINFO="CONST_MAXKEY_USERINFO";
private String clientId;
private String clientSecret;
private String callBackUri;
private boolean enable;
private OAuthService service ;
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
HttpSession session = httpServletRequest.getSession();
if(enable){
Token EMPTY_TOKEN = null;
String code=request.getParameter("code");
if(code!=null&&uuidMatches(code)){
Verifier verifier = new Verifier(code);
Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
log.debug(" access token is "+accessToken);
OAuthClient restClient=new OAuthClient(OAuthClient.OAUTH_V20_USERINFO_URI);
UserInfo userInfo=restClient.getUserInfo(accessToken.getToken());
session.setAttribute(CONST_MAXKEY_USERINFO, userInfo);
}else if(session.getAttribute(CONST_MAXKEY_USERINFO)==null){
String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
log.debug("Redirect to authorization Url : "+authorizationUrl);
httpServletResponse.sendRedirect(authorizationUrl);
}
}
chain.doFilter(request, response);
}
public void destroy() {
this.destroy();
}
public void init(FilterConfig config) throws ServletException {
this.clientId=config.getInitParameter("clientId");
this.clientSecret=config.getInitParameter("clientSecret");
this.callBackUri=config.getInitParameter("callBackUri");
this.enable=config.getInitParameter("enable").equalsIgnoreCase("true");
log.debug("client_id : "+clientId);
log.debug("client_secret : "+clientSecret);
log.debug("callBack Uri : "+callBackUri);
log.debug("enable : "+enable);
service = new ServiceBuilder()
.provider(MaxkeyApi20.class)
.apiKey(this.clientId)
.apiSecret(this.clientSecret)
.callback(this.callBackUri)
.build();
log.debug(" init.");
}
public static boolean uuidMatches(String uuidString) {
return uuidString.matches(UUID_REGEX);
}
}

View File

@ -1,65 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.web.authn;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Crystal.Sea
*/
public class SingleSignOutFilter implements Filter {
private static final Logger log = LoggerFactory.getLogger(SingleSignOutFilter.class);
private String singleSignOutEndpoint;
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
HttpSession session = httpServletRequest.getSession();
session.removeAttribute(AuthenticationFilter.CONST_MAXKEY_USERINFO);
session.invalidate();
httpServletResponse.sendRedirect(singleSignOutEndpoint);
chain.doFilter(request, response);
}
public void destroy() {
this.destroy();
}
public void init(FilterConfig config) throws ServletException {
this.singleSignOutEndpoint=config.getInitParameter("singleSignOutEndpoint");
log.debug(" init.");
}
}

View File

@ -1,40 +0,0 @@
# General Log Settings
#log4j.rootLogger=INFO,LOGFILE,stdout
log4j.rootLogger=INFO,LOGFILE,stdout
#appender config:stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%c:%p %X %L] %m%n
#log4j.appender.stdout.layout.ConversionPattern=%-d{HH:mm:ss.SSS} [%c:%p %X{$UserName$} %L] %m%n
#appender config:LOGFILE
# log file arrcoss file size
log4j.appender.LOGFILE=org.apache.log4j.RollingFileAppender
#log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.LOGFILE.DatePattern=.yyyy-MM-dd
log4j.appender.LOGFILE.File=${catalina.home}/logs/maxkey_client_out.log
log4j.appender.LOGFILE.maxFileSize=2048KB
log4j.appender.LOGFILE.MaxBackupIndex = 5
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%c:%p] %m%n
log4j.appender.DEBUG=org.apache.log4j.RollingFileAppender
log4j.appender.DEBUG.File=${catalina.home}/logs/maxkey_client_debug.log
log4j.appender.DEBUG.maxFileSize=2048KB
log4j.appender.DEBUG.MaxBackupIndex = 5
log4j.appender.DEBUG.DatePattern=.yyyy-MM-dd
log4j.appender.DEBUG.layout=org.apache.log4j.PatternLayout
log4j.appender.DEBUG.layout.ConversionPattern=[%c:%p %X %L] %m%n
#log4j.appender.ERROR=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.ERROR.DatePattern=.yyyy-MM-dd
log4j.appender.ERROR=org.apache.log4j.RollingFileAppender
log4j.appender.ERROR.File=${catalina.home}/logs/maxkey_client_error.log
log4j.appender.ERROR.maxFileSize=2048KB
log4j.appender.ERROR.MaxBackupIndex = 5
log4j.appender.ERROR.layout=org.apache.log4j.PatternLayout
log4j.appender.ERROR.layout.ConversionPattern=[%c:%p %X %L] %m%n

View File

@ -1,85 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.test;
import java.util.*;
import org.maxkey.client.http.HttpVerb;
import org.maxkey.client.http.Response;
import org.maxkey.client.oauth.builder.ServiceBuilder;
import org.maxkey.client.oauth.builder.api.MaxkeyApi20;
import org.maxkey.client.oauth.model.OAuthRequest;
import org.maxkey.client.oauth.model.Token;
import org.maxkey.client.oauth.model.Verifier;
import org.maxkey.client.oauth.oauth.OAuthService;
public class MaxKey20Example
{
private static final String NETWORK_NAME = "SinaWeibo";
private static final String PROTECTED_RESOURCE_URL = "https://api.weibo.com/2/account/get_uid.json";
private static final Token EMPTY_TOKEN = null;
public static void main(String[] args)
{
// Replace these with your own api key and secret
String apiKey = "your_api_key";
String apiSecret = "your_api_secret";
OAuthService service = new ServiceBuilder()
.provider(MaxkeyApi20.class)
.apiKey(apiKey)
.apiSecret(apiSecret)
.callback("http://www.dajie.com/oauth/sina")
.build();
Scanner in = new Scanner(System.in);
System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
System.out.println();
// Obtain the Authorization URL
System.out.println("Fetching the Authorization URL...");
String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
System.out.println("Got the Authorization URL!");
System.out.println("Now go and authorize Scribe here:");
System.out.println(authorizationUrl);
System.out.println("And paste the authorization code here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verifier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken + " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(HttpVerb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getCode());
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with Scribe! :)");
}
}

View File

@ -1,53 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.oauth.test;
import org.maxkey.client.http.Response;
import org.maxkey.client.oauth.builder.api.MaxkeyPasswordApi20;
import org.maxkey.client.oauth.model.OAuthConfig;
import org.maxkey.client.oauth.model.Token;
import org.maxkey.client.oauth.oauth.OAuthPasswordService;
public class MaxkeyPasswordDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String accessTokenUrl="http://localhost:8080/opensec/oauth/v20/token";
String clientId = "e6bfadbfc1d64d0e9140a716548c35db";
String clientSerect = "e6bfadbfc1d64d0e9140a716548c35db";
String callback = "http://localhost:8080/oauth1demo/oauth20callback.jsp";
String responseType ="token";
String approvalprompt = "auto";
OAuthConfig oauthServiceConfig=new OAuthConfig(clientId,clientSerect,callback);
MaxkeyPasswordApi20 ConnsecPasswordApi20=new MaxkeyPasswordApi20(accessTokenUrl);
OAuthPasswordService oAuthPasswordService=new OAuthPasswordService(oauthServiceConfig,ConnsecPasswordApi20);
Token accessToken = null;
Response response = null;
accessToken = oAuthPasswordService.getAccessToken("6ac07a3d-b935-43f2-a693-9ce49b6695b7", "1qaz2wsx");
}
}

View File

@ -1,25 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
/**
* @author Administrator
*
*/
package org.maxkey.client.oauth.test;

View File

@ -1,44 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.client.utils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
public class URLTest {
/**
* @param args
* @throws UnsupportedEncodingException
*/
public static void main(String[] args) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
//String encoderString="/bi/QvAJAXZfc/opendoc.htm?document=康缘药业经营决策分析 .qvw&host=QVS@bi-server51";
String encoderString="康缘药业经营决策分析 .qvw";
encoderString=URLEncoder.encode(encoderString,"UTF-8");
System.out.println(encoderString);
String decoderString="/bi/QvAJAXZfc/opendoc.htm?document=%E5%BA%B7%E7%BC%98%E8%8D%AF%E4%B8%9A%E7%BB%8F%E8%90%A5%E5%86%B3%E7%AD%96%E5%88%86%E6%9E%90.qvw&host=QVS%40bi-server51";
decoderString=URLDecoder.decode(decoderString,"UTF-8");
System.out.println(decoderString);
}
}

View File

@ -1,25 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
/**
* @author Administrator
*
*/
package org.maxkey.client.utils;

View File

@ -1,51 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.rest;
import java.util.HashMap;
import org.junit.Test;
import org.maxkey.client.oauth.OAuthClient;
import org.maxkey.client.oauth.model.Token;
import org.maxkey.client.utils.JsonUtils;
public class RestClientTest {
//@Test
public void main() {
OAuthClient tokenRestClient=new OAuthClient("https://exmail.qq.com/cgi-bin/token");
tokenRestClient.addParameter("grant_type", "client_credentials");
tokenRestClient.addBasicAuthorization("maxkey", "66199e4c36b6dfcfb6f1ebceda789432");
Token token =tokenRestClient.requestAccessToken();
System.out.println(token);
OAuthClient authkeyRestClient=new OAuthClient("http://openapi.exmail.qq.com:12211/openapi/mail/authkey");
authkeyRestClient.addBearerAuthorization(token.getAccess_token());
authkeyRestClient.addParameter("Alias", "test@maxkey.org");
HashMap authKey=JsonUtils.gson2Object(authkeyRestClient.execute().getBody(), HashMap.class);
String login_url="https://exmail.qq.com/cgi-bin/login?fun=bizopenssologin&method=bizauth&agent=%s&user=%s&ticket=%s";
System.out.println(String.format(login_url, "connsec","test@maxkey.org",authKey.get("auth_key")));
//https://exmail.qq.com/cgi-bin/login?fun=bizopenssologin&method=bizauth&agent=connsec&user=test@connsec.com&ticket=25640C491CA4A056BD1A936C6AA4ABBCAB13AE76EB80E6C3A9259F5E8BFD91D7EA05D10DA3FB18F9BFB445D104CB58A0B4CDE97D9F219F3C
}
}

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/>
</classpath>

View File

@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>maxkey-connectors</name>
<comment>Project maxkey-connectors created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.boot.validation.springbootbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>

View File

@ -1,36 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="bin/main" path="src/main/java">
<attributes>
<attribute name="gradle_scope" value="main"/>
<attribute name="gradle_used_by_scope" value="main,test"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="bin/main" path="src/main/resources">
<attributes>
<attribute name="gradle_scope" value="main"/>
<attribute name="gradle_used_by_scope" value="main,test"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="bin/test" path="src/test/java">
<attributes>
<attribute name="gradle_scope" value="test"/>
<attribute name="gradle_used_by_scope" value="test"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="bin/test" path="src/test/resources">
<attributes>
<attribute name="gradle_scope" value="test"/>
<attribute name="gradle_used_by_scope" value="test"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer">
<attributes>
<attribute name="org.eclipse.jst.component.nondependency" value=""/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="bin/default"/>
</classpath>

View File

@ -1,41 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>maxkey-connector-activedirectory</name>
<comment>Project maxkey-connectors-activedirectory created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.boot.validation.springbootbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>

View File

@ -1,2 +0,0 @@
connection.project.dir=../..
eclipse.preferences.version=1

View File

@ -1,2 +0,0 @@
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@ -1,14 +0,0 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.builder.cleanOutputFolder=clean
org.eclipse.jdt.core.builder.duplicateResourceTask=warning
org.eclipse.jdt.core.builder.invalidClasspath=abort
org.eclipse.jdt.core.builder.recreateModifiedClassFileInOutputFolder=ignore
org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch
org.eclipse.jdt.core.circularClasspath=warning
org.eclipse.jdt.core.classpath.exclusionPatterns=enabled
org.eclipse.jdt.core.classpath.mainOnlyProjectHasTestOnlyDependency=error
org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled
org.eclipse.jdt.core.classpath.outputOverlappingAnotherSource=error
org.eclipse.jdt.core.compiler.maxProblemPerUnit=100
org.eclipse.jdt.core.incompatibleJDKLevel=ignore
org.eclipse.jdt.core.incompleteClasspath=error

View File

@ -1,3 +0,0 @@
eclipse.preferences.version=1
org.eclipse.jdt.launching.PREF_COMPILER_COMPLIANCE_DOES_NOT_MATCH_JRE=warning
org.eclipse.jdt.launching.PREF_STRICTLY_COMPATIBLE_JRE_NOT_AVAILABLE=warning

View File

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="maxkey-connector-activedirectory">
<wb-resource deploy-path="/" source-path="src/main/resources"/>
<wb-resource deploy-path="/" source-path="src/main/java"/>
<dependent-module deploy-path="../" handle="module:/resource/maxkey-core/maxkey-core">
<dependency-type>uses</dependency-type>
</dependent-module>
<dependent-module deploy-path="../" handle="module:/resource/maxkey-persistence/maxkey-persistence">
<dependency-type>uses</dependency-type>
</dependent-module>
<dependent-module deploy-path="../" handle="module:/resource/maxkey-client-sdk/maxkey-client-sdk">
<dependency-type>uses</dependency-type>
</dependent-module>
<dependent-module deploy-path="../" handle="module:/resource/maxkey-connector-base/maxkey-connector-base">
<dependency-type>uses</dependency-type>
</dependent-module>
<dependent-module deploy-path="../" handle="module:/resource/maxkey-identity-kafka/maxkey-identity-kafka">
<dependency-type>uses</dependency-type>
</dependent-module>
</wb-module>
</project-modules>

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<fixed facet="jst.java"/>
<installed facet="jst.utility" version="1.0"/>
<installed facet="jst.java" version="1.8"/>
</faceted-project>

Some files were not shown because too many files have changed in this diff Show More