package coral.oauth2.web;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.request.OAuthAuthzRequest;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.apache.oltu.oauth2.common.message.types.ParameterStyle;
import org.apache.oltu.oauth2.common.message.types.ResponseType;
import org.apache.oltu.oauth2.common.utils.OAuthUtils;
import org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest;
import org.apache.oltu.oauth2.rs.response.OAuthRSResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.wondersgroup.ybServices.HttpApiClient;
import tw.tool.helper.LogHelper;
import coral.oauth2.bean.Oauth2Client;
import coral.oauth2.service.ClientService;
import coral.oauth2.service.OAuth2Service;
import coral.oauth2.view.UserInfo;
@Controller
public class OAuth2Controllers {
// 資源服務器的名稱
public static String RESOURCE_SERVER_NAME = "ac-oauth2";
// 驗證失敗提示
public static final String INVALID_CLIENT_DESCRIPTION = "failed, maybe the client_id or client_secret invalid";
@Autowired
private OAuth2Service auth2Service;
@Autowired
private ClientService clientService;
@SuppressWarnings({ "unchecked", "rawtypes" })
@RequestMapping("authorize.do")
public Object authorize(HttpServletRequest request, HttpServletResponse response)
throws URISyntaxException, OAuthSystemException {
try {
// 構建OAuth 授權請求
OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);
// 檢查傳入的客戶端id是否正確
//請求的Id去表里查詢有沒有
if (!auth2Service.checkClientId(oauthRequest.getClientId())) {
// 生成錯誤信息
OAuthResponse responseError = OAuthASResponse
.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
.setError(OAuthError.TokenResponse.INVALID_CLIENT)
.setErrorDescription(INVALID_CLIENT_DESCRIPTION)
.buildJSONMessage();
return new ResponseEntity(responseError.getBody(),
HttpStatus.valueOf(responseError.getResponseStatus()));
}
Subject subject = SecurityUtils.getSubject();
// 如果用戶沒有登錄,跳轉到登陸頁面
//isAuthenticated 屬性是布爾值,登錄為true
if (!subject.isAuthenticated()) {
if (!login(subject, request)) {// 登錄失敗時跳轉到登陸頁面
LogHelper.info("S:進入服務端authorize,登錄失敗時跳轉到登陸頁面");
return new ModelAndView("******.jsp");
}
}
//SecurityUtils.getSubject().getPrincipal(); 獲取登錄的用戶信息
String userName = (String) subject.getPrincipal();
// UserInfo userInfo =
// onetUserService.getUserInfoByUserName(userName);
UserInfo userInfo = new UserInfo();
userInfo.setStUserName(userName);
// 生成授權碼
String authorizationCode = null;
// responseType目前僅支持CODE,另外還有TOKEN
String responseType = oauthRequest
.getParam(OAuth.OAUTH_RESPONSE_TYPE);
if (responseType.equals(ResponseType.CODE.toString())) {
OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(
new MD5Generator());
//授權碼
authorizationCode = oauthIssuerImpl.authorizationCode();
// 把授權碼放進緩存中
auth2Service.addAuthCode(authorizationCode, userInfo);
}
// 進行OAuth響應構建
OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse
.authorizationResponse(request, HttpServletResponse.SC_FOUND);
// 設置授權碼
builder.setCode(authorizationCode);
// 得到到客戶端重定向地址
String redirectURI = oauthRequest
.getParam(OAuth.OAUTH_REDIRECT_URI);
// 構建響應
final OAuthResponse responseError = builder.location(redirectURI)
.buildQueryMessage();
// 根據OAuthResponse返回ResponseEntity響應
HttpHeaders headers = new HttpHeaders();
headers.setLocation(new URI(responseError.getLocationUri()));
LogHelper.info("S:進入服務端authorize,發送授權碼authorizationCode="
+ authorizationCode);
return new ResponseEntity(headers, HttpStatus.valueOf(responseError
.getResponseStatus()));
} catch (OAuthProblemException e) {
// 出錯處理
String redirectUri = e.getRedirectUri();
if (OAuthUtils.isEmpty(redirectUri)) {
// 告訴客戶端沒有傳入redirectUri直接報錯
return new ResponseEntity("not found redirect_uri",
HttpStatus.NOT_FOUND);
}
// 返回錯誤消息(如?error=)
final OAuthResponse responseError = OAuthASResponse
.errorResponse(HttpServletResponse.SC_FOUND).error(e)
.location(redirectUri).buildQueryMessage();
HttpHeaders headers = new HttpHeaders();
headers.setLocation(new URI(responseError.getLocationUri()));
return new ResponseEntity(headers, HttpStatus.valueOf(responseError
.getResponseStatus()));
}
}
/**
* 獲取用戶令牌
*
* @param request
* @return
* @throws URISyntaxException
* @throws OAuthSystemException
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@RequestMapping("/access_token.do")
public HttpEntity access_token(HttpServletRequest request)
throws URISyntaxException, OAuthSystemException {
try {
// 構建OAuth請求
OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);
// 檢查提交的客戶端id是否正確 和數據庫對比
if (!auth2Service.checkClientId(oauthRequest.getClientId())) {
OAuthResponse response = OAuthASResponse
.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
.setError(OAuthError.TokenResponse.INVALID_CLIENT)
.setErrorDescription(INVALID_CLIENT_DESCRIPTION)
.buildJSONMessage();
return new ResponseEntity(response.getBody(),
HttpStatus.valueOf(response.getResponseStatus()));
}
// 檢查客戶端安全KEY是否正確
if (!auth2Service.checkClientSecret(oauthRequest.getClientSecret())) {
OAuthResponse response = OAuthASResponse
.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
.setError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT)
.setErrorDescription(INVALID_CLIENT_DESCRIPTION)
.buildJSONMessage();
return new ResponseEntity(response.getBody(),
HttpStatus.valueOf(response.getResponseStatus()));
}
String authCode = oauthRequest.getParam(OAuth.OAUTH_CODE);
UserInfo userInfo = null;
// 檢查驗證類型,此處只檢查AUTHORIZATION_CODE類型,其他的還有PASSWORD或REFRESH_TOKEN
if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(
GrantType.AUTHORIZATION_CODE.toString())) {
if (!auth2Service.checkAuthCode(authCode)) {
OAuthResponse response = OAuthASResponse
.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
.setError(OAuthError.TokenResponse.INVALID_GRANT)
.setErrorDescription("錯誤的授權碼").buildJSONMessage();
return new ResponseEntity(response.getBody(),
HttpStatus.valueOf(response.getResponseStatus()));
}
userInfo = auth2Service.getUserInfoByAuthCode(authCode);
} else if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(
GrantType.CLIENT_CREDENTIALS.toString())) {
Oauth2Client oClient = clientService
.findByClientId(oauthRequest.getClientId());
userInfo = new UserInfo();
userInfo.setStUserName(oClient.getStClientId());
userInfo.setStName(oClient.getStClientName());
} else {
OAuthResponse response = OAuthASResponse
.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
.setError(OAuthError.TokenResponse.INVALID_GRANT)
.setErrorDescription("grant_type不正確")
.buildJSONMessage();
return new ResponseEntity(response.getBody(),
HttpStatus.valueOf(response.getResponseStatus()));
}
// 生成Access Token
OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(
new MD5Generator());
final String accessToken = oauthIssuerImpl.accessToken();
auth2Service.addAccessToken(accessToken, userInfo);
// 生成OAuth響應
OAuthResponse response = OAuthASResponse
.tokenResponse(HttpServletResponse.SC_OK)
.setAccessToken(accessToken)
.setExpiresIn(String.valueOf(auth2Service.getExpireIn()))
.buildJSONMessage();
LogHelper.info("S:認證服務器生成令牌Access Token=" + accessToken);
HttpHeaders headers = new HttpHeaders();
headers.add("Access-Control-Allow-Origin", "*");
// 根據OAuthResponse生成ResponseEntity
return new ResponseEntity(response.getBody(), headers,
HttpStatus.valueOf(response.getResponseStatus()));
} catch (OAuthProblemException e) {
e.printStackTrace();
// 構建錯誤響應
OAuthResponse res = OAuthASResponse
.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e)
.buildJSONMessage();
return new ResponseEntity(res.getBody(), HttpStatus.valueOf(res
.getResponseStatus()));
}
}
/**
* 獲取授權信息
*
* @param request
* @return
* @throws OAuthSystemException
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping("/userinfo.do")
public HttpEntity userinfo(HttpServletRequest request)
throws OAuthSystemException {
try {
// 構建OAuth資源請求(遠程的可以使用自定義接口)
OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest(
request, ParameterStyle.QUERY);
// 獲取Access Token
String accessToken = oauthRequest.getAccessToken();
// 驗證Access Token
LogHelper.info("Z:資源服務器驗證令牌");
if (!auth2Service.checkAccessToken(accessToken)) {
// 如果不存在/過期了,返回未驗證錯誤,需重新驗證
OAuthResponse oauthResponse = OAuthRSResponse
.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
.setRealm(RESOURCE_SERVER_NAME)
.setError(OAuthError.ResourceResponse.INVALID_TOKEN)
.buildHeaderMessage();
HttpHeaders headers = new HttpHeaders();
headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse
.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
return new ResponseEntity(headers, HttpStatus.UNAUTHORIZED);
}
// 返回客戶端資源
UserInfo userInfo = auth2Service
.getUserInfoByAccessToken(accessToken);
LogHelper.info("Z:訪問資源控制器,並返回授權限的資源");
JSONObject object = JSONObject.fromObject(userInfo);
HttpHeaders headers = new HttpHeaders();
headers.add("Access-Control-Allow-Origin", "*");
MediaType mediaType = new MediaType("text", "html",
Charset.forName("utf-8"));
headers.setContentType(mediaType);
return new ResponseEntity(object.toString(), headers, HttpStatus.OK);
} catch (OAuthProblemException e) {
// 檢查是否設置了錯誤碼
String errorCode = e.getError();
if (OAuthUtils.isEmpty(errorCode)) {
OAuthResponse oauthResponse = OAuthRSResponse
.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
.setRealm(RESOURCE_SERVER_NAME).buildHeaderMessage();
HttpHeaders headers = new HttpHeaders();
headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse
.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
return new ResponseEntity(headers, HttpStatus.UNAUTHORIZED);
}
OAuthResponse oauthResponse = OAuthRSResponse
.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
.setRealm(RESOURCE_SERVER_NAME).setError(e.getError())
.setErrorDescription(e.getDescription())
.setErrorUri(e.getUri()).buildHeaderMessage();
HttpHeaders headers = new HttpHeaders();
headers.add(OAuth.HeaderType.WWW_AUTHENTICATE,
oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
/**
* 用戶登錄
*
* @param subject
* @param request
* @return
*/
private boolean login(Subject subject, HttpServletRequest request) {
// if ("get".equalsIgnoreCase(request.getMethod())) {
// return false;
// }
// String username = request.getParameter("username");
// String password = request.getParameter("password");
//
// if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
// return false;
// }
//
// UsernamePasswordToken token = new UsernamePasswordToken(username,
// password);
// try {
// subject.login(token);// 沿着用戶登錄
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// request.setAttribute("error", "login failed:"
// + e.getClass().getName());
// return false;
// }
return false;
}
}