My liferay portlet jsonws not accessible from remote location but i can access it using localhost
example [http://localhost:8050/MySite-portlet/api/secure/jsonws] is accesible on the lacal machine
but when i try to access it remotely using the external ip e.g
[http://120.23.223.24:8050/MySite-portlet/api/secure/jsonws] its returning me the Connection refused error
However [http://120.23.223.24:8050/api/jsonws] and [http://120.23.223.24:8050/web/MySite] is working
my portal-ext.properties file contains the following entries
open.id.auth.enabled=
auth.login.site.url=
auth.login.community.url=
company.default.home.url=
default.logout.page.path=
default.landing.page.path=
redirect.url.ips.allowed=
jsonws.servlet.hosts.allowed=
json.servlet.hosts.allowed=
json.web.service.enabled=true
jsonws.web.service.public.methods=*
json.service.auth.token.enabled=true
jsonws.web.service.strict.http.method=false
I am using liferay-tomcat 6.1.0
Below is the error I am getting
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
`java.net.ConnectException: Connection refused: connect
java.net.PlainSocketImpl.socketConnect(Native Metho
d)
java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
java.net.Socket.connect(Socket.java:529)
java.net.Socket.connect(Socket.java:478)
sun.net.NetworkClient.doConnect(NetworkClient.java:163)
sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
sun.net.www.http.HttpClient.<init>(HttpClient.java:233)
sun.net.www.http.HttpClient.New(HttpClient.java:306)
sun.net.www.http.HttpClient.New(HttpClient.java:323)
sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:860)
sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:801)
sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)
sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
java.net.URL.openStream(URL.java:1010)
com.liferay.portal.jsonwebservice.JSONWebServiceServlet.service(JSONWebServiceServlet.java:136)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
com.liferay.portal.kernel.servlet.PortalClassLoaderServlet.service(PortalClassLoaderServlet.java:98)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:72)
sun.reflect.GeneratedMethodAccessor218.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
com.liferay.portal.kernel.bean.ClassLoaderBeanHandler.invoke(ClassLoaderBeanHandler.java:54)
$Proxy431.doFilter(Unknown Source)
com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:72)
com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:121)
com.liferay.portal.servlet.filters.secure.SecureFilter.processFilter(SecureFilter.java:201)
com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:48)
com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:203)
com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:105)
com.liferay.portal.kernel.servlet.PortalClassLoaderFilter.doFilter(PortalClassLoaderFilter.java:69)
com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:203)
com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:105)
com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilter.doFilter(InvokerFilter.java:70)`
Can you set up a debugger to look into this? If you look at the code in JSONWebServiceServlet, you'll find this in service() (I took the code from 6.1.1 which I have available - this differs from the line numbers in your sample - you might want to try an update as well, something has changed in this class. Also, for brevity, I've eliminated empty lines and some linebreaks, don't let that irritate you)
if (servletContext.getContext(PropsValues.PORTAL_CTX) != null) {
RequestDispatcher requestDispatcher = request.getRequestDispatcher(
apiPath);
requestDispatcher.forward(request, response);
}
else {
String requestURI = request.getRequestURI();
String requestURL = String.valueOf(request.getRequestURL());
String serverURL = requestURL.substring(0, requestURL.length() - requestURI.length());
String queryString = request.getQueryString();
if (Validator.isNull(queryString)) {
queryString = StringPool.BLANK;
}
else {
queryString += StringPool.AMPERSAND;
}
String servletContextPath = ContextPathUtil.getContextPath(servletContext);
queryString += "contextPath=" + HttpUtil.encodeURL(servletContextPath);
// CHECK THIS VALUE IN DEBUGGER:
apiPath = serverURL + apiPath + StringPool.QUESTION + queryString;
URL url = new URL(apiPath);
InputStream inputStream = null;
try {
inputStream = url.openStream();
OutputStream outputStream = response.getOutputStream();
StreamUtil.transfer(inputStream, outputStream);
}
finally {
StreamUtil.cleanUp(inputStream);
}
}
One possibility is that Liferay itself can't connect to the server name that it determines - e.g. because of Firewall or DNS setup. Once you know what apiPath results in (sadly there seems to be no logging that you could activate) you should be a lot closer to the solution than now.
Set following property in portal-ext.properties
json.servlet.hosts.allowed=
Let me know if you have any problem !!
Related
I am calling microsoft Azureurl with restTemplate in springboot application
Url:-https://login.microsoftonline.com/{{tenantId}}/oauth2/v2.0/token
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("grant_type","client_credentials");
map.add("client_id","xxxxxxxxxxxxxxxxxxxxxxxxxx");
map.add("client_secret","xxxxxxxxxxxxxxxxxx");
map.add("scope","https://graph.microsoft.com/.default");
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
ResponseEntity<String> response =
restTemplate.exchange("https://login.microsoftonline.com/xxxxxxxxxx-xxxxxx-c666dbeda42c\n/oauth2/v2.0/token",
HttpMethod.POST,
entity,
String.class);
if (response.getStatusCode() == HttpStatus.OK) {
System.out.println("Request Successful");
} else {
System.out.println("Request Failed");
}
While running the above sample call to connect with Azure, we are getting the Exception as : Caused by: java.net.UnknownHostException: login.microsoftonline.com
Later tried at home, where there is no Proxy to connect to the internet, and then am able to successfully get output without this "UnknownHostException" error.
So how to resolve the issue.
Your url seems to be not specification https://login.microsoftonline.com/xxxxxxxxxx-xxxxxx-c666dbeda42c\n/oauth2/v2.0/token, try to change it to: https://login.microsoftonline.com/xxxxxxxxxx-xxxxxx-c666dbeda42c/oauth2/v2.0/token . Remove \n.
I have the same error for a missing proxy configuration. (I was googling for solutions for a specific case)
"Host not found" has nothing to do with the url parameters, but as said just before, having "\n" in an url is never a good idea.
I need to create an SOAP client with JAX-WS on JBoss.
The Problem is I cannot get past the authentication.
I have a test implemented in SoapUI which works when I set the request properties username and password
With the following code
URL kbaURL = new URL("http://...");
IkfzService ikfzService = new IkfzService(kbaURL);
IkfzPortType ikfzPortType = ikfzService.getIkfzSOAP();
Map<String, Object> requestContext = ((BindingProvider)ikfzPortType).getRequestContext();
requestContext.put(BindingProvider.USERNAME_PROPERTY, "...");
requestContext.put(BindingProvider.PASSWORD_PROPERTY, "...");
Where URL, username und password are the same like in SOAPUI I am getting
javax.xml.ws.WebServiceException: org.apache.cxf.service.factory.ServiceConstructionException:
Failed to create service.
...
Caused by: javax.wsdl.WSDLException: WSDLException: faultCode=PARSER_ERROR:
Problem parsing 'http://..'.: java.io.IOException: Server returned HTTP response code:
401 for URL: http://..
What am I missing?
This should be a basic example of what you're trying to accomplish - let me know if you need more help or clarification
//the WSDL/webservice endpoint
private static final String WSDL_URL = "http://localhost:8080/MyWebService/MyWebService?wsdl";
URL url = new URL(WSDL_URL);
QName qname = new QName("http://ws.mycompany.com/", MyWebServiceImpl");
Service theWSService = Service.create(url, qname);
//returns the interface for MyWebServiceImpl
TheWSServiceIF port = theWSService.getPort(TheWSServiceIF.class);
//Setup Security
Map<String, Object> requestContext = ((BindingProvider)port).getRequestContext();
requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WS_URL);
Map<String, List<String>> requestHeaders = new HashMap<String, List<String>>();
requestHeaders.put("Username", Collections.singletonList("myUserName"));
requestHeaders.put("Password", Collections.singletonList("myPasword"));
requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
/**********************************************************************/
//actually call the web service method, print results
System.out.println(port.getMyWebServiceData());
I am getting the berlow error while using the service account.
The same code works well in local and iam able to create the credentials using service account.
....Error Snapshot :
aused by: java.net.SocketTimeoutException: connect timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:618)
at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:378)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:473)
at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:270)
at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:327)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:931)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1090)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:77)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:965)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:283)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:269)
Try the following ...
Set the proxy in the linux box.
While creating storage - new NetHttpTransport() provide your own way to create the socket and add the proxy in the transport.
Example code ...
public HttpClient myHttpClient() throws Exception {
SchemeRegistry schemeRegistry = new SchemeRegistry();
//SetRegisrty for both HTTP and HTTPS - Check google for this.
schemeRegistry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), YOUR_PROXY_PORT));
schemeRegistry.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 30 * 1000); // SET the timeout
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
ClientConnectionManager connManager = new ThreadSafeClientConnManager(
params, schemeRegistry);
DefaultHttpClient httpClient = new DefaultHttpClient(connManager,
params);
try {
int proxyPort = YOUR_PROXY_PORT;
String proxyHost = "YOUR_PROXT_HOST_NAME";
if (proxyPort > 0 && proxyHost != null && proxyHost.length() > 0) {
System.setProperty("https.proxyHost", proxyHost);
System.setProperty("https.proxyPort", proxyPort + "");
System.setProperty("http.proxyHost", proxyHost);
System.setProperty("http.proxyPort", proxyPort + "");
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
httpClient.getParams().setParameter(
ConnRoutePNames.DEFAULT_PROXY, proxy);
}
} catch (NullPointerException e) {
System.out.println("Proxy error here");
}
return httpClient;
}
public static HttpTransport myNetHttpTransport()
throws Exception {
return new ApacheHttpTransport(myHttpClient());
}
use .setTransport(myNetHttpTransport()) instead of NetHttpTransport() .
we spent long time on this. but as of now this seems to be working. Please let me know if any help in this...
I'm using Apache Shiro 1.2.0 in a long-running application that reads messages from a queue and and takes action. The action taken requires a Shiro authenticated session, so I've implemented an "ActAsAuthenticationToken" and custom credentials matcher which allows us to login in with only the username. I'm using the DefaultSecurityManager with only my custom realm and subject factory injected. Everything else should be default.
As it is configured, everything worked fine for a while, but as the application ran a long time (not that long - like a full day) I started to get this stack trace whenever I did anything that required the session:
Caused by: org.apache.shiro.session.UnknownSessionException: There is no session with id [f5b7c3bf-2c53-40e9-a707-37f4265970aa]
at org.apache.shiro.session.mgt.eis.AbstractSessionDAO.readSession(AbstractSessionDAO.java:170)
at org.apache.shiro.session.mgt.DefaultSessionManager.retrieveSessionFromDataSource(DefaultSessionManager.java:236)
at org.apache.shiro.session.mgt.DefaultSessionManager.retrieveSession(DefaultSessionManager.java:222)
at org.apache.shiro.session.mgt.AbstractValidatingSessionManager.doGetSession(AbstractValidatingSessionManager.java:118)
at org.apache.shiro.session.mgt.AbstractNativeSessionManager.lookupSession(AbstractNativeSessionManager.java:105)
at org.apache.shiro.session.mgt.AbstractNativeSessionManager.lookupRequiredSession(AbstractNativeSessionManager.java:109)
at org.apache.shiro.session.mgt.AbstractNativeSessionManager.getAttribute(AbstractNativeSessionManager.java:206)
at org.apache.shiro.session.mgt.DelegatingSession.getAttribute(DelegatingSession.java:141)
at org.apache.shiro.session.ProxiedSession.getAttribute(ProxiedSession.java:121)
at org.apache.shiro.session.ProxiedSession.getAttribute(ProxiedSession.java:121)
at org.apache.shiro.session.ProxiedSession.getAttribute(ProxiedSession.java:121)
at com.factorlab.security.FactorlabDelegatingSubject.getUser(FactorlabDelegatingSubject.java:34)
at com.factorlab.security.FactorlabDelegatingSubject.getUser(FactorlabDelegatingSubject.java:10)
at com.factorlab.persistence.AbstractEntityDao.getCurrentUser(AbstractEntityDao.java:227)
at com.factorlab.persistence.AbstractEntityDao.fireEvent(AbstractEntityDao.java:215)
at com.factorlab.persistence.AbstractEntityDao.saveOrUpdate(AbstractEntityDao.java:190)
at com.factorlab.persistence.AbstractEntityDao.saveOrUpdate(AbstractEntityDao.java:177)
at com.factorlab.persistence.AbstractEntityDao.saveOrUpdate(AbstractEntityDao.java:38)
at sun.reflect.GeneratedMethodAccessor106.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:196)
at $Proxy72.saveOrUpdate(Unknown Source)
at com.factorlab.observations.sales.OpportunityScoreUpdateServiceImpl.receiveOpportunityEvent(OpportunityScoreUpdateServiceImpl.java:83)
at sun.reflect.GeneratedMethodAccessor103.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy76.receiveOpportunityEvent(Unknown Source)
at sun.reflect.GeneratedMethodAccessor102.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.springframework.expression.spel.support.ReflectiveMethodExecutor.execute(ReflectiveMethodExecutor.java:69)
at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:84)
at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:57)
at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:102)
at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:102)
at org.springframework.integration.util.AbstractExpressionEvaluator.evaluateExpression(AbstractExpressionEvaluator.java:126)
at org.springframework.integration.util.MessagingMethodInvokerHelper.processInternal(MessagingMethodInvokerHelper.java:227)
at org.springframework.integration.util.MessagingMethodInvokerHelper.process(MessagingMethodInvokerHelper.java:127)
at org.springframework.integration.handler.MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:73)
... 49 more
The really weird part (as far as I'm concerned) is that I have a successful login (or at least an indication that I already have been authenticated right before I get the error:
#Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ)
#Trace(dispatcher = true)
public void receiveOpportunityEvent(EntityEvent<Opportunity> event) {
sessionFactory.getCurrentSession().refresh(event.getEntity());
log.info("OpportunityScoreUpdateService receiveOpportunityEvent: " + event);
//
//
// Here we see that we are either authenticated or we log in successfully
//
//
if (!securityUtils.getSubject().isAuthenticated()) {
try {
securityUtils.getFactorlabSubject().login(new ActAsAuthenticationToken(event.getEventUsername()));
} catch (RuntimeException e) {
log.error("Could not log in user " + event.getEventUsername() + ": " + e.getMessage(), e);
return;
}
}
if (event.getEntity() instanceof ObservedOpportunity) {
ObservedOpportunity opportunity = (ObservedOpportunity) event.getEntity();
opportunity = (ObservedOpportunity) opportunityDao.getById(opportunity.getId(), SkippedCheck.PERMISSION, SkippedCheck.DELETED);
if (!opportunity.isDeleted()) {
List<Stage> stages = stageDao.getAllByZone(opportunity.getZone(), SkippedCheck.PERMISSION);
Map<Stage, Double> originalScoresByStage = new HashMap<Stage, Double>();
Map<Stage, Double> newScoresByStage = new HashMap<Stage, Double>();
final Double originalTotal = opportunity.getTotalScore();
for (Stage stage : stages) {
originalScoresByStage.put(stage, opportunity.getScoreByStage(stage));
double score = calculator.getScoreForOpportunityAndStage(opportunity, stage);
opportunity.setScoreByStage(stage, score);
newScoresByStage.put(stage, opportunity.getScoreByStage(stage));
}
final double newTotalScore = calculator.getTotalScoreForOpportunity(opportunity);
opportunity.setTheTotalScore(newTotalScore);
final boolean scoreChanged = originalTotal == null ||
Math.round(originalTotal) != Math.round(newTotalScore) ||
checkStageScoresChanged(originalScoresByStage, newScoresByStage);
if (scoreChanged) {
opportunity.setScoreCalculated(new Date());
//
//
// Here is where we get the exception
//
//
opportunityDao.saveOrUpdate(opportunity, SkippedCheck.PERMISSION);
} else {
opportunityDao.refresh(opportunity);
}
}
}
}
What could be causing this exception?
I was getting this error and found that completely destroying any existing session before calling subject.login(credentials) fixed it.
// Login the user
private Subject loginUser()
{
ensureUserIsLoggedOut();
Subject subject = SecurityUtils.getSubject();
subject.login(credentials);
}
And the supporting routines are:
// Logout the user fully before continuing.
private void ensureUserIsLoggedOut()
{
try
{
// Get the user if one is logged in.
Subject currentUser = SecurityUtils.getSubject();
if (currentUser == null)
return;
// Log the user out and kill their session if possible.
currentUser.logout();
Session session = currentUser.getSession(false);
if (session == null)
return;
session.stop();
}
catch (Exception e)
{
// Ignore all errors, as we're trying to silently
// log the user out.
}
}
Shiro is validating credentials against SecuritySubject, which is stored in Session. So, it's very likely your session expired after some time of inactivity. You can change expiration time in web.xml or you can use Shiro rememberMe function, but your client have to support cookies. After rememberMe function SecuritySubject will obtain different session and will return false against isAuthenticated, but isRemembered will return true.
The session will never expired This will produce another problem, when your session will never expire. It will most likely get you out of memory, because your web container is most likely using memory session manager.
<session-config>
<session-timeout>-1</session-timeout>
</session-config>
Shiro rememberMe
http://shiro.apache.org/java-authentication-guide.html
//Example using most common scenario:
//String username and password. Acquire in
//system-specific manner (HTTP request, GUI, etc)
UsernamePasswordToken token =
new UsernamePasswordToken( username, password );
//”Remember Me” built-in, just do this:
token.setRememberMe(true);
We can disable the session storage in shiro.
The org.apache.shiro.mgt.DefaultSessionStorageEvaluator class contains a flag called sessionStorageEnabled. We can make it false.
I use the following in my spring application context for not using session storage.
<bean id="defaultSessionStorageEvaluator" class="org.apache.shiro.mgt.DefaultSessionStorageEvaluator">
<property name="sessionStorageEnabled" value="false" />
<bean id="defaultSubjectDAO" class="org.apache.shiro.mgt.DefaultSubjectDAO">
<property name="sessionStorageEvaluator" ref="defaultSessionStorageEvaluator" />
</bean>
I'm trying to read a value from a list in a remote SharePoint site (different SP Web App). The web apps are set up with Claims Auth, and the client web app SP Managed account is configured with an SPN. I believe Kerberos and claims are set up correctly, but I am unable to reach the remote server, and the request causes an exception: "The remote server returned an error: (401) Unauthorized."
The exception occurs in the line ctx.ExecuteQuery(); but it does not catch the exception in the if (scope.HasException) instead, the exception is caught by the calling code (outside of the using{} block).
When I look at the traffic at the remote server using Wireshark, it doesn't look like the request is even getting to the server; it's almost as if the 401 occurs before the Kerberos ticket is exchanged for the claim.
Here's my code:
using (ClientContext ctx = new ClientContext(contextUrl))
{
CredentialCache cc = new CredentialCache();
cc.Add(new Uri(contextUrl), "Kerberos", CredentialCache.DefaultNetworkCredentials);
ctx.Credentials = cc;
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx);
Web ctxWeb = ctx.Web;
List ctxList;
Microsoft.SharePoint.Client.ListItemCollection listItems;
using (scope.StartScope())
{
using (scope.StartTry())
{
ctxList = ctxWeb.Lists.GetByTitle("Reusable Content");
CamlQuery qry = new CamlQuery();
qry.ViewXml = string.Format(ViewQueryByField, "Title", "Text", SharedContentTitle);
listItems = ctxList.GetItems(qry);
ctx.Load(listItems, items => items.Include(
item => item["Title"],
item => item["ReusableHtml"],
item => item["ReusableText"]));
}
using (scope.StartCatch()) { }
using (scope.StartFinally()) { }
}
ctx.ExecuteQuery();
if (scope.HasException)
{
result = string.Format("Error retrieving content<!-- Error Message: {0} | {1} -->", scope.ErrorMessage, contextUrl);
}
if (listItems.Count == 1)
{
Microsoft.SharePoint.Client.ListItem contentItem = listItems[0];
if (SelectedType == SharedContentType.Html)
{
result = contentItem["ReusableHtml"].ToString();
}
else if (SelectedType == SharedContentType.Text)
{
result = contentItem["ReusableText"].ToString();
}
}
}
I realize the part with the CredentialCache shouldn't be necessary in claims, but every single example I can find is either running in a console app, or in a client side application of some kind; this code is running in the codebehind of a regular ASP.NET UserControl.
Edit: I should probably mention, the code above doesn't even work when the remote URL is the root site collection on the same web app as the calling code (which is in a site collection under /sites/)--in other words, even when the hostname is the same as the calling code.
Any suggestions of what to try next are greatly appreciated!
Mike
Is there a reason why you are not using the standard OM?
You already said this is running in a web part, which means it is in the context of application pool account. Unless you elevate permissions by switching users, it won't authenticate correctly. Maybe try that. But I would not use the client OM when you do have access to the API already.