Error occurred while sending a direct message or getting the response - OAuth2.0 Sample

3,756 views
Skip to first unread message

Matias Munoz

unread,
Feb 14, 2012, 3:53:52 PM2/14/12
to DotNetOpenAuth
Hi all! I'm having a issue when I'm trying to connect the OAuth2
sample to my own database. With the DataBase that comes with sample I
don't have any problem, but when I'm trying to connect to my own Data
Base I'm getting this exception:
"Error occurred while sending a direct message or getting the
response."
public IncomingWebResponse GetResponse(HttpWebRequest request,
DirectWebRequestOptions options) {
// This request MAY have already been prepared by GetRequestStream,
but
// we have no guarantee, so do it just to be safe.
PrepareRequest(request, false);

try {
Logger.Http.DebugFormat("HTTP {0} {1}", request.Method,
request.RequestUri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return new NetworkDirectWebResponse(request.RequestUri, response);
} catch (WebException ex) {
HttpWebResponse response = (HttpWebResponse)ex.Response;
if (response != null && response.StatusCode ==
HttpStatusCode.ExpectationFailed &&
request.ServicePoint.Expect100Continue) {
// Some OpenID servers doesn't understand the Expect header and
send 417 error back.
// If this server just failed from that, alter the ServicePoint
for this server
// so that we don't send that header again next time (whenever
that is).
// "Expect: 100-Continue" HTTP header. (see Google Code Issue 72)
// We don't want to blindly set all ServicePoints to not use the
Expect header
// as that would be a security hole allowing any visitor to a web
site change
// the web site's global behavior when calling that host.
Logger.Http.InfoFormat("HTTP POST to {0} resulted in 417
Expectation Failed. Changing ServicePoint to

not use Expect: Continue next time.", request.RequestUri);
request.ServicePoint.Expect100Continue = false; // TODO:
investigate that CAS may throw here

// An alternative to ServicePoint if we don't have permission to
set that,
// but we'd have to set it BEFORE each request.
////request.Expect = "";
}

if ((options & DirectWebRequestOptions.AcceptAllHttpResponses) !=
0 && response != null &&
response.StatusCode != HttpStatusCode.ExpectationFailed) {
Logger.Http.InfoFormat("The HTTP error code {0} {1} is being
accepted because the {2} flag is set.",

(int)response.StatusCode, response.StatusCode,
DirectWebRequestOptions.AcceptAllHttpResponses);
return new NetworkDirectWebResponse(request.RequestUri,
response);
}

if (Logger.Http.IsErrorEnabled) {
if (response != null) {
using (var reader = new
StreamReader(ex.Response.GetResponseStream())) {
Logger.Http.ErrorFormat("WebException from {0}: {1}{2}",
ex.Response.ResponseUri,

Environment.NewLine, reader.ReadToEnd());
}
} else {
Logger.Http.ErrorFormat("WebException {1} from {0}, no response
available.",

request.RequestUri, ex.Status);
}
}

// Be sure to close the response stream to conserve resources and
avoid
// filling up all our incoming pipes and denying future requests.
// If in the future, some callers actually want to read this
response
// we'll need to figure out how to reliably call Close on
exception
// responses at all callers.
if (response != null) {
response.Close();
}

throw ErrorUtilities.Wrap(ex,
MessagingStrings.ErrorInRequestReplyMessage);//IN
//THIS LINE I'M GETTING THE ERROR
}

I already change my web.config to this one:
<add name="DatabaseConnectionString" connectionString="Integrated
Security=SSPI;Data Source=server\test;Initial
Catalog=TestOAuth;PersistSecurity Info=True;Min Pool Size=3" />

And also I have created the tables that are defined in the Data Base
sample, to my own Data Base.
.
The exception is arise after I log in with my open id server provider
(in this case www.myopenid.com). So I never get the authorization to
access the data.

I'm using the samples from the last version of DNOA that I had
downloaded from GitHub.

Any help for this will be appreciated. Thanks in advance.

Regards, Matias.

Matias Munoz

unread,
Feb 14, 2012, 4:03:45 PM2/14/12
to DotNetOpenAuth
I forgot to say that this occurs when I'm trying the Authorization
Code Sample. If use the Implicit method, I get the access to see the
data.

Thanks, Matias.

Andrew Arnott

unread,
Feb 14, 2012, 8:10:20 PM2/14/12
to dotnet...@googlegroups.com
This is a useless error that means the server you're calling threw an error.  To understand what's going wrong, you need to attach a debugger to the server that's throwing the original error to examine what's going wrong.  Activating logging may help with that if you can't get a debugger on it.
--
You received this message because you are subscribed to the Google Groups "DotNetOpenAuth" group.
To post to this group, send email to dotnet...@googlegroups.com.
To unsubscribe from this group, send email to dotnetopenid...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/dotnetopenid?hl=en.



--
--
Andrew Arnott
"I [may] not agree with what you have to say, but I'll defend to the death your right to say it." - S. G. Tallentyre

Matias Munoz

unread,
Feb 16, 2012, 2:45:29 PM2/16/12
to DotNetOpenAuth
Andrew this is the trace I'm getting:
2012-02-16 16:11:55,388 (GMT-3) [8] ERROR DotNetOpenAuth.Http -
WebException from http://localhost:50172/OAuth/Token:
<html>
<head>
<title>This message has already been processed. &nbsp;This
could indicate a replay attack in progress.</title>
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .
7em;color:black;}
p {font-family:"Verdana";font-
weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-
top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:
18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:
14pt;color:maroon }
pre {font-family:"Lucida Console";font-size: .9em}
.marker {font-weight: bold; color: black;text-decoration:
none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold;
color:navy; cursor:hand; }
</style>
</head>

<body bgcolor="white">

<span><H1>Server Error in '/' Application.<hr width=100%
size=1 color=silver></H1>

<h2> <i>This message has already been processed.
&nbsp;This could indicate a replay attack in progress.</i> </h2></
span>

<font face="Arial, Helvetica, Geneva, SunSans-Regular,
sans-serif ">

<b> Description: </b>An unhandled exception occurred
during the execution of the current web request. Please review the
stack trace for more information about the error and where it
originated in the code.

<br><br>

<b> Exception Details: </
b>DotNetOpenAuth.Messaging.Bindings.ReplayedMessageException: This
message has already been processed. &nbsp;This could indicate a replay
attack in progress.<br><br>

<b>Source Error:</b> <br><br>

<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>

Line 243: if (!this.decodeOnceOnly.StoreNonce(context,
Convert.ToBase64String(message.Nonce), message.UtcCreationDate)) {
Line 244: Logger.OpenId.ErrorFormat(&quot;Replayed nonce detected
({0} {1}). Rejecting message.&quot;, message.Nonce,
message.UtcCreationDate);
<font color=red>Line 245: throw new
ReplayedMessageException(containingMessage);
</font>Line 246: }
Line 247: }</pre></code>

</td>
</tr>
</table>

<br>

<b> Source File: </b> C:\Users\Downloads\SourceCode
\AArnott-dotnetopenid-7bf6304\src\DotNetOpenAuth.Core\Messaging
\DataBagFormatterBase.cs<b> &nbsp;&nbsp; Line: </b> 245
<br><br>

<b>Stack Trace:</b> <br><br>

<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>

[ReplayedMessageException: This message has already been processed.
This could indicate a replay attack in progress.]

DotNetOpenAuth.Messaging.DataBagFormatterBase`1.Deserialize(IProtocolMessage
containingMessage, String value) in C:\Users\Downloads\SourceCode
\AArnott-dotnetopenid-7bf6304\src\DotNetOpenAuth.Core\Messaging
\DataBagFormatterBase.cs:245

DotNetOpenAuth.OAuth2.ChannelElements.AccessRequestBindingElement.ProcessIncomingMessage(IProtocolMessage
message) in C:\Users\Downloads\SourceCode\AArnott-
dotnetopenid-7bf6304\src\DotNetOpenAuth.OAuth2\OAuth2\ChannelElements
\AccessRequestBindingElement.cs:121

DotNetOpenAuth.Messaging.Channel.ProcessIncomingMessage(IProtocolMessage
message) in C:\Users\Downloads\SourceCode\AArnott-
dotnetopenid-7bf6304\src\DotNetOpenAuth.Core\Messaging\Channel.cs:1218
DotNetOpenAuth.Messaging.Channel.ReadFromRequest(HttpRequestInfo
httpRequest) in C:\Users\Downloads\SourceCode\AArnott-
dotnetopenid-7bf6304\src\DotNetOpenAuth.Core\Messaging\Channel.cs:478
DotNetOpenAuth.Messaging.Channel.TryReadFromRequest(HttpRequestInfo
httpRequest, TRequest&amp; request) in C:\Users\Downloads\SourceCode
\AArnott-dotnetopenid-7bf6304\src\DotNetOpenAuth.Core\Messaging
\Channel.cs:417

DotNetOpenAuth.OAuth2.AuthorizationServer.ReadAccessTokenRequest(HttpRequestInfo
requestInfo) in C:\Users\Downloads\SourceCode\AArnott-
dotnetopenid-7bf6304\src\DotNetOpenAuth.OAuth2.AuthorizationServer
\OAuth2\AuthorizationServer.cs:152
OAuthAuthorizationServer.Controllers.OAuthController.Token() in C:
\Users\Downloads\SourceCode\AArnott-dotnetopenid-7bf6304\samples
\OAuthAuthorizationServer\Controllers\OAuthController.cs:24
lambda_method(Closure , ControllerBase , Object[] ) +62
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase
controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
controllerContext, IDictionary`2 parameters) +199

System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
controllerContext, ActionDescriptor actionDescriptor, IDictionary`2
parameters) +27

System.Web.Mvc.&lt;&gt;c__DisplayClassd.&lt;InvokeActionMethodWithFilters&gt;b__a()
+56

System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter
filter, ActionExecutingContext preContext, Func`1 continuation) +267

System.Web.Mvc.&lt;&gt;c__DisplayClassf.&lt;InvokeActionMethodWithFilters&gt;b__c()
+20

System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext
controllerContext, IList`1 filters, ActionDescriptor actionDescriptor,
IDictionary`2 parameters) +190

System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName) +345
System.Web.Mvc.Controller.ExecuteCore() +115
System.Web.Mvc.ControllerBase.Execute(RequestContext
requestContext) +42

System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext
requestContext) +10

System.Web.Mvc.&lt;&gt;c__DisplayClass8.&lt;BeginProcessRequest&gt;b__4()
+34

System.Web.Mvc.Async.&lt;&gt;c__DisplayClass1.&lt;MakeVoidDelegate&gt;b__0()
+21

System.Web.Mvc.Async.&lt;&gt;c__DisplayClass8`1.&lt;BeginSynchronous&gt;b__7(IAsyncResult
_) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult
asyncResult) +43

System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
result) +9

System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+8969117
System.Web.HttpApplication.ExecuteStep(IExecutionStep step,
Boolean&amp; completedSynchronously) +184
</pre></code>

</td>
</tr>
</table>

<br>

<hr width=100% size=1 color=silver>

<b>Version Information:</b>&nbsp;Microsoft .NET Framework
Version:4.0.30319; ASP.NET Version:4.0.30319.272

</font>

</body>
</html>
<!--
[ReplayedMessageException]: This message has already been processed.
This could indicate a replay attack in progress.
at
DotNetOpenAuth.Messaging.DataBagFormatterBase`1.Deserialize(IProtocolMessage
containingMessage, String value) in C:\Users\Downloads\SourceCode
\AArnott-dotnetopenid-7bf6304\src\DotNetOpenAuth.Core\Messaging
\DataBagFormatterBase.cs:line 245
at
DotNetOpenAuth.OAuth2.ChannelElements.AccessRequestBindingElement.ProcessIncomingMessage(IProtocolMessage
message) in C:\Users\Downloads\SourceCode\AArnott-
dotnetopenid-7bf6304\src\DotNetOpenAuth.OAuth2\OAuth2\ChannelElements
\AccessRequestBindingElement.cs:line 121
at
DotNetOpenAuth.Messaging.Channel.ProcessIncomingMessage(IProtocolMessage
message) in C:\Users\Downloads\SourceCode\AArnott-
dotnetopenid-7bf6304\src\DotNetOpenAuth.Core\Messaging\Channel.cs:line
1218
at DotNetOpenAuth.Messaging.Channel.ReadFromRequest(HttpRequestInfo
httpRequest) in C:\Users\Downloads\SourceCode\AArnott-
dotnetopenid-7bf6304\src\DotNetOpenAuth.Core\Messaging\Channel.cs:line
478
at DotNetOpenAuth.Messaging.Channel.TryReadFromRequest[TRequest]
(HttpRequestInfo httpRequest, TRequest& request) in C:\Users\Downloads
\SourceCode\AArnott-dotnetopenid-7bf6304\src\DotNetOpenAuth.Core
\Messaging\Channel.cs:line 417
at
DotNetOpenAuth.OAuth2.AuthorizationServer.ReadAccessTokenRequest(HttpRequestInfo
requestInfo) in C:\Users\Downloads\SourceCode\AArnott-
dotnetopenid-7bf6304\src\DotNetOpenAuth.OAuth2.AuthorizationServer
\OAuth2\AuthorizationServer.cs:line 152
at OAuthAuthorizationServer.Controllers.OAuthController.Token() in
C:\Users\Downloads\SourceCode\AArnott-dotnetopenid-7bf6304\samples
\OAuthAuthorizationServer\Controllers\OAuthController.cs:line 24
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase
controller, Object[] parameters)
at
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
controllerContext, IDictionary`2 parameters)
at
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
controllerContext, ActionDescriptor actionDescriptor, IDictionary`2
parameters)
at
System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a()
at
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter
filter, ActionExecutingContext preContext, Func`1 continuation)
at
System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClassd.<>c__DisplayClassf.<InvokeActionMethodWithFilters>b__c()
at
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext
controllerContext, IList`1 filters, ActionDescriptor actionDescriptor,
IDictionary`2 parameters)
at
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext
requestContext)
at
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext
requestContext)
at
System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__4()
at
System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at
System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult
_)
at
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult
asyncResult)
at
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
result)
at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step,
Boolean& completedSynchronously)
-->
2012-02-16 16:12:23,137 (GMT-3) [8] ERROR DotNetOpenAuth.OAuthClient -
An unhandled exception was raised. Details follow:
System.Web.HttpUnhandledException: Exception of type
'System.Web.HttpUnhandledException' was thrown. --->
DotNetOpenAuth.Messaging.ProtocolException: Error occurred while
sending a direct message or getting the response. --->
System.Net.WebException: The remote server returned an error: (500)
Internal Server Error.
at System.Net.HttpWebRequest.GetResponse()
at
DotNetOpenAuth.Messaging.StandardWebRequestHandler.GetResponse(HttpWebRequest
request, DirectWebRequestOptions options) in C:\Users\Downloads
\SourceCode\AArnott-dotnetopenid-7bf6304\src\DotNetOpenAuth.Core
\Messaging\StandardWebRequestHandler.cs:line 127
--- End of inner exception stack trace ---
at
DotNetOpenAuth.Messaging.StandardWebRequestHandler.GetResponse(HttpWebRequest
request, DirectWebRequestOptions options) in C:\Users\Downloads
\SourceCode\AArnott-dotnetopenid-7bf6304\src\DotNetOpenAuth.Core
\Messaging\StandardWebRequestHandler.cs:line 173
at
DotNetOpenAuth.Messaging.StandardWebRequestHandler.GetResponse(HttpWebRequest
request) in C:\Users\Downloads\SourceCode\AArnott-
dotnetopenid-7bf6304\src\DotNetOpenAuth.Core\Messaging
\StandardWebRequestHandler.cs:line 101
at
DotNetOpenAuth.Messaging.Channel.GetDirectResponse(HttpWebRequest
webRequest) in C:\Users\Downloads\SourceCode\AArnott-
dotnetopenid-7bf6304\src\DotNetOpenAuth.Core\Messaging\Channel.cs:line
676
at
DotNetOpenAuth.Messaging.Channel.RequestCore(IDirectedProtocolMessage
request) in C:\Users\Downloads\SourceCode\AArnott-
dotnetopenid-7bf6304\src\DotNetOpenAuth.Core\Messaging\Channel.cs:line
697
at
DotNetOpenAuth.Messaging.Channel.Request(IDirectedProtocolMessage
requestMessage) in C:\Users\Downloads\SourceCode\AArnott-
dotnetopenid-7bf6304\src\DotNetOpenAuth.Core\Messaging\Channel.cs:line
520
at
DotNetOpenAuth.OAuth2.ClientBase.UpdateAuthorizationWithResponse(IAuthorizationState
authorizationState, EndUserAuthorizationSuccessAuthCodeResponse
authorizationSuccess) in C:\Users\Downloads\SourceCode\AArnott-
dotnetopenid-7bf6304\src\DotNetOpenAuth.OAuth2.Client
\OAuth2\ClientBase.cs:line 227
at
DotNetOpenAuth.OAuth2.WebServerClient.ProcessUserAuthorization(HttpRequestInfo
request) in C:\Users\Downloads\SourceCode\AArnott-
dotnetopenid-7bf6304\src\DotNetOpenAuth.OAuth2.Client
\OAuth2\WebServerClient.cs:line 121
at OAuthClient.SampleWcf2.Page_Load(Object sender, EventArgs e) in
C:\Users\Downloads\SourceCode\AArnott-dotnetopenid-7bf6304\samples
\OAuthClient\SampleWcf2.aspx.cs:line 54
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp,
Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object
sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
--- End of inner exception stack trace ---
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext
context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.samplewcf2_aspx.ProcessRequest(HttpContext context) in c:
\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files
\root\853feb29\cec7eb81\App_Web_zfbu800c.2.cs:line 0
at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step,
Boolean& completedSynchronously)

I had read in stackoverflow that some has solved this by incrementing
the maxAuthorizationTime, and I had tray it but the error persits.

Thanks, in advanced.

Matias.

Andrew Arnott

unread,
Feb 18, 2012, 4:18:05 PM2/18/12
to dotnet...@googlegroups.com
When this error happens consistently, it's a sign that your site is actually processing the incoming token twice.  This can happen when, for example, you have an HTTP authentication module registered in your web.config file that calls into DNOA to read the token and you're also asking DNOA to read the token within your MVC controller.

There are actually two places in a web.config file where such a module could be registered, one for Cassini and one for IIS7.  For example, here's what one might look like:

<httpModules>
	<add name="OAuthAuthenticationModule" type="RelyingPartyLogic.OAuthAuthenticationModule, RelyingPartyLogic" />
--
You received this message because you are subscribed to the Google Groups "DotNetOpenAuth" group.
To post to this group, send email to dotnet...@googlegroups.com.
To unsubscribe from this group, send email to dotnetopenid...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/dotnetopenid?hl=en.

Matias Munoz

unread,
Feb 22, 2012, 2:28:56 PM2/22/12
to DotNetOpenAuth
Hi Andrew! Thanks for the info. If I understand you correctly I have
to get rid of that line in the web.config. I commented but the same
error appears, maybe I am missing something else.
Is kind of wierd, because with the sample Data Base all works just
fine, but when I change the connection string this error arise.

Thanks for answering.
Matias.

Andrew Arnott

unread,
Feb 22, 2012, 8:04:52 PM2/22/12
to dotnet...@googlegroups.com
I can't explain why the connection string is significant.  

You presumably have implemented the INonceStore interface within your codebase.  Set a breakpoint in your INonceStore.StoreNonce method.  For a single incoming request that repros the problem, you'll see that the method is called with the same nonce twice.  Record both callstacks when those calls come in.  One of them shouldn't be there.  You can probably decide which one isn't supposed to be there and eliminate it by removing your code that calls into it.  If you can't decide, please include both callstacks in a reply email.

Either way, please share your results.
--
You received this message because you are subscribed to the Google Groups "DotNetOpenAuth" group.
To post to this group, send email to dotnet...@googlegroups.com.
To unsubscribe from this group, send email to dotnetopenid...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/dotnetopenid?hl=en.

Matias Munoz

unread,
Feb 24, 2012, 10:22:41 AM2/24/12
to DotNetOpenAuth
Hi Andrew again! So, I debug a lot, and I found an error in the
StoreNonce method: "System.Data.SqlClient.SqlException was caught
Message=String or binary data would be truncated."

In my Data Base I create the Nonce table, but with nvarchar(200), so I
changed this and now the sample is working.

I don't know why the error appears in some other place, but when I
start debugging I found that error.

Thanks a lot Andrew.

Matias.

Andrew Arnott

unread,
Feb 24, 2012, 11:11:49 AM2/24/12
to dotnet...@googlegroups.com
I'm glad that helped.  200 character width should have been sufficient for either of the two strings passed in as arguments.  Do you know which one was being truncated and why?
--
You received this message because you are subscribed to the Google Groups "DotNetOpenAuth" group.
To post to this group, send email to dotnet...@googlegroups.com.
To unsubscribe from this group, send email to dotnetopenid...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/dotnetopenid?hl=en.

Matias Munoz

unread,
Feb 24, 2012, 12:58:03 PM2/24/12
to DotNetOpenAuth
I honestly don't know why. But I enlarge the Context column in the
Nonce table and in the first test the sample worked.

Felipe Almeida

unread,
Apr 10, 2012, 5:06:04 PM4/10/12
to dotnet...@googlegroups.com
Hey, im trying to implement one OpenID authentication where the users are the company workers, then only @domain.com.br emails can access the app..
to restrict only this users to authenticate, i use this identifier
https://google.com/accounts/o8/site-xrds?hd=mydomain.com.br
the user can log in using hit account, but when i check the response status, this message appears:

"Error occurred while sending a direct message or getting the response"
and i dont know how to resolve this problem, can u help me?
thanks
 
MY CODE:


    public partial class AuthenticationEndpoint : System.Web.UI.Page
    {
        const string parametroDeCallback = "callback";
        const string AUTHENTICATION_ENDPOINT = "~/AuthenticationEndpoint.aspx";
        //const string GOOGLE_OAUTH_ENDPOINT = "https://www.google.com/accounts/o8/id";
        const string returnUrlParameter = "returnUrl";
 
        protected void Page_Load(object sender, EventArgs e)
        {
            //Check if either to handle a call back or start an authentication
            if (Request.Params[parametroDeCallback] == "true")
            {
                GerenciarCallback(); //Google has performed a callback, let's analyze it
            }
            else
            {
                AutenticacaoOpenID();  //There is no callback parameter, 
            }
        }
 
        /// <summary>
        /// Pede para o google autenticar o usuário
        /// </summary>
        void AutenticacaoOpenID()
        {
            using (OpenIdRelyingParty openid = new OpenIdRelyingParty())
            {
                //Set up the callback URL
                Uri callbackUrl = new Uri(
                    String.Format("{0}{1}{2}{3}?{4}=true&returnUrl={5}",
                    (Request.IsSecureConnection) ? "https://" : "http://",
                    Request.Url.Host,
                    (Request.Url.IsDefaultPort) ?
                        String.Empty : String.Concat(":", Request.Url.Port),
                    Page.ResolveUrl(AUTHENTICATION_ENDPOINT),
                    parametroDeCallback,
                    Request.Params[returnUrlParameter]
                    ));
 
                //Set up request object for Google Authentication
                IAuthenticationRequest request =
                    openid.CreateRequest("https://google.com/accounts/o8/site-xrds?hd=t4w.com.br",//GOOGLE_OAUTH_ENDPOINT,
                    DotNetOpenAuth.OpenId.Realm.AutoDetect, callbackUrl);
 
                //Let's tell Google, what we want to have from the user:
                var fetch = new FetchRequest();
                fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                fetch.Attributes.AddRequired(WellKnownAttributes.Name.FullName);
                fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
                fetch.Attributes.AddRequired(WellKnownAttributes.Name.Middle);
                fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                request.AddExtension(fetch);
 
                //Redirect to Google Authentication
                request.RedirectToProvider();
            }
        }
 
        /// <summary>
        /// Gerencia o Callback do google, verificando se o uruário foi autenticado, recuperando entao o email e nome completo do mesmo
        /// </summary>
        void GerenciarCallback()
        {
            OpenIdRelyingParty openid = new OpenIdRelyingParty();
            var response = openid.GetResponse();
 
            if (response != null && response.Status == AuthenticationStatus.Authenticated)
            {
                var fetch = response.GetExtension<FetchResponse>();
                string email = string.Empty;
                string fullName = string.Empty;
                string firstName = string.Empty;
                string middleName = string.Empty;
                string lastName = string.Empty;
                if (fetch != null)
                {
                    email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
                    fullName = fetch.GetAttributeValue(WellKnownAttributes.Name.FullName);
                    firstName = fetch.GetAttributeValue(WellKnownAttributes.Name.First);
                    middleName = fetch.GetAttributeValue(WellKnownAttributes.Name.Middle);
                    lastName = fetch.GetAttributeValue(WellKnownAttributes.Name.Last);
                }
 
                //Se o nome completo não for informado, tentar unir as 3 informaçoes para formar o nome completo
                if (String.IsNullOrEmpty(fullName))
                {
                    fullName = String.Format("{0} {1} {2}", firstName, middleName, lastName).TrimStart().TrimEnd().Replace("  "" ");
                }
 
                if (new RNFake().ValidarUsuario(email, fullName))
                {
                    //https://www.google.com/accounts/Logout
                    RetornarAutenticacao("""");
                }
                else
                {
                    RetornarAutenticacao(email, fullName);
                }
            }
            else
            {
                //            throw new System.Security.SecurityException("Authentication failed");
                RetornarAutenticacao("""");
            }
        }
 
        void RetornarAutenticacao(string email, string fullName)
        {
            string returnUrl = Request.Params[returnUrlParameter];
            if (String.IsNullOrEmpty(returnUrl))
            {
                //Retorna para uma pagina default
                return;
            }
 
            Uri uri = new Uri(returnUrl);
            string queryStringConcat = String.IsNullOrEmpty(uri.Query) ? "?" : "&";
            Response.Redirect(String.Format("{0}{1}email={2}&fullName{3}", returnUrl, queryStringConcat, email, fullName));
        }
    }
 
    public class RNFake
    {
        public RNFake()
        {
 
        }
 
        /// <summary>
        /// Valida as informações do usuário
        /// </summary>
        /// <param name="email"></param>
        /// <param name="nomeCompleto"></param>
        /// <returns></returns>
        public bool ValidarUsuario(string email, string nomeCompleto)
        {
            if (String.IsNullOrEmpty(email) || string.IsNullOrEmpty(nomeCompleto))
                return false;
 
            return ValidaEmailT4W(email);
        }
 
        bool ValidaEmailT4W(string email)
        {
            if (String.IsNullOrEmpty(email))
                return false;
 
            string dominio = email.ToUpper().Split('@').Last();
            return dominio == "t4w.com.br".ToUpper();
        }
    }

Andrew Arnott

unread,
Apr 10, 2012, 8:45:16 PM4/10/12
to dotnet...@googlegroups.com
To help in analyzing the problem, please activate logging.

But more importantly, you're making the common mistake of considering that email addresses are the secure identifier in OpenID.  They are not.  Claimed Identifiers are.  And the identifier you begin authentication with (mydomain.com.br in your case) is not sufficient to ensure that only that domain can log in.  Due to "unsolicited assertions", anyone can login using a Provider that will send an assertion to your RP.  It's vitally important that when you receive an IAuthenticationResponse, that you check its Provider.Uri property value to make sure it's the OP Endpoint that you expect/trust.

--
Andrew Arnott
"I [may] not agree with what you have to say, but I'll defend to the death your right to say it." - S. G. Tallentyre


--
You received this message because you are subscribed to the Google Groups "DotNetOpenAuth" group.
To view this discussion on the web visit https://groups.google.com/d/msg/dotnetopenid/-/_u6rv_kAKzEJ.
Reply all
Reply to author
Forward
0 new messages