Tag Archives: OAuth

Session value returns "null" ?

Hi there,

I have the following code and I am trying to get a token from session cache but it returns null. 

public static string GetSessionToken()
        {
            var session = HttpContext.Current.Session;
            if (session != null)
            {
                var startTokenKey = "_TokenCache";
                string ServiceResourceId = "https://outlook.office365.com/";
                var tokenKey = session.Keys
                                .Cast<string>()
                                .Where(k => k.Contains(startTokenKey))
                                .SingleOrDefault();

                if (tokenKey != null)
                {
                    var tokenObject = session[tokenKey + ServiceResourceId];
                    //Hack to get value since CacheItem type isn't accessible
                    if (tokenObject != null)
                    {
                        var token = tokenObject.GetType().GetField("Value").GetValue(tokenObject).ToString();
                        return token;
                    }
                }
            }
            return null;
        }

I have no idea about session at all, why the above function always return null ? where did I go wrong ? Please help me figure out the problem so that I can rectify the error. I am completely clueless here.

It’s returning null because the info it is looking for isn’t in the session.  The problem is unlikely to be the code you posted but to do with how and when you add the data to the session which you haven’t explained.

SharpDragon

1) I am trying to get a token from session cache
2) but it returns null

Probably you should see what exactly returns null as there are multiple cases when you could get null

1) session is null (in this case your method does nothing and returns null)
2) session is not null but it either has no key with a name containg "_TokenCache"
3) session is not null and key with "_TokenCache" is there but there is no key with name tokenKey + ServiceResourceId or its value is null
4) all above is not null but .GetValue(tokenObject) is null

Hi , Good morning.

I am using Active Directory (Adal.net) to connect to office 365 Api via Oauth2.0.  You can see I am successfully receiving the token. Here is the IIS Log:

iisexpress.exe Information: 0 : ADAL .NET with assembly version '2.12.0.0', file version '2.12.11107.1459' and informational version '0adb54f5edd13d1866d15c6d445bb08081e85957' is running...
iisexpress.exe Information: 0 : === Token Acquisition started. Correlation ID: 8fbedf41-d8fb-430f-93da-0c3b2e9d7589
iisexpress.exe Information: 0 : Access Token with hash '6PD59RQZC0z8L74x2ygf5iNnFdp9EwDuQrqLUy4OKw8=' and Refresh Token with hash 'LDI3/rtqY1olt0rv5LKfPe/GQukVf21Yv+N6j5eMzNo=' returned. Correlation ID: 8fbedf41-d8fb-430f-93da-0c3b2e9d7589
iisexpress.exe Information: 0 : === Token Acquisition started. Correlation ID: 9972d971-92bb-4ee3-a68d-9cd776a5e44e
iisexpress.exe Information: 0 : A matching token was found in the cache. Correlation ID: 9972d971-92bb-4ee3-a68d-9cd776a5e44e
iisexpress.exe Information: 0 : Access Token with hash 'nssYffUW/6466ukfECC+yeT7LmEKDTi8kzNGyfq7tBo=' and Refresh Token with hash 'EhgZuCWdI/2kYsvtsquTtDeA95cUug0dvQTdQNRhi3g=' returned. Correlation ID: 9972d971-92bb-4ee3-a68d-9cd776a5e44e
iisexpress.exe Information: 0 : === Token Acquisition started. Correlation ID: b975cf29-0e5f-4ac7-be58-381e5112182e
iisexpress.exe Information: 0 : A matching token was found in the cache. Correlation ID: b975cf29-0e5f-4ac7-be58-381e5112182e
iisexpress.exe Information: 0 : Access Token with hash '3/nI4yuYE98VGdV86kKaHSpVW925MbIs8h2qUHMeydA=' and Refresh Token with hash 'UQ7NZjFGDswbhPM4gCwu7LulRvigc+JSKNuBWpKJhaA=' returned. Correlation ID: b975cf29-0e5f-4ac7-be58-381e5112182e

I checked the values of tokenkey and tokenObject in my code.

tokenkey = > _TokenCache

tokenObject >= null

Maybe _TokenCache is not the correct key I am using. I am not sure. :(

Well, it’s stil unclear.

SharpDragon

tokenkey = > _TokenCache

tokenObject >= null

What does => stand for?

If tokenkey is not null but tokenObject is null then you need to check

var tokenObject = session[tokenKey + ServiceResourceId];

because this is the only line where you get tokenObject.

SharpDragon

Maybe _TokenCache is not the correct key I am using. I am not sure.

Maybe, who knows? :-)

Are you sure that tokenkey is not null?

My service resource ID is correct.  Please tell me how to loop through session keys here and make sure I am using correct session key as "startTokenkey".  

Yes, tokenkey also returns null, sorry for inconvenience. 

I think you do not understand the code.

If tokenkey is null, then in this code

var tokenKey = session.Keys
         .Cast<string>()
         .Where(k => k.Contains(startTokenKey))
         .SingleOrDefault();

a) either session is null 
b) or condition is not correct.

Are you sure that session is NOT null? You can check it e.g. 

if (session != null)
{
Response.Write("SESSION IS NOT NULL");
...
} else {

Response.Write("SESSION IS NULL");
}

I just checked, it says "Session is not null".

Good, it means that there is no key which has a name with "_TokenCache" in it.

Are you sure that value you search is "_TokenCache" and not ‘LDI3/rtqY1olt0rv5LKfPe/GQukVf21Yv+N6j5eMzNo=’ or something like this?

The problem is I did not search the value ,  I followed this article :

http://www.jeremythake.com/2014/08/using-the-exchange-online-ews-api-with-office-365-api-via-azure-ad/

I copied the above code from this article. Would you please tell me how to find out the correct key/value which stores the accesstoken ?

I think you need to read it again because in the original code it has

var startTokenKey = "_O365#AccessToken#";

I suggest you close the topic now as it neither related to ASP.NET nor MVC

I know.. I tried this original value already.  ok. I close this topic. 

best regards,

Hi,

I don’t think that value stored in the session. That value may store in the cookie or URL. So you need to know where that data stored.

Best Regards

Starain

[RESOLVED]compilation error – CS0122: 'mapdistance.DistHandler' is inaccessible due to its protection level (EDITED)

I am querying the Bing Maps api through a rest service, based on information from a
MSDN tutorial.

Originally I started out with a test project in Visual Studio, and the code works there as designed.

Now I have copied the 3 files involved to where it is going to live as part of my site, and I get the error message above.

C:Windowssystem32> "C:WindowsMicrosoft.NETFrameworkv4.0.30319csc.exe" /t:library /utf8output /R:"C:WindowsassemblyGAC_MSILSystem.Data.SqlServerCe4.0.0.0__89845dcd8080cc91System.Data.SqlServerCe.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.ComponentModel.DataAnnotationsv4.0_4.0.0.0__31bf3856ad364e35System.ComponentModel.DataAnnotations.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.WorkflowServicesv4.0_4.0.0.0__31bf3856ad364e35System.WorkflowServices.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl35e9a55a448f4a257_d715ce01RestSharp.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl33ff72591d8ce7474_b735cf01zxing.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.Helpersv4.0_2.0.0.0__31bf3856ad364e35System.Web.Helpers.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Data.Entityv4.0_4.0.0.0__b77a5c561934e089System.Data.Entity.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Activitiesv4.0_4.0.0.0__31bf3856ad364e35System.Activities.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl332bcbe5a68a37e57_d715ce01Newtonsoft.Json.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl3ec6e8f6888e94967_d715ce01iTextSharp.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Drawingv4.0_4.0.0.0__b03f5f7f11d50a3aSystem.Drawing.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.WebPagesv4.0_2.0.0.0__31bf3856ad364e35System.Web.WebPages.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl38cf09cbd58f686f8_d615ce01DotNetOpenAuth.OAuth.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILMicrosoft.CSharpv4.0_4.0.0.0__b03f5f7f11d50a3aMicrosoft.CSharp.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Net.Httpv4.0_4.0.0.0__b03f5f7f11d50a3aSystem.Net.Http.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Xml.Linqv4.0_4.0.0.0__b77a5c561934e089System.Xml.Linq.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILWebMatrix.WebDatav4.0_2.0.0.0__31bf3856ad364e35WebMatrix.WebData.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl39ac13ad668708ef8_d615ce01DotNetOpenAuth.AspNet.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51App_Code.5dgnjctq.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.DynamicDatav4.0_4.0.0.0__31bf3856ad364e35System.Web.DynamicData.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl3a8d694dd8b946f8_d615ce01DotNetOpenAuth.Core.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILNuGet.Corev4.0_1.6.30117.9648__31bf3856ad364e35NuGet.Core.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Configurationv4.0_4.0.0.0__b03f5f7f11d50a3aSystem.Configuration.dll" /R:"C:WindowsMicrosoft.NETFrameworkv4.0.30319mscorlib.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl3846e796b478fff65_726cce01EntityFramework.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystemv4.0_4.0.0.0__b77a5c561934e089System.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.WebPages.Administrationv4.0_2.0.0.0__31bf3856ad364e35System.Web.WebPages.Administration.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Runtime.Serializationv4.0_4.0.0.0__b77a5c561934e089System.Runtime.Serialization.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Corev4.0_4.0.0.0__b77a5c561934e089System.Core.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILWebMatrix.Datav4.0_2.0.0.0__31bf3856ad364e35WebMatrix.Data.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.Extensionsv4.0_4.0.0.0__31bf3856ad364e35System.Web.Extensions.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl3eae21eaa2cb2997_a018cf01Microsoft.Web.Helpers.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.ServiceModel.Webv4.0_4.0.0.0__31bf3856ad364e35System.ServiceModel.Web.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl3f3f60bfd50c835fc_66e2cf01Twilio.WebMatrix.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_32System.Datav4.0_4.0.0.0__b77a5c561934e089System.Data.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.ServiceModelv4.0_4.0.0.0__b77a5c561934e089System.ServiceModel.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Data.DataSetExtensionsv4.0_4.0.0.0__b77a5c561934e089System.Data.DataSetExtensions.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Data.Entity.Designv4.0_4.0.0.0__b77a5c561934e089System.Data.Entity.Design.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.ServiceModel.Activationv4.0_4.0.0.0__31bf3856ad364e35System.ServiceModel.Activation.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.Razorv4.0_2.0.0.0__31bf3856ad364e35System.Web.Razor.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Securityv4.0_4.0.0.0__b03f5f7f11d50a3aSystem.Security.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.WebPages.Deploymentv4.0_2.0.0.0__31bf3856ad364e35System.Web.WebPages.Deployment.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.Servicesv4.0_4.0.0.0__b03f5f7f11d50a3aSystem.Web.Services.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.ServiceModel.Activitiesv4.0_4.0.0.0__31bf3856ad364e35System.ServiceModel.Activities.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.ApplicationServicesv4.0_4.0.0.0__31bf3856ad364e35System.Web.ApplicationServices.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Net.Http.WebRequestv4.0_4.0.0.0__b03f5f7f11d50a3aSystem.Net.Http.WebRequest.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.WebPages.Razorv4.0_2.0.0.0__31bf3856ad364e35System.Web.WebPages.Razor.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_32System.EnterpriseServicesv4.0_4.0.0.0__b03f5f7f11d50a3aSystem.EnterpriseServices.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl31608e86e58aa69f8_d615ce01DotNetOpenAuth.OpenId.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILMicrosoft.Web.Infrastructurev4.0_1.0.0.0__31bf3856ad364e35Microsoft.Web.Infrastructure.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl311ca539da81379f8_d615ce01DotNetOpenAuth.OpenId.RelyingParty.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl3c7951ba8b447574_b735cf01zxing.presentation.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl34daf8edb69ddff65_726cce01EntityFramework.SqlServer.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_32System.Webv4.0_4.0.0.0__b03f5f7f11d50a3aSystem.Web.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILMicrosoft.VisualStudio.Web.PageInspector.Loaderv4.0_1.0.0.0__b03f5f7f11d50a3aMicrosoft.VisualStudio.Web.PageInspector.Loader.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Xmlv4.0_4.0.0.0__b77a5c561934e089System.Xml.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.IdentityModelv4.0_4.0.0.0__b77a5c561934e089System.IdentityModel.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl39de30ca2e4929c02_d615ce01Microsoft.Web.WebPages.OAuth.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl38b2c05e5517e33fc_66e2cf01Twilio.Api.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl33c4ebd20c8788af8_d615ce01DotNetOpenAuth.OAuth.Consumer.dll" /out:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51App_Web_testdistance.cshtml.cdcab7d2.s-jejj60.dll" /D:DEBUG /debug+ /optimize- /w:4 /nowarn:1659;1699;1701;612;618 /warnaserror-  "C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51App_Web_testdistance.cshtml.cdcab7d2.s-jejj60.0.cs" "C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51App_Web_testdistance.cshtml.cdcab7d2.s-jejj60.1.cs"


Microsoft (R) Visual C# Compiler version 4.0.30319.18408

for Microsoft (R) .NET Framework 4.5
Copyright (C) Microsoft Corporation. All rights reserved.

c:UsersrobertDocumentsMy Web Sitesbetestdistance.cshtml(3,31): error CS0122: 'mapdistance.DistHandler' is inaccessible due to its protection level
c:UsersrobertDocumentsMy Web Sitesbetestdistance.cshtml(4,5): error CS0118: 'System.Web.WebPages.WebPageRenderingBase.Response' is a 'property' but is used like a 'type'
c:UsersrobertDocumentsMy Web Sitesbetestdistance.cshtml(4,34): error CS0122: 'mapdistance.DistHandler' is inaccessible due to its protection level
c:UsersrobertDocumentsMy Web Sitesbetestdistance.cshtml(5,14): error CS0122: 'mapdistance.DistHandler' is inaccessible due to its protection level

Googling "Is inaccessessible due to its protection level" does not result in anything useful to me at least.

I am wondering what scenario would cause file to work in one application but not in the other?

testdistance is the razor C code that calls DistHandler class file

mapdistance is the name space inside DistHandler

@using mapdistance;
@{
    string locationsRequest = DistHandler.CreateRequest("Pasedena, MD", "Sparks, MD", "&avoid=minimizeTolls");
    Response locationsResponse = DistHandler.MakeRequest(locationsRequest);
    var rt = DistHandler.ProcessResponse2(locationsResponse);


}

And DistHandler.cs, at least the first few lines:

using System;
using System.Net;
using System.Runtime.Serialization.Json;
using BingMapsRESTService.Common.JSON;


namespace mapdistance
{
    static class DistHandler
    {
        static string BingMapsKey = "blahblah";

        public static string CreateRequest(string queryString1, string queryString2, string options)
        {
            string UrlRequest = "http://dev.virtualearth.net/REST/v1/Routes/Driving" +
             "?wp.0=" + queryString1 +
             "&wp.1=" + queryString2 +
             options +
             "&output=json" +
             " &key=" + BingMapsKey;
            return (UrlRequest);
        }

        public static Response MakeRequest(string requestUrl)
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                        throw new Exception(String.Format(
                        "Server error (HTTP {0}: {1}).",
                        response.StatusCode,
                        response.StatusDescription));
                    DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Response));
                    object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
                    Response jsonResponse = objResponse as Response;
                    return jsonResponse;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }


        static public Route ProcessResponse2(Response locationsResponse)
        {
            int locNum = locationsResponse.ResourceSets[0].Resources.Length;

            Route location = (Route)locationsResponse.ResourceSets[0].Resources[0];
            return location;

            //for (int i = 0; i < locNum; i++)
            //{
            //    Route location = (Route)locationsResponse.ResourceSets[0].Resources[i];
            //    var x = location.TravelDistance;
            //}


        }

EDIT: I am adding the main program that calls DistHandler in the VS application (which works)

using System;
using System.Net;
using System.Runtime.Serialization.Json;
using BingMapsRESTService.Common.JSON;
using mapdistance;

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string locationsRequest = DistHandler.CreateRequest("Hunt Valley, MD", "Pasedena, MD", "&avoid=minimizeTolls");
                Response locationsResponse = DistHandler.MakeRequest(locationsRequest);
                var rt =DistHandler.ProcessResponse2(locationsResponse);
                Console.WriteLine(rt.TravelDistance.ToString() + " " + rt.TravelDuration.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.Read();
            }
        }
    }

You’re right. This problem is because by default the accessibility to the classes in .NET are set to be private. This class that you’re showing doesn’t have anything set to it, so the default properties would be applied. 

static class DistHandler

If you can, you can edit it and make it public. Like this

public static class DistHandler

then you will be able to use it. 

Yes, that did it.

Thank you very much!

OWIN OAuth 2.0 Authorization Server

I have read the tutorial http://www.asp.net/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server and realized that this is what I really want
to secure my web APIs. so I downloaded the project code and added to my API’s MVC project. Actually my project is divided into 2 parts, the MVC_application (for displaying data from web API’s) and the MVC_API where my API’s are configured. so now I have three
projects (MVC_application, MVC_API and AuthorizationServer)

My question is: Howcan I link the AuthorizationServer to my project?

In other words: how do I tell the application to call AuthorizationServer before calling the MVC_API project to read the data?

Edit: I think this is what I am supposed to add to my startup.Auth.cs file in the MVC_application project

app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
AuthorizeEndpointPath = new PathString(Paths.AuthorizePath),
TokenEndpointPath = new PathString(Paths.TokenPath),
ApplicationCanDisplayErrors = true,
#if DEBUG
AllowInsecureHttp = true,
#endif
// Authorization server provider which controls the lifecycle of Authorization Server
Provider = new OAuthAuthorizationServerProvider
{
OnValidateClientRedirectUri = ValidateClientRedirectUri,
OnValidateClientAuthentication = ValidateClientAuthentication,
OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials,
OnGrantClientCredentials = GrantClientCredetails
},

// Authorization code provider which creates and receives authorization code
AuthorizationCodeProvider = new AuthenticationTokenProvider
{
OnCreate = CreateAuthenticationCode,
OnReceive = ReceiveAuthenticationCode,
},

// Refresh token provider which creates and receives referesh token
RefreshTokenProvider = new AuthenticationTokenProvider
{
OnCreate = CreateRefreshToken,
OnReceive = ReceiveRefreshToken,
}
});
}

but how will I edit this to fit my code?

Hi lolo512,

Thanks for your post. From your description, you are going to implement an OAuth 2.0 Authorization Server using OWIN OAuth middleware.

This article briefly describes the Katana Architecture. When the server accepts a request from a client, it is  responsible for passing it through a pipeline of OWIN components, which are specified  by the developer’s startup code. These pipeline components
are known as middleware.

http://www.asp.net/aspnet/overview/owin-and-katana/an-overview-of-project-katana

Also some information as below.

An implementation of an OAuth2 authorization server 

https://github.com/thinktecture/Thinktecture.AuthorizationServer

Protecting an ASP.net Web API hosted on Azure with OAuth Simple Web Tokens using the Access Control Service – Server Side

http://blogs.msdn.com/b/africaapps/archive/2013/04/04/part-1-protecting-an-asp-net-web-api-hosted-on-azure-with-oauth-simple-web-tokens-using-the-access-control-service-server-side.aspx

Secure ASP.NET Web API with Windows Azure AD and Microsoft OWIN Components

http://msdn.microsoft.com/en-us/magazine/dn463788.aspx

Use OWIN to Self-Host ASP.NET Web API 2

http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api

Hope these useful to you.

Best Regards

[RESOLVED]How to fetch the twitter feed using asp.net

Hi, anybody have any idea or links tat how to fetch the twitter feed data and show it on asp.net application through API.

I have googled through the same and also tried few code but no luck

If anybody has done the same please share your links or code snippet.

Thanks.

Since the API V1.1 of twitter, they do not allow people to access the tweets that easily.

You have to authenticate first in order to access the timeline and get tweets. - https://dev.twitter.com/docs/auth/oauth#v1-1

You can see the below on how to get the tweets

https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline

[RESOLVED]Twitter Connectivity

Hello every one,

I am working on news website developed on asp.net.

I want to connect my asp.net news application with My Twitter account so that I can post my news on my twitter account as well as my tweets to on my news web page. 

I found many exemples but these all are very complicated and result less flease give me proper path for doing that.

Thanks-

S.Faiq

faiqueali_109@live.com

Hi ,

I feel for your needs Twitterizer is the Best choice.Twitterizer is a .NET class library that provides an easy-to-use interface for
the Twitter web api. It is written for developers. It’s features are easy to discover and follow a consistent design pattern.
http://www.twitterizer.net

Using Twitterizer in one of your projects is easy – just download the Twitterizer assembly, copy it to your application’s /Bin folder, and start coding! The download available at the end of this article includes the latest version of Twitterizer at the time
of writing, version 2.0.1.224. To get the latest version of  Twitterizer, visit
Twitterizer.Net and go to the
Downloads page
.

The Twitterizer library contains a number of classes that model the information exchanged between the client and the server when making Twitter API calls.You can use it to get your recent tweets and also tweet from your website.

Integrating Twitter Into An ASP.NET Website Using OAuth

http://www.4guysfromrolla.com/articles/051210-1.aspx

Best Regards!

 

Thanks for you support!

I already knows about twitterizer and it is used by previous developer who now lefft the compony,

but it is not working at all now I dont know why,

when I am tried to work on this from initial level I got so many problems coz it so confusing for me when I hit the Download page I got 404.

when I hit any particular assembly from main page it shows coding like xml or etc

i-e https://github.com/Twitterizer/Twitterizer/commit/dab6fac7b238d63f80bdf9a0106eee77f3a81a17

so i am confused what to do now..

please help..

 

Hi,

Never mind. There are lots of other libraries out there. Choose the one that works with ASP.NET or .NET.

Twitter Libraries – https://dev.twitter.com/docs/twitter-libraries

Few good ones:

asptwitter

LINQ2Twitter - In addition to being able to download from this site, you can also automatically install LINQ to Twitter into your Visual Studio projects via
NuGet

TweetSharp  — A .net library for Twitter API access

Choose the one that suits your purpose. There are lots of tutorials available in the sites on how to implement.

My suggestion will be to use LINQ2Twitter. They have ample amount of documentation.

Documentation –

http://linqtotwitter.codeplex.com/wikipage?title=Making%20API%20Calls&referringTitle=Home

Twitter Helper with ASP.NET Web Pages –

http://www.asp.net/web-pages/overview/getting-started/twitter-helper

Best Regards!

 

 

[RESOLVED]Mark the classes in WebMatrix.Security.Clients as public / not-sealed

Asp.net webpages 2′s new OAuth features look fantastic. However they’re not usable in a context where testability and inversion-of-control are priorities. Implementations of IAuthenticationClient sealed as are the base classes for implementing OpenID
and OAuth clients. Ideally all the classes in that namespace with the exceptions of the trivial helper classes would be public. This would allow developers to:

  1. Use the OAuth/OpenID facilities in an environment where static classes are frowned on.
  2. implement clients not defined in the library, maybe for some weird provider they have to integrate with

I realize this is asking you to implement or at least test features which aren’t directly related to webmatrix and or the coding patterns webmatrix promotes. However this feature is getting top-billing in the preview articles as part of asp.net not webmatrix
so I’d kind of expect that it meets the needs of all asp.net developers.

feedback link:http://webmatrix.uservoice.com/forums/128313-webmatrix-suggestions/suggestions/2519390-mark-the-classes-in-webmatrix-security-clients-as- 

I’m the PM for this feature. I’ll respond to you on UserVoice. Thanks!

My Mvc wrapper for OAuth stuff:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using WebMatrix.Security;
using WebMatrix.Security.Clients;

namespace MvcApplication3.Security
{
    public interface IMvcOAuthService
    {
        void RegisterClient(IAuthenticationClient client);

        ActionResult RequestAuthentication(string providerName, string actionName, string controllerName,
                                           object routeValues);

        AuthenticationResult VerifyAuthentication(HttpContextBase httpContext);
    }

    public class MvcOAuthService : IMvcOAuthService
    {
        private readonly Dictionary<string, IAuthenticationClient> _clients =
            new Dictionary<string, IAuthenticationClient>(StringComparer.InvariantCultureIgnoreCase);

        public void RegisterClient(IAuthenticationClient client)
        {
            _clients[client.ProviderName] = client;
        }

        public ActionResult RequestAuthentication(string providerName, string actionName, string controllerName,
                                                  object routeValues)
        {
            var client = GetClient(providerName);

            return new RequestAuthenticationActionResult(client, actionName, controllerName, routeValues);
        }

        private IAuthenticationClient GetClient(string providerName, bool throwOnNullClient = true)
        {
            if (string.IsNullOrEmpty(providerName))
                throw new ArgumentException("The argument 'providerName' can not be null or empty.", "providerName");

            var client = _clients.ContainsKey(providerName) ? _clients[providerName] : null;
            if (client == null && throwOnNullClient)
                throw new ArgumentException(String.Format("No provider "{0}" registered", providerName),
                                            "providerName");
            return client;
        }

        public AuthenticationResult VerifyAuthentication(HttpContextBase httpContext)
        {
            string provider = httpContext.Request.QueryString["__provider"];
            var client = GetClient(provider, false);
            if (client == null)
                return AuthenticationResult.Failed;
            else
                return client.VerifyAuthentication(httpContext);
        }
    }

    public class MvcOAuthModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var service = DependencyResolver.Current.GetService<IMvcOAuthService>();
            return service.VerifyAuthentication(controllerContext.HttpContext);
        }

        public void Register()
        {
            ModelBinders.Binders[typeof (AuthenticationResult)] = new MvcOAuthModelBinder();
        }
    }

    public class RequestAuthenticationActionResult : ActionResult
    {
        private readonly IAuthenticationClient _client;
        private readonly object _routeValues;
        private readonly string _actionName;
        private readonly string _controllerName;


        public RequestAuthenticationActionResult(IAuthenticationClient client, string actionName, string controllerName,
                                                 object routeValues)
        {
            _client = client;
            _actionName = actionName;
            _controllerName = controllerName;
            _routeValues = routeValues;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            var urlHelper = new UrlHelper(context.RequestContext);
            var routeValuesDictionary = new RouteValueDictionary(_routeValues ?? new object());
            routeValuesDictionary["__provider"] = _client.ProviderName;
            var redirectUrl = urlHelper.Action(_actionName, _controllerName, routeValuesDictionary);
            _client.RequestAuthentication(context.HttpContext, new Uri(redirectUrl));
        }
    }
}