📄 openidprovider.java
字号:
/*
* Copyright 2005-2008 WSO2, Inc. (http://wso2.com) 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.wso2.solutions.identity.openid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletOutputStream;
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.openid4java.association.AssociationException;
import org.openid4java.message.AuthFailure;
import org.openid4java.message.AuthRequest;
import org.openid4java.message.AuthSuccess;
import org.openid4java.message.DirectError;
import org.openid4java.message.Message;
import org.openid4java.message.MessageException;
import org.openid4java.message.MessageExtension;
import org.openid4java.message.ParameterList;
import org.openid4java.message.sreg.SRegMessage;
import org.openid4java.server.ServerException;
import org.openid4java.server.ServerManager;
import org.wso2.solutions.identity.IdentityConstants;
import org.wso2.solutions.identity.IdentityProviderException;
import org.wso2.solutions.identity.openid.extensions.OpenIDExtension;
import org.wso2.solutions.identity.persistence.IPPersistenceManager;
import org.wso2.solutions.identity.persistence.dataobject.OpenIDUserRPDO;
import org.wso2.solutions.identity.openid.OpenIDExtensionFactory;
import org.wso2.utils.ServerConfiguration;
public class OpenIDProvider {
// Instantiate a ServerManager object.
public static final ServerManager manager = new OpenIDServerManager();
private String authPage;
private static Log log = LogFactory.getLog(OpenIDProvider.class);
private static String opAddress = null;
/**
* Configure the OpenID Provider's end-point URL.
*/
static {
ServerConfiguration serverConfig = null;
String openIDServerUrl = null;
serverConfig = ServerConfiguration.getInstance();
openIDServerUrl = serverConfig.getFirstProperty("OpenIDServerUrl");
// This is the OpenID provider server URL
opAddress = openIDServerUrl + "/server/";
manager.setOPEndpointUrl(opAddress);
}
/**
* Process the Relying Party request at the OpenID Provider end.
* @param httpReq HttpServletRequest
* @param httpResp HttpServletResponse
* @return The Url to be redirected
* @throws IdentityProviderException
*/
public String processRequest(HttpServletRequest httpReq,
HttpServletResponse httpResp) throws IdentityProviderException {
ParameterList request = null;
Message message = null;
String responseText = null;
HttpSession session = null;
try {
session = httpReq.getSession();
if (IdentityConstants.OpenId.COMPLETE.equals(httpReq
.getParameter(IdentityConstants.OpenId.ACTION))
|| IdentityConstants.OpenId.CANCEL.equals(httpReq
.getParameter(IdentityConstants.OpenId.ACTION))) {
// Authentication completed.
request = (ParameterList) session
.getAttribute(IdentityConstants.OpenId.PARAM_LIST);
} else {
// Extract the parameters from the request.
// Authentication not completed.
request = new ParameterList(httpReq.getParameterMap());
}
if (request == null)
throw new Exception("Invalid OpenID request");
String mode = request
.hasParameter(IdentityConstants.OpenId.ATTR_MODE) ? request
.getParameterValue(IdentityConstants.OpenId.ATTR_MODE)
: null;
if (IdentityConstants.OpenId.ASSOCIATE.equals(mode)) {
// Process an association request made by RP.
message = manager.associationResponse(request);
responseText = message.keyValueFormEncoding();
} else if (IdentityConstants.OpenId.CHECKID_SETUP.equals(mode)
|| IdentityConstants.OpenId.CHECKID_IMMEDIATE.equals(mode)) {
return checkSetupOrImmediate(httpReq, httpResp, request);
} else if (IdentityConstants.OpenId.CHECK_AUTHENTICATION
.equals(mode)) {
responseText = checkAuthentication(request);
} else {
// Error response.
message = DirectError.createDirectError("Unknown request");
responseText = message.keyValueFormEncoding();
}
} catch (Exception e) {
log.error(e.getMessage());
// Error response.
message = DirectError.createDirectError(e.getMessage());
responseText = message.keyValueFormEncoding();
}
try {
// Return the result to the user.
return directResponse(httpResp, responseText);
} catch (IOException e) {
log.error(e.getMessage());
throw new IdentityProviderException(
IdentityConstants.ErrorCodes.OPENID_DIRECT_RESP_FAILED);
}
}
/**
* @param authPage Authentication page
*/
public void setAuthPage(String authPage) {
ServerConfiguration serverConfig = null;
String host = null;
String httpsPort = null;
serverConfig = ServerConfiguration.getInstance();
host = serverConfig.getFirstProperty("HostName");
httpsPort = serverConfig.getFirstProperty("Ports.HTTPS");
this.authPage = "https://" + host + ":" + httpsPort + "/" + authPage;
}
/**
* @return OpenID Provider server URL.
*/
public static String getOpAddress() {
return opAddress;
}
/**
* @return ServerManager instance.
*/
public static ServerManager getManager() {
return manager;
}
/**
* @param params List of parameters from the OpenID authentication request
* @return response text
*/
private String checkAuthentication(ParameterList params) {
Message message = null;
// Processing a verification request.
message = manager.verify(params);
return message.keyValueFormEncoding();
}
/**
* @param httpReq HttpServletRequest
* @param params Parameter list
* @return response text
* @throws IdentityProviderException
* @throws ServerException
* @throws MessageException
* @throws AssociationException
*/
private String checkSetupOrImmediate(HttpServletRequest httpReq,
HttpServletResponse httpResp, ParameterList params)
throws IdentityProviderException, ServerException,
MessageException, AssociationException {
boolean authenticatedAndApproved = false;
String userSelectedClaimedId = null;
String openId = null;
String userId = null;
Message message = null;
HttpSession session = null;
String returnTo = null;
String profileName = null;
session = httpReq.getSession();
openId = params.hasParameter(IdentityConstants.OpenId.ATTR_IDENTITY) ? params
.getParameterValue(IdentityConstants.OpenId.ATTR_IDENTITY)
: null;
if (openId == null)
throw new IdentityProviderException(
IdentityConstants.ErrorCodes.REQUIRED_ATTRIBUTE_MISSING);
userId = OpenIDUtil.getUserName(openId);
if (httpReq.getParameter("authenticatedAndApproved") != null
&& httpReq.getParameter("authenticatedAndApproved").equals(
"true")) {
IPPersistenceManager persistenceManager = null;
OpenIDUserRPDO[] rpdo = null;
persistenceManager = IPPersistenceManager.getPersistanceManager();
returnTo = params
.getParameterValue(IdentityConstants.OpenId.ATTR_RETURN_TO);
rpdo = persistenceManager.getOpenIDUserRP(userId, OpenIDUtil
.getRelyingPartyUrl(returnTo));
if (rpdo != null && rpdo.length > 0)
profileName = rpdo[0].getDefaultProfileName();
authenticatedAndApproved = true;
}
// Process an authentication request.
AuthRequest authReq = AuthRequest.createAuthRequest(params, manager
.getRealmVerifier());
List<String> requestedAttributes = null;
if (IdentityConstants.OpenId.CANCEL.equals(httpReq
.getParameter(IdentityConstants.OpenId.ACTION))) {
authenticatedAndApproved = false;
} else if (!authenticatedAndApproved) {
// Not authenticated, redirect to the authentication
// page.
requestedAttributes = getRequestedAttributes(authReq);
session.setAttribute(IdentityConstants.OpenId.PARAM_LIST, params);
session.setAttribute("RequestedAttr", requestedAttributes);
return authPage;
}
session.removeAttribute("RequestedAttr");
String opLocalId = null;
message = manager.authResponse(params, opLocalId,
userSelectedClaimedId, authenticatedAndApproved);
if (message instanceof DirectError || message instanceof AuthFailure)
return message.getDestinationUrl(true);
else {
OpenIDExtension extension = null;
OpenIDAuthenticationRequest req = null;
req = new OpenIDAuthenticationRequest();
if ("true".equals(session
.getAttribute("phishingResistanceAuthentication"))) {
req.setPhishingResistanceLogin(true);
session.removeAttribute("phishingResistanceAuthentication");
}
if ("true".equals(session.getAttribute("multifactorlogin"))) {
req.setMultifactorLogin(true);
session.removeAttribute("multifactorlogin");
}
req.setAuthRequest(authReq);
boolean hasExtension = false;
boolean hasSregExtension = false;
for (Object alias : authReq.getExtensions()) {
if (log.isDebugEnabled())
log.info("Found extension in the OpenID request: " + alias);
req.setExtensionAlias((String) alias);
extension = OpenIDExtensionFactory.getInstance().getExtension(
req);
if (extension != null) {
MessageExtension messageExtension = null;
messageExtension = extension.getMessageExtension(userId,
profileName);
if (messageExtension != null) {
message.addExtension(messageExtension);
AuthSuccess authSuccess = (AuthSuccess) message;
authSuccess.setSignExtension((String) alias);
if ((messageExtension instanceof SRegMessage)
&& req
.getExtensionAlias()
.equals(
IdentityConstants.OpenId.SimpleRegAttributes.NS_SREG)) {
hasSregExtension = true;
} else {
hasExtension = true;
}
manager.sign(authSuccess);
}
}
}
if (hasSregExtension && !hasExtension) {
return message.getDestinationUrl(true);
}
sendData(httpReq, httpResp, message);
return null;
}
}
private List<String> getRequestedAttributes(AuthRequest request)
throws IdentityProviderException {
OpenIDAuthenticationRequest req = null;
OpenIDExtension extension = null;
List<String> requiredAttributes = null;
req = new OpenIDAuthenticationRequest();
req.setAuthRequest(request);
requiredAttributes = new ArrayList<String>();
for (Object alias : request.getExtensions()) {
req.setExtensionAlias((String) alias);
extension = OpenIDExtensionFactory.getInstance().getExtension(req);
if (extension != null) {
extension.addRequiredAttributes(requiredAttributes);
}
}
return requiredAttributes;
}
/**
* @param message
*/
private void sendData(HttpServletRequest httpReq,
HttpServletResponse httpResp, Message message)
throws IdentityProviderException {
try {
String page = null;
page = "/jsp/redirect.jsp";
// HTML FORM Redirection
RequestDispatcher dispatcher = httpReq.getRequestDispatcher(page);
httpReq.setAttribute("parameterMap", message.getParameterMap());
httpReq.setAttribute("destinationUrl", message
.getDestinationUrl(false));
dispatcher.forward(httpReq, httpResp);
} catch (Exception e) {
throw new IdentityProviderException(
IdentityConstants.ErrorCodes.OPENID_RESP_GENERATION_FAILED,
e);
}
}
/**
* Send a direct response to the RP.
* @param httpResp HttpServletResponse
* @param response Response message
* @return
* @throws IOException
*/
private String directResponse(HttpServletResponse httpResp, String response)
throws IOException {
ServletOutputStream stream = null;
try {
stream = httpResp.getOutputStream();
stream.write(response.getBytes());
} finally {
if (stream != null)
stream.close();
}
return null;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -