参考:
https://developer.linkedin.com/docs/oauth2
https://developer.linkedin.com/docs/signin-with-linkedin
准备工作:
注册一个开发号在创建一个Web应用,网址: https://www.linkedin.com/developer/apps
需求:点击使用linkedIn登录图标,调转到linkedIn授权页面。点击允许登录网址。
开发:
第一步获取Code:
Controller:
@RequestMapping(value = "/toLogin")
public void weixinLogin(HttpServletRequest request,HttpServletResponse response){
String appid=PropertiesUtils.getProperty("system.linkedIn.clientId");
int serverPost = request.getServerPort();
String basePath = null;
if(serverPost==80){
basePath = request.getScheme()+"://"+request.getServerName()+request.getContextPath();
}else{
basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
}
String redirectUri=basePath+"/linkedIn/loginProcess";
String code="code";
String state=MyTools.generateString(20);
HttpSession session = request.getSession();
session.setAttribute("linkcode", state);
String baseUrl="https://www.linkedin.com/oauth/v2/authorization";
linkedInHelper.toLoginPage(baseUrl, appid, redirectUri, code, "", state,response);
}
public boolean toLoginPage(String baseUrl,String clientId,String redirectUri,String code,String scope,String state,HttpServletResponse response){
try {
String redirectUriCode = URLEncoder.encode(redirectUri,"utf-8");//坑1
baseUrl+="?client_id="+clientId+"&redirect_uri="+redirectUriCode+"&response_type="+code+"&scope="+scope+"&state="+state+"&format=json";
try {
response.sendRedirect(baseUrl);
} catch (IOException e) {
log.error("URLEncoder重定向地址失败,请求取消");
e.printStackTrace();
return false;
}
return true;
} catch (UnsupportedEncodingException e) {
log.error("URLEncoder重定向地址失败,请求取消");
e.printStackTrace();
return false;
}
}
第二步获取Token,然后获取用户信息登录网址:
@RequestMapping(value = "/loginProcess")
public ModelAndView LoginProcess( HttpServletRequest request){
ModelAndView mav=new ModelAndView();
String code=request.getParameter("code");
String status=request.getParameter("state");
String tempCode=(String)request.getSession().getAttribute("linkcode");
request.getSession().removeAttribute("linkcode");
/*防止跨站攻击*/
if(null==tempCode||null==status||!tempCode.trim().equalsIgnoreCase(status.trim())){
mav.setViewName("/error404");
mav.addObject("msg", "疑似跨站攻击");
return mav;
}
/*判断第一步是否得到Code*/
if(MyTools.isEmptyStr(code)){
//登录失败处理
mav.setViewName("/error404");
String errorDes=request.getParameter("error_description");
mav.addObject("msg",errorDes);
return mav;
}else{
String appid=PropertiesUtils.getProperty("system.linkedIn.clientId");
String secret=PropertiesUtils.getProperty("system.linkedIn.clientSecret");
String getTokenUrl="https://www.linkedin.com/oauth/v2/accessToken";
int serverPost = request.getServerPort();
String basePath = null;
if(serverPost==80){
basePath = request.getScheme()+"://"+request.getServerName()+request.getContextPath();
}else{
basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
}
String redirectUri=basePath+"/linkedIn/loginProcess";
JSONObject tokenInfo=linkedInHelper.getAccessToken(getTokenUrl, appid, secret, code, "authorization_code", redirectUri);
if(null==tokenInfo){
mav.setViewName("/error404");
mav.addObject("msg", "HTTP请求出错!");
return mav;
}
if(!tokenInfo.containsKey("access_token")){
/*获取Token失败处理*/
//登录失败处理
mav.setViewName("/error404");
mav.addObject("msg","获取令牌失败");
return mav;
}else{
/*用Token获取用户信息*/
String accessToken=tokenInfo.getString("access_token");
if(MyTools.isEmptyStr(accessToken)){
/*获取Token失败处理*/
//登录失败处理
mav.setViewName("/error404");
mav.addObject("msg","获取令牌失败");
return mav;
}
String getUserInfoUrl="https://api.linkedin.com/v1/people/~";
JSONObject userInfo=linkedInHelper.getUserInfo(getUserInfoUrl, accessToken);
if(!userInfo.containsKey("id")){
/*获取信息失败*/
mav.setViewName("/error404");
mav.addObject("msg", tokenInfo.get("errmsg"));
return mav;
}else{
/*获取信息成功*/
//保存用户
UserInfo user=new UserInfo();
user.setName(userInfo.getString("firstName")+" "+userInfo.getString("lastName"));
user.setUid(userInfo.getString("id"));
user.setLinkedInId(userInfo.getString("id"));
user.setCreateDate(new Date());
user.setEnabled(1);
user.setType(1);
user.setRegisterSource(2);
user.setRegisterCode(MyTools.generateString(30));
userService.saveUserInfo(user);
InsideUsernamePasswordToken token = new InsideUsernamePasswordToken();
token.setUsername(userInfo.getString("id"));
//****—****#####登录处理代码
token.setRememberMe(false);
Subject subject = SecurityUtils.getSubject();
subject.login(token);
mav.setViewName("redirect:/index");
return mav;
}
}
}
}
/**
* 获取令牌
* @param baseUrl
* @param clientId
* @param secret
* @param code 第一步中得到的
* @param grantType 填authorization_code
* @param redirectUri
* @return access_token and expires_in
* 创建时间:2016年11月9日 下午2:11:11
*/
public JSONObject getAccessToken(String baseUrl,String clientId,String secret,String code,String grantType,String redirectUri){
try {
String redirectUriCode = URLEncoder.encode(redirectUri,"utf-8");//对应坑1
baseUrl+="?client_id="+clientId+"&client_secret="+secret+"&code="+code+"&grant_type="+grantType+"&redirect_uri="+redirectUriCode+"&format=json";
String resultJson=HttpHelper.doPostForLinkedIn(baseUrl,"");
return JSONObject.parseObject(resultJson);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
/**
* 获取用户的基本信息
* @param baseUrl
* @param accessToken
* @return
* 创建时间:2016年11月9日 下午3:29:29
*/
public JSONObject getUserInfo(String baseUrl,String accessToken){
String resultJson=HttpHelper.doGet(baseUrl+"?"+"format=json","Bearer "+accessToken);//坑2,token放到这里
return JSONObject.parseObject(resultJson);
}
public static String doGet(String strURL,String authorizationStr){
String result="";
try{
URL url = new URL(strURL);// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("GET"); // 设置请求方式
connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
connection.setRequestProperty("Authorization",authorizationStr);//对应坑2,token放到这里
connection.connect();
// 处理响应数据
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} finally {
if(in!=null) in.close();
}
}catch(Exception e){
StackTraceElement stes[]=e.getStackTrace();
log.info(HttpHelper.class.toString()+"function:doGet");
log.info("---------------------http请求地址-----------------------");
log.info(strURL);
log.info("---------------------http请求内容-----------------------");
log.info(result);
for(StackTraceElement ste:stes){
log.error(ste.getFileName()+":"+ste.getLineNumber()+":"+ste.getMethodName());
}
}
return result;
}
public static String doPostForLinkedIn(String strURL, String jsonParams){
String result = "";
try{
URL url = new URL(strURL);// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
// connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST"); // 设置请求方式
//坑3 application/x-www-form-urlencoded
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置发送数据的格式
connection.connect();
PrintWriter out = new PrintWriter(connection.getOutputStream());
System.out.println("helper==="+jsonParams+"===");
try {
out.print(jsonParams);
out.flush();
} finally {
if(out!=null) out.close();
}
// 处理响应数据
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} finally {
if(in!=null) in.close();
}
}catch(Exception e){
log.info(HttpHelper.class.toString());
log.info("---------------------http请求地址-----------------------");
log.info(strURL);
log.info("---------------------http请求内容-----------------------");
log.info(result);
StackTraceElement stes[]=e.getStackTrace();
for(StackTraceElement ste:stes){
log.error(ste.getFileName()+":"+ste.getLineNumber()+":"+ste.getMethodName());
}
e.printStackTrace();
}
return result;
}