Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Warren Buckley 2106 posts 4836 karma points MVP 7x admin c-trib
    Jun 16, 2015 @ 10:17
    Warren Buckley
    0

    UmbracoRestApi project - How do I authorise?

    Hello all
    So from the CodeGarden15 Keynote Shannon & Per demoed a HAL specification side line project named UmbracoRestApi.

    I have downloaded the 7.3 beta along with the identity NuGet package & UmbracoRestApi package to play with all these lovely new things & start exploring.

    So I wanted to start exploring & seeing how to use the API so I logged into the Umbraco backoffice, so that I assume a cookie gets set for me so that when I goto /umbraco/rest/v1/content as listed on the GitHub project readme page. I get a 401 Unauthorised HTTP response code when using the Chrome Extension POSTMAN for API exploring.

    I equally get the same result when browsing to the same URL endpoint using the HAL browser that was demoed in the keynote here - http://haltalk.herokuapp.com/explorer/browser.html

    So if anyone can give me some pointers on this project so I can start playing & exploring please that would be fantastic :)

    Cheers,
    Warren

  • Shannon Deminick 1526 posts 5272 karma points MVP 3x
    Jun 17, 2015 @ 12:22
    Shannon Deminick
    2

    Postman doesn't really use your cookies from your browser session... though you could copy and paste the cookie values in from your session and send them on up.

    Alternatively, you can use OAuth tokens to get the job done. When you install UmbracoCms.RestApi (https://github.com/umbraco/UmbracoRestApi), it also installs the IdentityExtensions package (https://github.com/umbraco/UmbracoIdentityExtensibility) which includes a very simple auth token server.

    Unfortunately when the rest api installs, it doesn't show the readme from the identity extensions package. If you have a look at the file that it's installed:

    /AppStart/UmbracoStandardOwinStartup.cs (there's also a 'Custom' startup one too). If you read through all of the notes it tells you how to enable the auth server at the bottom. Here's a ref: https://github.com/umbraco/UmbracoIdentityExtensions/blob/master/src/Umbraco.IdentityExtensions/AppStart/UmbracoStandardOwinStartup.cs.pp#L50

    You probably don't need to use a custom CORS policy at all, the default (without specifying one) will work in most cases. Then you can have a look at the file called UmbracoAuthTokenServerExtensions.cs (ref here: https://github.com/umbraco/UmbracoIdentityExtensions/blob/master/src/Umbraco.IdentityExtensions/App_Start/UmbracoAuthTokenServerExtensions.cs.pp)

    You can read through this class and change it if you need a more advanced token server (or you can use this code to create your own). You'll note that the path for the token auth is:

    /umbraco/oauth/token

    Here's a cURL example of calling this endpoint:

    curl -X POST -H "Accept: application/json" -H "Content-Type: application/x-www-form-urlencoded" -H "Cache-Control: no-cache" -d 'grant_type=password&username=admin&password=test' http://localhost:7300/umbraco/oauth/token

    The response will look something like (example, the token will be much larger):

    {"access_token":"123456789456789456789","token_type":"bearer","expires_in":86399}

    Then when you make a request to an Umbraco resource you include the Authorization header with the access_token, here’s a cURL example:

    curl -X GET -H "Accept: application/json, text/plain, */*" -H "Authorization: Bearer 123456789456789456789" -H "Cache-Control: no-cache" http://localhost:7300/umbraco/backoffice/UmbracoApi/Content/GetById?id=2168

    Note: the space between “Bearer” and the actual token in the Authorization header.

    I haven't had time to write this documentation yet, but ideally this sort of stuff would be included in the file's we ship so that they are self-documenting.

  • Warren Buckley 2106 posts 4836 karma points MVP 7x admin c-trib
    Jun 18, 2015 @ 09:48
    Warren Buckley
    0

    Hi Shannon,
    OK I have tried your steps and I have uncommented/added app.UseUmbracoBackOfficeTokenAuth(); in my OWIN Startup class

    This calls the extension class in App_Start folder UmbracoAuthTokenServerExtensions.cs

    I can see the example code as is with most of it commented out, just authorises the user or says this a valid request without checking the username & password. However I get an exception rather than a JSON blob when doing the POST to the /umbraco/oauth/token endpoint

    To help explain whats going on & how I have this setup I recorded a quick screencast to make life easier. As you may be able to spot very quickly where I have gone wrong or forgotten to configure or set something up.

    https://www.youtube.com/watch?v=ZQf5XRGEot0

    Cheers,
    Warren

  • Shannon Deminick 1526 posts 5272 karma points MVP 3x
    Jun 18, 2015 @ 10:17
    Shannon Deminick
    0

    Firstly, the code DOES validate username/password. The commented out code that you were looking at is if you want to extend/enhance any functionality, you don't need to change anything there unless you need more functionality. We ship it as-is and it works... but it's just a very basic auth token server. All of that is part of ASP.Net Identity.

    I'll install a new version of Umbraco 7.3 and see what happens.

  • Warren Buckley 2106 posts 4836 karma points MVP 7x admin c-trib
    Jun 18, 2015 @ 10:22
    Warren Buckley
    0

    Ah OK from what I understood from the comments & the example code further down I was under the impression that all requests with any username or password was authenticating.

    So some clearer notes & comments in these files may be helpful to avoid confusion of what to uncomment or not.

    For reference I was trying an invalid username & password, and I would assume I get some kind of response back even a 401 HTTP Status Code of Unauthorised.

    Thanks for the help.

  • Aaron Powell 1708 posts 3046 karma points c-trib
    Jun 18, 2015 @ 10:32
    Aaron Powell
    0

    Did you update the owin:appStartup to point at the new Identity base class?

    I had to change it to be UmbracoStandardOwinStartup and uncommented this line:

    app.UseUmbracoBackOfficeTokenAuth(new BackOfficeAuthServerProviderOptions());
    
  • Warren Buckley 2106 posts 4836 karma points MVP 7x admin c-trib
    Jun 18, 2015 @ 10:47
    Warren Buckley
    0

    Yes Aaron, mine is as follows:

    using Microsoft.Owin;
    using Owin;
    using Umbraco.Core;
    using Umbraco.Core.Security;
    using Umbraco.RestApi;
    using Umbraco.Web.Security.Identity;
    using Umbraco.IdentityExtensions;
    using UmbracoPlayground;
    
    //To use this startup class, change the appSetting value in the web.config called 
    // "owin:appStartup" to be "CustomUmbracoOwinStartup"
    
    [assembly: OwinStartup("UmbracoCustomOwinStartup", typeof(UmbracoCustomOwinStartup))]
    
    namespace UmbracoPlayground
    {
        /// <summary>
        /// A custom way to configure OWIN for Umbraco
        /// </summary>
        /// <remarks>
        /// The startup type is specified in appSettings under owin:appStartup - change it to "CustomUmbracoStartup" to use this class
        /// 
        /// This startup class would allow you to customize the Identity IUserStore and/or IUserManager for the Umbraco Backoffice
        /// </remarks>
        public class UmbracoCustomOwinStartup
        {
            public void Configuration(IAppBuilder app)
            {
                //Configure the Identity user manager for use with Umbraco Back office 
                // (EXPERT: an overload accepts a custom BackOfficeUserStore implementation)
                app.ConfigureUserManagerForUmbracoBackOffice(
                    ApplicationContext.Current,
                    MembershipProviderExtensions.GetUsersMembershipProvider().AsUmbracoMembershipProvider());
    
                //Ensure owin is configured for Umbraco back office authentication
                app.UseUmbracoBackOfficeCookieAuthentication(ApplicationContext.Current);
                app.UseUmbracoBackOfficeExternalCookieAuthentication(ApplicationContext.Current);
                app.ConfigureBackOfficeGoogleAuth(
                        "903993111999-i8em676kego06771hn7foooooooooBaaaaar.apps.googleusercontent.com",
                        "L46oZKTgwJCNNmsrmuVDLrSr");
    
    
                app.UseUmbracoBackOfficeTokenAuth();
    
                /* 
                 * Configure external logins for the back office:
                 * 
                 * Depending on the authentication sources you would like to enable, you will need to install 
                 * certain Nuget packages. 
                 * 
                 * For Google auth:                 Install-Package UmbracoCms.IdentityExtensions.Google
                 * For Facebook auth:                   Install-Package UmbracoCms.IdentityExtensions.Facebook
                 * For Microsoft auth:                  Install-Package UmbracoCms.IdentityExtensions.Microsoft
                 * For Azure ActiveDirectory auth:      Install-Package UmbracoCms.IdentityExtensions.AzureActiveDirectory
                 * 
                 * There are many more providers such as Twitter, Yahoo, ActiveDirectory, etc... most information can
                 * be found here: http://www.asp.net/web-api/overview/security/external-authentication-services
                 * 
                 * For sample code on using external providers with the Umbraco back office, install one of the 
                 * packages listed above to review it's code samples 
                 *  
                 */
    
                /*
                 * To configure a simple auth token server for the back office:
                 *             
                 * By default the CORS policy is to allow all requests
                 * 
                 *      app.UseUmbracoBackOfficeTokenAuth(new BackOfficeAuthServerProviderOptions());
                 *      
                 * If you want to have a custom CORS policy for the token server you can provide
                 * a custom CORS policy, example: 
                 * 
                 *      app.UseUmbracoBackOfficeTokenAuth(
                 *          new BackOfficeAuthServerProviderOptions()
                 *              {
                 *                  //Modify the CorsPolicy as required
                 *                  CorsPolicy = new CorsPolicy()
                 *                  {
                 *                      AllowAnyHeader = true,
                 *                      AllowAnyMethod = true,
                 *                      Origins = { "http://mywebsite.com" }                
                 *                  }
                 *              });
                 */
            }
        }
    }
    

    And my web.config appsetting is as follows:

    <add key="owin:appStartup" value="UmbracoCustomOwinStartup" />
    
  • Aaron Powell 1708 posts 3046 karma points c-trib
    Jun 18, 2015 @ 10:35
    Aaron Powell
    0

    Also, looking at the postman call you made I noticed you didn't provide the client_id.

    Here's my postman sample:

    {
        "version": 1,
        "collections": [{
            "id": "cfd33fd3-57d7-99f1-23b8-d36add5f52fb",
            "name": "umbraco restapi",
            "timestamp": 1434609445329,
            "requests": [{
                "collectionId": "cfd33fd3-57d7-99f1-23b8-d36add5f52fb",
                "id": "a1f45fe0-9ece-aae4-f1a8-f5339065ecdb",
                "name": "login",
                "description": "",
                "url": "http://localhost:49199/umbraco/oauth/token",
                "method": "POST",
                "headers": "",
                "data": [{
                    "key": "grant_type",
                    "value": "password",
                    "type": "text"
                }, {
                    "key": "username",
                    "value": "[email protected]",
                    "type": "text"
                }, {
                    "key": "password",
                    "value": "password",
                    "type": "text"
                }, {
                    "key": "client_id",
                    "value": "umbraco",
                    "type": "text"
                }, {
                    "key": "client_secret",
                    "value": "",
                    "type": "text"
                }],
                "dataMode": "urlencoded",
                "timestamp": 0,
                "responses": [],
                "version": 2
            }]
        }],
        "environments": [],
        "headerPresets": [],
        "globals": []
    }
    
  • Warren Buckley 2106 posts 4836 karma points MVP 7x admin c-trib
    Jun 18, 2015 @ 10:51
    Warren Buckley
    0

    I tried the client_id being set to umbraco, I still get the same exception as follows:

    [NullReferenceException: Object reference not set to an instance of an object.]
       Microsoft.AspNet.Identity.CultureAwaiter`1.get_IsCompleted() +31
       Microsoft.AspNet.Identity.<FindAsync>d__12.MoveNext() +355
       System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
       System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
       System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
       Umbraco.IdentityExtensions.<GrantResourceOwnerCredentials>d__0.MoveNext() in x:\Projects\Umbraco\UmbracoIdentityExtensibility\src\Umbraco.IdentityExtensions\BackOfficeAuthServerProvider.cs:48
       System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
       System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
       System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
       Microsoft.Owin.Security.OAuth.<InvokeTokenEndpointResourceOwnerPasswordCredentialsGrantAsync>d__3f.MoveNext() +863
       System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
       System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
       System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
       Microsoft.Owin.Security.OAuth.<InvokeTokenEndpointAsync>d__22.MoveNext() +2336
       System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
       System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
       System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
       Microsoft.Owin.Security.OAuth.<InvokeAsync>d__0.MoveNext() +1724
       System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
       System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
       System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
       Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +664
       System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
       System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
       System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
       Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +936
       System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
       System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
       System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
       Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +936
       System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
       System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
       System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
       Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +936
       System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
       System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
       System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
       Microsoft.AspNet.Identity.Owin.<Invoke>d__0.MoveNext() +641
       System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
       System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
       System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
       Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +287
       System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
       System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
       System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
       Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<DoFinalWork>d__2.MoveNext() +272
       System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +22
       Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow() +33
       Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +150
       Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +42
       System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +415
       System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
    
  • Aaron Powell 1708 posts 3046 karma points c-trib
    Jun 18, 2015 @ 11:01
    Aaron Powell
    0

    I haven't tried with UmbracoCustomOwinStartup yet, I've only used UmbracoStandardOwinStartup which inherits from UmbracoDefaultOwinStartup. See here.

  • Warren Buckley 2106 posts 4836 karma points MVP 7x admin c-trib
    Jun 18, 2015 @ 11:14
    Warren Buckley
    0

    Interesting if I switch to using UmbracoStandardOwinStartup this then works fine. Is it not possible to use the CustomOwinStartup Shannon?

    As would like to use the Google Identity Login & experiment with the new RESTApi bits too.

    Can you offer a solution or advice on how to make this work in the CustomOwinStartup class?

  • Shannon Deminick 1526 posts 5272 karma points MVP 3x
    Jun 18, 2015 @ 11:34
    Shannon Deminick
    100

    Is it not possible to use the CustomOwinStartup Shannon?

    Obviously this is a bug

    Here is the readme that explains the difference between the 2 startup classes :

    https://github.com/umbraco/UmbracoIdentityExtensions/blob/master/build/Readme.txt

    There's also some docs in the classes about what these do:

    https://github.com/umbraco/UmbracoIdentityExtensions/blob/master/src/Umbraco.IdentityExtensions/App_Start/UmbracoCustomOwinStartup.cs.pp#L22

    To recap:

    "UmbracoStandardOwinStartup" = use this unless you are doing EXPERT things like customizing the BackOfficeUserStore or user manager, otherwise you need to use "UmbracoCustomOwinStartup" ... that is the ONLY difference

  • Aaron Powell 1708 posts 3046 karma points c-trib
    Jun 18, 2015 @ 11:44
    Aaron Powell
    0

    Not sure if it's a bug or if it's something in Warren's install as I was able to use the CustomOwinStartup with no problem myself.

  • Warren Buckley 2106 posts 4836 karma points MVP 7x admin c-trib
    Jun 18, 2015 @ 11:36
    Warren Buckley
    0

    Yeh I am no way an expert, just hacking around trying to figure out what the hell I should be doing :-P

    Thanks for the help guys!

  • Shannon Deminick 1526 posts 5272 karma points MVP 3x
    Jun 18, 2015 @ 11:40
    Shannon Deminick
    0

    This is the class that you said isn't documented very clearly:

    https://github.com/umbraco/UmbracoIdentityExtensions/blob/master/src/Umbraco.IdentityExtensions/App_Start/UmbracoAuthTokenServerExtensions.cs.pp

    Happy to accept a PR to make it more clear if you don't think that it is clear enough but IMO there is quite a lot of detail there

  • Shannon Deminick 1526 posts 5272 karma points MVP 3x
    Jun 18, 2015 @ 11:42
    Shannon Deminick
    0

    Can you also create an issue on the github tracker for identity extensions describing the issue when using the UmbracoCustomOwinStartup ?

    https://github.com/umbraco/UmbracoIdentityExtensions/issues

  • Warren Buckley 2106 posts 4836 karma points MVP 7x admin c-trib
    Jun 18, 2015 @ 11:50
Please Sign in or register to post replies

Write your reply to:

Draft