Commit b69c241c by win7

路径替换

parents
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/
\ No newline at end of file
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip
**知微数据授权登录中间件说明**
---
授权登录 说明文档
---
* **项目地址**>http://192.168.0.36:9090/ycy/AuthorizeLogin.git
---
+ **登录接口**
- 微博>http://login.zhiweidata.com/WeiboLogin
请求参数|必须|类型|说明
:----|:----|:----|:----
yoururl|true|string|授权登录后携带token及uid 或 授权登录取消后携带error_code返回的地址
返回数据|类型|说明
:----|:----|:----
token|string| (微博API中的access_token)用户授权的唯一票据,用于调用微博开放接口
uid|string|(微博API中的uid)授权用户的UID
取消登录返回数据|类型|说明
:----|:----|:----
error_code|string| 在用户取消授权后返回yoururl的错误代码
- QQ>http://login.zhiweidata.com/QQLogin
请求参数|必须|类型|说明
:----|:----|:----|:----
yoururl|true|string|授权登录成功后携带token及uid返回的地址
返回数据|类型|说明
:----|:----|:----
token|string|(QQAPI中的access_token)用户授权的唯一票据,授权令牌
uid|string|(QQAPI中的openid)是此网站上唯一对应用户身份的标识
- 微信(未实现,缺少开发者权限)
---
+ **yoururl如何获取到登录信息?**
- 登录完毕以后会跳转到yoururl?token=xxxx&uid=xxxxx
\ No newline at end of file
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
echo $MAVEN_PROJECTBASEDIR
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zhiwei</groupId>
<artifactId>AuthorizeLogin</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>AuthorizeLogin</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.7.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- httpClient -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<!-- httpClient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-cache</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<!-- jsoup 解析包 -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.8.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.33</version>
</dependency>
<!-- servlet jar -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- weibojar -->
<dependency>
<groupId>com.zhiwei</groupId>
<artifactId>weibobusiness</artifactId>
<version>0.0.5-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<finalName>AuthorizeLogin</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.zhiwei;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AuthorizeLoginApplication {
public static void main(String[] args) {
SpringApplication.run(AuthorizeLoginApplication.class, args);
}
}
package com.zhiwei.Tool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GetQQOpenUrl {
private static final Logger logger = LoggerFactory.getLogger(GetQQOpenUrl.class);
/**
* Step1地址 获取code
*
* @param getCodeUrl
* @param response_type
* @param client_id
* @param redirect_uri
* @param state
* @return
*/
public String getUrl(String getCodeUrl, String response_type, String client_id, String redirect_uri, String state) {
StringBuilder url = new StringBuilder();
url.append(getCodeUrl);
url.append("authorize?response_type=");
url.append(response_type);
url.append("&client_id=");
url.append(client_id);
url.append("&redirect_uri=");
url.append(redirect_uri);
url.append("&state=");
url.append(state);
logger.info("请求授权登录url:" + url);
return url.toString();
}
/**
* Step2地址 获取access_token
*
* @param getCodeUrl
* @param grant_type
* @param client_id
* @param client_secret
* @param code
* @param redirect_uri
* @return
*/
public String getTokenUrl(String getCodeUrl, String grant_type, String client_id, String client_secret, String code,
String redirect_uri) {
StringBuilder url = new StringBuilder();
url.append(getCodeUrl);
url.append("token?grant_type=");
url.append(grant_type);
url.append("&client_id=");
url.append(client_id);
url.append("&client_secret=");
url.append(client_secret);
url.append("&code=");
url.append(code);
url.append("&redirect_uri=");
url.append(redirect_uri);
url.append("/token");
logger.info("请求success_tokend的url:" + url);
return url.toString();
}
/**
* Step3地址 获取open_id
*
* @param getCodeUrl
* @param access_token
* @return
*/
public String getOpenIDUrl(String getCodeUrl, String access_token) {
StringBuilder url = new StringBuilder();
url.append(getCodeUrl);
url.append("me?access_token=");
url.append(access_token);
logger.info("请求openid的url:" + url);
return url.toString();
}
}
package com.zhiwei.Tool;
import com.zhiwei.weibobusiness.weibo4j.Oauth;
import com.zhiwei.weibobusiness.weibo4j.Users;
import com.zhiwei.weibobusiness.weibo4j.model.User;
import com.zhiwei.weibobusiness.weibo4j.model.WeiboException;
import com.zhiwei.weibobusiness.weibo4j.util.BareBonesBrowserLaunch;
import com.zhiwei.weibobusiness.weibo4j.util.WeiboConfig;
//获取微博授权登录地址
public class GetWeiboOpenUrl {
/**
* @Title: openul
* @Description: 后台调用浏览器打开制定路径 设定文件
* @return code从回调地址中取
*/
public void openul() {
Oauth oauth = new Oauth();
try {
BareBonesBrowserLaunch.openURL(oauth.authorize("code"));
} catch (WeiboException e) {
Log.logInfo("Unable to open the weibologinURL.");
e.printStackTrace();
}
}
/**
* @Title: openulbyown
* @Description: 通过自己给网址在浏览器中打开 seturl String
* @return void 返回类型
*/
public void openulbyown(String seturl) {
BareBonesBrowserLaunch.openURL(seturl);
}
/**
* @Title: seturl
* @Description: 自定义路径
* @param clientID
* @param redirectURI
* @param responsetype
* @return 设定文件
* @return String url
*/
public String seturl(String clientID, String redirectURI, String responsetype) {
Oauth oauth = new Oauth();
String url = null;
try {
WeiboConfig.updateProperties("client_ID", clientID);
WeiboConfig.updateProperties("redirect_URI", redirectURI);
url = oauth.authorize(responsetype);
} catch (WeiboException e) {
Log.logInfo("Unable to set the weibologinURL.");
e.printStackTrace();
}
return url;
}
/**
* @Title: getUser
* @Description: 通过token和uid得到user信息
* @param access_token
* @param uid
* @return 设定文件
* @return String 返回类型
*/
public String getUser(String access_token, String uid) {
Users um = new Users(access_token);
String usermessage = new String();
try {
User user = um.showUserById(uid);
usermessage = user.toString();
} catch (WeiboException e) {
e.printStackTrace();
}
return usermessage;
}
}
package com.zhiwei.Tool;
import org.apache.log4j.Logger;
public class Log {
static Logger log = Logger.getLogger(Log.class.getName());
public static void logDebug(String message) {
log.debug(message);
}
public static void logInfo(String message) {
log.info(message);
}
}
package com.zhiwei.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
//QQ配置类
@Component
@Configuration
@ConfigurationProperties(prefix = "qq")
@PropertySource(value = "qqlogin.properties")
public class QQConfig {
// https://graph.qq.com/oauth2.0/
private String getCodeUrl;
// 授权类型,值固定为"code"
private String responseType;
// 申请QQ登录成功后,分配给应用的appid
private String clientId;
// 申请QQ登录成功后,分配给网站的appkey
private String clientSecret;
// 成功授权后的回调地址,必须是注册appid时填写的主域名下的地址
private String redirectUri;
// client端的状态值
private String state;
// 授权类型
private String grantType;
public String getGetCodeUrl() {
return getCodeUrl;
}
public void setGetCodeUrl(String getCodeUrl) {
this.getCodeUrl = getCodeUrl;
}
public String getResponseType() {
return responseType;
}
public void setResponseType(String responseType) {
this.responseType = responseType;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public String getRedirectUri() {
return redirectUri;
}
public void setRedirectUri(String redirectUri) {
this.redirectUri = redirectUri;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getGrantType() {
return grantType;
}
public void setGrantType(String grantType) {
this.grantType = grantType;
}
}
package com.zhiwei.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
//微博配置类
@Component
@Configuration
@ConfigurationProperties(prefix = "weibo")
@PropertySource(value = "weibologin.properties")
public class WeiBoConfig {
// 申请应用时分配的AppKey
private String clientID;
// 申请应用时分配的AppSecret
private String clientSERCRET;
// 回调地址,需需与注册应用里的回调地址一致
private String redirectURI;
public String getRedirectURI() {
return redirectURI;
}
public void setRedirectURI(String redirectURI) {
this.redirectURI = redirectURI;
}
public String getClientID() {
return clientID;
}
public void setClientID(String clientID) {
this.clientID = clientID;
}
public String getClientSERCRET() {
return clientSERCRET;
}
public void setClientSERCRET(String clientSERCRET) {
this.clientSERCRET = clientSERCRET;
}
}
package com.zhiwei.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zhiwei.Tool.GetQQOpenUrl;
import com.zhiwei.config.QQConfig;
import com.zhiwei.entity.TokenEntity;
@SuppressWarnings("deprecation")
@RestController
public class QQLoginController {
@Autowired
private QQConfig config;
private static final Logger logger = LoggerFactory.getLogger(QQLoginController.class);
private GetQQOpenUrl getUrl = new GetQQOpenUrl();
private static String yoururl = null;
/**
* 登录接口
*
* @param response
* @param request
*/
@RequestMapping("/QQLogin")
public void Login(HttpServletResponse response, HttpServletRequest request) {
yoururl = request.getParameter("yoururl");
String url = getUrl.getUrl(config.getGetCodeUrl(), config.getResponseType(), config.getClientId(),
config.getRedirectUri(), config.getState());
try {
response.sendRedirect(url);
} catch (IOException e) {
logger.error("QQ授权登录请求发送失败,错误信息:{},错误位置:{}", e.getMessage(), e.getStackTrace());
}
}
/**
* 回调接口
*
* @param response
* @param request
*/
@SuppressWarnings({ "resource" })
@RequestMapping("/QQRecall")
public void Recall(HttpServletResponse response, HttpServletRequest request) {
// 取得code
String code = request.getParameter("code");
// QQ互联用
String url = null;
try {
/**
* 根据code取得access_token
*/
url = getUrl.getTokenUrl(config.getGetCodeUrl(), config.getGrantType(), config.getClientId(),
config.getClientSecret(), code, config.getRedirectUri());
String resultToken = "";
String resultOpenID = "";
// 根据地址获取请求
HttpGet httpGet = new HttpGet(url);// 这里发送get请求
// 获取当前客户端对象
HttpClient httpClient = new DefaultHttpClient();
// 通过请求对象获取响应对象
HttpResponse httpresponse = httpClient.execute(httpGet);
// 判断网络连接状态码是否正常(0--200都数正常)
if (httpresponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
resultToken = EntityUtils.toString(httpresponse.getEntity(), "utf-8");
}
// 返回数据示例access_token=540ED********EF70A&expires_in=7776000&refresh_token=F7F062*****3EC614
// System.out.println(resultToken);
// 将resultToken拆分
String[] datas = resultToken.split("&");
TokenEntity token = new TokenEntity();
token.setAccess_token(datas[0].split("=")[1]);
token.setExpires_in(datas[1].split("=")[1]);
token.setRefresh_token(datas[2].split("=")[1]);
/**
* 根据access_token获得open_id
*/
url = getUrl.getOpenIDUrl(config.getGetCodeUrl(), token.getAccess_token());
httpGet = new HttpGet(url);
httpresponse = httpClient.execute(httpGet);
if (httpresponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
resultOpenID = EntityUtils.toString(httpresponse.getEntity(), "utf-8");
}
// 返回数据示例callback(
// {"client_id":"10****67","openid":"BA8******************97848"} );
// System.out.println(resultOpenID);
// 截取openid
String openid = null;
if (resultOpenID.contains("openid")) {
int start = resultOpenID.indexOf("openid");
int end = resultOpenID.indexOf("}");
openid = resultOpenID.substring(start + 9, end - 1);
}
String sendurl = yoururl + "?token=" + token.getAccess_token() + "&uid=" + openid;
response.sendRedirect(sendurl);
} catch (Exception e) {
logger.error("QQ回调请求失败,错误信息:{},错误位置:{}", e.getMessage(), e.getStackTrace());
}
}
}
package com.zhiwei.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zhiwei.Tool.GetWeiboOpenUrl;
import com.zhiwei.config.WeiBoConfig;
import com.zhiwei.weibobusiness.weibo4j.Account;
import com.zhiwei.weibobusiness.weibo4j.Oauth;
import com.zhiwei.weibobusiness.weibo4j.model.WeiboException;
import com.zhiwei.weibobusiness.weibo4j.org.json.JSONException;
import com.zhiwei.weibobusiness.weibo4j.org.json.JSONObject;
//微博授权登录
@RestController
public class WeiboLoginController {
@Autowired
private WeiBoConfig config;
private static final Logger logger = LoggerFactory.getLogger(WeiboLoginController.class);
private static String yoururl;
// 登录页面
@RequestMapping(value = "/WeiboLogin")
public void Login(HttpServletResponse response, HttpServletRequest request) {
GetWeiboOpenUrl openurl = new GetWeiboOpenUrl();
// yoururl获取
yoururl = request.getParameter("yoururl");
// 请求授权地址生成
String seturl = openurl.seturl(config.getClientID(), config.getRedirectURI() + "?yoururl=" + yoururl, "code");
try {
response.sendRedirect(seturl);
} catch (IOException e) {
logger.error("微博授权登录请求发送失败,错误信息:{},错误位置:{}", e.getMessage(), e.getStackTrace());
}
}
// 回调
@RequestMapping(value = "/WeiboRecall")
public void Recall(HttpServletResponse response, HttpServletRequest request) {
String code = request.getParameter("code");
String yoururl = request.getParameter("yoururl");
String access_token = null;
String user_id = null;
// 登录成功,传回code
if (null != code && !code.equals("")) {
// 根据uid获取user_id
try {
Oauth oauth = new Oauth();
access_token = oauth.getAccessTokenByCode(code).getAccessToken();
Account am = new Account(access_token);
JSONObject uid = am.getUid();
user_id = uid.getString("uid");
} catch (JSONException | WeiboException e) {
logger.error("微博回调获取user_id失败,错误信息:{},错误位置:{}", e.getMessage(), e.getStackTrace());
}
try {
response.sendRedirect(yoururl + "?token=" + access_token + "&uid=" + user_id);
} catch (IOException e) {
logger.error("微博回调页面重定向失败,错误信息:{},错误位置:{}", e.getMessage(), e.getStackTrace());
}
}
// 取消登录,传回error_code
else
try {
String error_code = request.getParameter("error_code");
response.sendRedirect(yoururl + "?error_code=" + error_code);
logger.info("用户取消授权登录,页面跳转至yoururl");
} catch (IOException e) {
logger.error("微博用户取消登录失败,错误信息:{},错误位置:{}", e.getMessage(), e.getStackTrace());
}
}
}
package com.zhiwei.entity;
public class TokenEntity {
private String access_token;
// 有效时间
private String expires_in;
private String refresh_token;
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getExpires_in() {
return expires_in;
}
public void setExpires_in(String expires_in) {
this.expires_in = expires_in;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
@Override
public String toString() {
return "TokenEntity [access_token=" + access_token + ", expires_in=" + expires_in + ", refresh_token="
+ refresh_token + "]";
}
}
server.port=10000
\ No newline at end of file
#weibobusiness中使用
client_ID = 3176521415
client_SERCRET = 32a973bfd29abaea6d97b90419bb73bb
redirect_URI =http://login.zhiweidata.com/WeiboRecall
baseURL=https://api.weibo.com/2/
accessTokenURL=https://api.weibo.com/oauth2/access_token
authorizeURL=https://api.weibo.com/oauth2/authorize
rmURL=https://rm.api.weibo.com/2/
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!-- scan 配置文件如果发生改变,将会被重新加载 scanPeriod 检测间隔时间-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<contextName>spring-boot-log</contextName>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<!-- 普通日志 -->
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>log/spring-boot-log-info.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志命名:单个文件大于128MB 按照时间+自增i 生成log文件 -->
<fileNamePattern>log/spring-boot-log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>128MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!-- 最大保存时间:30天-->
<maxHistory>30</maxHistory>
</rollingPolicy>
<append>true</append>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern>
<charset>utf-8</charset>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>info</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 错误日志 -->
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>log/spring-boot-log-error.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志命名:单个文件大于2MB 按照时间+自增i 生成log文件 -->
<fileNamePattern>log/spring-boot-log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>10MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!-- 最大保存时间:180天-->
<maxHistory>180</maxHistory>
</rollingPolicy>
<append>true</append>
<!-- 日志格式 -->
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern>
<charset>utf-8</charset>
</encoder>
<!-- 日志级别过滤器 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>ERROR</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 控制台 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- 日志格式 -->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern>
<charset>utf-8</charset>
</encoder>
<!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
</appender>
<!-- additivity 避免执行2次 -->
<logger name="com.itstyle" level="INFO" additivity="false">
<appender-ref ref="STDOUT"/>
<appender-ref ref="INFO_FILE"/>
<appender-ref ref="ERROR_FILE"/>
</logger>
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="ERROR_FILE" />
</root>
</configuration>
\ No newline at end of file
#"_"连接改为首字母大写
#登录地址
qq.getCodeUrl=https://graph.qq.com/oauth2.0/
#授权类型,值固定为"code"
qq.responseType=code
#申请QQ登录成功后,分配给应用的appid
qq.clientId=101465900
#申请QQ登录成功后,分配给网站的appkey
qq.clientSecret=1a03ca07462a41081274312722bcd1ff
#成功授权后的回调地址,必须是注册appid时填写的主域名下的地址
qq.redirectUri =http://login.zhiweidata.com/QQRecall
#client端的状态值
qq.state=1
#授权类型
qq.grantType=authorization_code
\ No newline at end of file
weibo.clientID = 3176521415
weibo.clientSERCRET = 32a973bfd29abaea6d97b90419bb73bb
weibo.redirectURI = http://login.zhiweidata.com/WeiboRecall
\ No newline at end of file
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
</web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<body>
<h2>授权成功!</h2>
</body>
</html>
package com.zhiwei;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AuthorizeLoginApplicationTests {
@Test
public void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment