RSS

Category Archives: OAuth

HTTP Error 500.19 and error code : 0x80070021

By: sgermain

Control Panel -> Programs and Features -> “Turn Windows features on or off” (sidebar) In the Features dialog, go to Internet Information Services -> World Wide Web Services -> Application Development Features ->Check in everything relevant (especially ASP.NET) and click OK. Launch a command prompt in admin mode and run “iisreset” Try your website again. ūüôā

 

Copy from http://forums.iis.net/t/1155232.aspx?HTTP+Error+500+19+Internal+Server+Error+0x80070021+Lock+Violation+with+OWA+Exchange+2007

Advertisements
 
Leave a comment

Posted by on May 21, 2014 in IIS, OAuth

 

OWIN OAuth 2.0 Authorization Server

By Rick Anderson, Hongye Sun and Praburaj Thiagarajan|March 20, 2014

This tutorial will guide you on how to implement an OAuth 2.0 Authorization Server using OWIN OAuth middleware. This is an advanced tutorial that only outlines the steps to create an OWIN OAuth 2.0 Authorization Server. This is not a step by step tutorial. Download the sample code.

Note: This outline should not be intended to be used for creating a secure production app. This tutorial is intended to provide only an outline on how to implement an OAuth 2.0 Authorization Server using OWIN OAuth middleware.

Software versions

Shown in the tutorial Also works with
Windows 8.1 Windows 8, Windows 7
Visual Studio 2013 Visual Studio 2013 Express for Desktop.

Visual Studio 2012 with the latest update should work, but the tutorial has not been tested with it, and some menu selections and dialog boxes are different.

.NET 4.5

Questions and Comments

If you have questions that are not directly related to the tutorial, you can post them athttp://katanaproject.codeplex.com/discussions. For questions and comments regarding the tutorial itself, see the comments section at the bottom of the page.

The  OAuth 2.0 framework enables a third-party app to obtain limited access to an HTTP service. Instead of using the resource owner’s credentials to access a protected resource, the client obtains an access token (which is a string denoting a specific scope, lifetime, and other access attributes). Access tokens are issued to third-party clients by an authorization server with the approval of the resource owner.

This tutorial will cover:

  • How to create an authorization server to support 4 Authorization Grants and refresh tokens.
  • Authorization code grant:
    • Implicit Grant
    • Resource Owner Password Credentials Grant
    • Client Credentials Grant
  • Creating a resource server which is protected by an access token.
  • Creating OAuth 2.0 clients.

Prerequisites

Create an Authorization Server

In this tutorial, we will roughly sketch out how to use OWIN and ASP.NET MVC to create an authorization server. We hope to soon provide a download for the completed sample, as this tutorial does not include each step. First, create an empty web app named AuthorizationServer and install the following packages:

  • Microsoft.AspNet.Mvc
  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.Owin.Security.OAuth
  • Microsoft.Owin.Security.Cookies
  • Microsoft.Owin.Security.Google (Or any other social login package such as Microsoft.Owin.Security.Facebook)

Add an OWIN Startup class under the project root folder named Startup.

usingMicrosoft.Owin;usingOwin;[assembly:OwinStartup(typeof(AuthorizationServer.Startup))]namespaceAuthorizationServer{publicpartialclassStartup{publicvoidConfiguration(IAppBuilder app){ConfigureAuth(app);}}}

Create an App_Start folder. Select the App_Start folder and use Shift+Alt+A to add the downloaded version of theAuthorizationServer\App_Start\Startup.Auth.cs file.

publicvoidConfigureAuth(IAppBuilder app){// Enable the Application Sign In Cookie.
     app.UseCookieAuthentication(newCookieAuthenticationOptions{AuthenticationType="Application",AuthenticationMode=AuthenticationMode.Passive,LoginPath=newPathString(Paths.LoginPath),LogoutPath=newPathString(Paths.LogoutPath),});// Enable the External Sign In Cookie.
     app.SetDefaultSignInAsAuthenticationType("External");
     app.UseCookieAuthentication(newCookieAuthenticationOptions{AuthenticationType="External",AuthenticationMode=AuthenticationMode.Passive,CookieName=CookieAuthenticationDefaults.CookiePrefix+"External",ExpireTimeSpan=TimeSpan.FromMinutes(5),});// Enable Google authentication.
     app.UseGoogleAuthentication();// Setup Authorization Server
     app.UseOAuthAuthorizationServer(newOAuthAuthorizationServerOptions{AuthorizeEndpointPath=newPathString(Paths.AuthorizePath),TokenEndpointPath=newPathString(Paths.TokenPath),ApplicationCanDisplayErrors=true,#if DEBUGAllowInsecureHttp=true,#endif// Authorization server provider which controls the lifecycle of Authorization ServerProvider=newOAuthAuthorizationServerProvider{OnValidateClientRedirectUri=ValidateClientRedirectUri,OnValidateClientAuthentication=ValidateClientAuthentication,OnGrantResourceOwnerCredentials=GrantResourceOwnerCredentials,OnGrantClientCredentials=GrantClientCredetails},// Authorization code provider which creates and receives the authorization code.AuthorizationCodeProvider=newAuthenticationTokenProvider{OnCreate=CreateAuthenticationCode,OnReceive=ReceiveAuthenticationCode,},// Refresh token provider which creates and receives refresh token.RefreshTokenProvider=newAuthenticationTokenProvider{OnCreate=CreateRefreshToken,OnReceive=ReceiveRefreshToken,}});}

The code above enables application/external sign in cookies and Google authentication, which are used by authorization server itself to manage accounts.

The UseOAuthAuthorizationServer extension method is to setup the authorization server. The setup options are:

  • AuthorizeEndpointPath: The request path where client applications will redirect the user-agent in order to obtain the users consent to issue a token or code. It must begin with a leading slash, for example,¬† “/Authorize“.
  • TokenEndpointPath: The request path client applications directly communicate to obtain the access token. It must begin with a leading slash, like “/Token”. If the client is issued a¬†client_secret, it must be provided to this endpoint.
  • ApplicationCanDisplayErrors: Set to¬†true¬†if the web application wants to generate a custom error page for the client validation errors on¬†/Authorize¬†endpoint. This is only needed for cases where the browser is not redirected back to the client application, for example, when the¬†client_id¬†or¬†redirect_uri¬†are incorrect. The¬†/Authorize¬†endpoint should expect to see the “oauth.Error”, “oauth.ErrorDescription”, and “oauth.ErrorUri” properties are added to the OWIN environment.
    Note: If not true, the authorization server will return a default error page with the error details.
  • AllowInsecureHttp: True to allow authorize and token requests to arrive on HTTP URI addresses, and to allow incoming¬†redirect_uri¬†authorize request parameters to have HTTP URI addresses.
    Security Note: This is for development only.
  • Provider: The object provided by the application to process events raised by the Authorization Server middleware. The application may implement the interface fully, or it may create an instance ofOAuthAuthorizationServerProvider¬†and assign delegates necessary for the OAuth flows this server supports.
  • AuthorizationCodeProvider: Produces a single-use authorization code to return to the client application. For the OAuth server to be secure the application¬†MUST¬†provide an instance forAuthorizationCodeProvider¬†where the token produced by the¬†OnCreate/OnCreateAsync¬†event is considered valid for only one call to¬†OnReceive/OnReceiveAsync.
  • RefreshTokenProvider: Produces a refresh token which may be used to produce a new access token when needed. If not provided the authorization server will not return refresh tokens from the¬†/Token¬†endpoint.

Account Management

 OAuth doesn’t care where or how you manage your user account information. It’s ASP.NET Identity which is responsible for it. In this tutorial, we will simplify the account management code and just make sure that user can login using OWIN cookie middleware. Here is the simplified sample code for the AccountController:

publicclassAccountController:Controller{publicActionResultLogin(){var authentication =HttpContext.GetOwinContext().Authentication;if(Request.HttpMethod=="POST"){var isPersistent =!string.IsNullOrEmpty(Request.Form.Get("isPersistent"));if(!string.IsNullOrEmpty(Request.Form.Get("submit.Signin"))){
                authentication.SignIn(newAuthenticationProperties{IsPersistent= isPersistent },newClaimsIdentity(new[]{newClaim(ClaimsIdentity.DefaultNameClaimType,Request.Form["username"])},"Application"));}}returnView();}publicActionResultLogout(){returnView();}publicActionResultExternal(){var authentication =HttpContext.GetOwinContext().Authentication;if(Request.HttpMethod=="POST"){foreach(var key inRequest.Form.AllKeys){if(key.StartsWith("submit.External.")&&!string.IsNullOrEmpty(Request.Form.Get(key))){var authType = key.Substring("submit.External.".Length);
                    authentication.Challenge(authType);returnnewHttpUnauthorizedResult();}}}var identity = authentication.AuthenticateAsync("External").Result.Identity;if(identity !=null){
            authentication.SignOut("External");
            authentication.SignIn(newAuthenticationProperties{IsPersistent=true},newClaimsIdentity(identity.Claims,"Application", identity.NameClaimType, identity.RoleClaimType));returnRedirect(Request.QueryString["ReturnUrl"]);}returnView();}}
privateTaskValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context){if(context.ClientId==Clients.Client1.Id){
        context.Validated(Clients.Client1.RedirectUrl);}elseif(context.ClientId==Clients.Client2.Id){
        context.Validated(Clients.Client2.RedirectUrl);}returnTask.FromResult(0);}privateTaskValidateClientAuthentication(OAuthValidateClientAuthenticationContext context){string clientId;string clientSecret;if(context.TryGetBasicCredentials(out clientId,out clientSecret)||
        context.TryGetFormCredentials(out clientId,out clientSecret)){if(clientId ==Clients.Client1.Id&& clientSecret ==Clients.Client1.Secret){
            context.Validated();}elseif(clientId ==Clients.Client2.Id&& clientSecret ==Clients.Client2.Secret){
            context.Validated();}}returnTask.FromResult(0);}

ValidateClientRedirectUri is used to validate the client with its registered redirect URL.ValidateClientAuthentication checks the basic scheme header and form body to get the client’s credentials.

The login page is shown below:

Review the IETF’s OAuth 2¬†Authorization Code Grant¬†section now.¬†¬†Provider¬†(in the table below) isOAuthAuthorizationServerOptions.Provider, which is of type¬†OAuthAuthorizationServerProvider, which contains all OAuth server events.

Flow steps from Authorization Code Grant section Sample download performs these steps with:
(A) The client initiates the flow by directing the resource owner’s user-agent to the authorization endpoint. The client includes its client identifier, requested scope, local state, and a redirection URI to which the authorization server will send the user-agent back once access is granted (or denied). Provider.MatchEndpoint
Provider.ValidateClientRedirectUri
Provider.ValidateAuthorizeRequest
Provider.AuthorizeEndpoint
(B) The authorization server authenticates the resource owner (via the user-agent) and establishes whether the resource owner grants or denies the client’s access request. <If user grants access>
Provider.MatchEndpoint
Provider.ValidateClientRedirectUri
Provider.ValidateAuthorizeRequest
Provider.AuthorizeEndpoint
AuthorizationCodeProvider.CreateAsync
(C) Assuming the resource owner grants access, the authorization server redirects the user-agent back to the client using the redirection URI provided earlier (in the request or during client registration). …
¬† (D) The client requests an access token from the authorization server’s token endpoint by including the authorization code received in the previous step. When making the request, the client authenticates with the authorization server. The client includes the redirection URI used to obtain the authorization code for verification. Provider.MatchEndpoint
Provider.ValidateClientAuthentication
AuthorizationCodeProvider.ReceiveAsync
Provider.ValidateTokenRequest
Provider.GrantAuthorizationCode
Provider.TokenEndpoint
AccessTokenProvider.CreateAsync
RefreshTokenProvider.CreateAsync

A sample implementation for AuthorizationCodeProvider.CreateAsync and ReceiveAsync to control the creation and validation of authorization code is shown below.

privatereadonlyConcurrentDictionary<string,string> _authenticationCodes =newConcurrentDictionary<string,string>(StringComparer.Ordinal);privatevoidCreateAuthenticationCode(AuthenticationTokenCreateContext context){
     context.SetToken(Guid.NewGuid().ToString("n")+Guid.NewGuid().ToString("n"));
     _authenticationCodes[context.Token]= context.SerializeTicket();}privatevoidReceiveAuthenticationCode(AuthenticationTokenReceiveContext context){string value;if(_authenticationCodes.TryRemove(context.Token,out value)){
         context.DeserializeTicket(value);}}

The code above uses an in-memory concurrent dictionary to store the code and identity ticket and restore the identity after receiving the code. In a real application, it would be replaced by a persistent data store.

The authorization endpoint is for the resource owner to grant access to the client. Usually, it needs a user interface to allow the user to click a button and confirm the grant. OWIN OAuth middleware allows application code to handle the authorization endpoint. In our sample app, we use an MVC controller called OAuthController to handle it. Here is the sample implementation:

publicclassOAuthController:Controller{publicActionResultAuthorize(){if(Response.StatusCode!=200){returnView("AuthorizeError");}var authentication =HttpContext.GetOwinContext().Authentication;var ticket = authentication.AuthenticateAsync("Application").Result;var identity = ticket !=null? ticket.Identity:null;if(identity ==null){authentication.Challenge("Application");returnnewHttpUnauthorizedResult();}var scopes =(Request.QueryString.Get("scope")??"").Split(' ');if(Request.HttpMethod=="POST"){if(!string.IsNullOrEmpty(Request.Form.Get("submit.Grant"))){
                 identity =newClaimsIdentity(identity.Claims,"Bearer", identity.NameClaimType, identity.RoleClaimType);foreach(var scope in scopes){
                     identity.AddClaim(newClaim("urn:oauth:scope", scope));}
                 authentication.SignIn(identity);}if(!string.IsNullOrEmpty(Request.Form.Get("submit.Login"))){
                 authentication.SignOut("Application");
                 authentication.Challenge("Application");returnnewHttpUnauthorizedResult();}}returnView();}}

The¬†Authorize¬†action will first check if the user has logged in to the authorization server. If not, the authentication middleware challenges the caller to authenticate using the ‚ÄúApplication‚ÄĚ cookie and redirects to the login page. (See highlighted code above.) If user has logged in, it will render the Authorize view, as shown below:

If the¬†Grant¬†button is selected, the¬†Authorize¬†action will create a new ‚ÄúBearer‚ÄĚ identity and sign in with it. It will trigger the authorization server to generate a bearer token and send it back to the client with JSON payload.

Implicit Grant

Refer to the IETF’s OAuth 2¬†Implicit Grant¬†section now.

The Implicit Grant flow shown in Figure 4 is the flow and mapping which the OWIN OAuth middleware follows.

Flow steps from Implicit Grant section Sample download performs these steps with:
(A) The client initiates the flow by directing the resource owner’s user-agent to the authorization endpoint. The client includes its client identifier, requested scope, local state, and a redirection URI to which the authorization server will send the user-agent back once access is granted (or denied). Provider.MatchEndpoint
Provider.ValidateClientRedirectUri
Provider.ValidateAuthorizeRequest
Provider.AuthorizeEndpoint
(B) The authorization server authenticates the resource owner (via the user-agent) and establishes whether the resource owner grants or denies the client’s access request. <If user grants access>
Provider.MatchEndpoint
Provider.ValidateClientRedirectUri
Provider.ValidateAuthorizeRequest
Provider.AuthorizeEndpoint
AuthorizationCodeProvider.CreateAsync
(C) Assuming the resource owner grants access, the authorization server redirects the user-agent back to the client using the redirection URI provided earlier (in the request or during client registration). …
¬† (D) The client requests an access token from the authorization server’s token endpoint by including the authorization code received in the previous step. When making the request, the client authenticates with the authorization server. The client includes the redirection URI used to obtain the authorization code for verification.

Since we already implemented the authorization endpoint (OAuthController.Authorize action) for authorization code grant, it automatically enables implicit flow as well.

Note: Provider.ValidateClientRedirectUri is used to validate the client ID with its redirection URL, which protects the implicit grant flow from sending the access token to malicious clients (Man-in-the-middle attack).

Resource Owner Password Credentials Grant

Refer to the IETF’s OAuth 2¬†Resource Owner Password Credentials Grant¬†section now.

The Resource Owner Password Credentials Grant flow shown in Figure 5 is the flow and mapping which the OWIN OAuth middleware follows.

Flow steps from Resource Owner Password Credentials Grant section Sample download performs these steps with:
(A) The resource owner provides the client with its username and password.
(B) The client requests an access token from the authorization server’s token endpoint by including the credentials received from the resource owner. When making the request, the client authenticates with the authorization server. Provider.MatchEndpoint
Provider.ValidateClientAuthentication Provider.ValidateTokenRequest
Provider.GrantResourceOwnerCredentials Provider.TokenEndpoint AccessToken
Provider.CreateAsync
RefreshTokenProvider.CreateAsync
(C) The authorization server authenticates the client and validates the resource owner credentials, and if valid, issues an access token.

Here is the sample implementation for Provider.GrantResourceOwnerCredentials:

privateTaskGrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context){var identity =newClaimsIdentity(newGenericIdentity(
        context.UserName,OAuthDefaults.AuthenticationType), 
        context.Scope.Select(x =>newClaim("urn:oauth:scope", x)));

     context.Validated(identity);returnTask.FromResult(0);}
The code above is intended to explain this section of the tutorial and should not be used in secure or production apps. It does not check the resource owners credentials. It assumes every credential is valid and creates a new identity for it. The new identity will be used to generate the access token and refresh token. Please replace the code with your own secure account management code.

Client Credentials Grant

Refer to the IETF’s OAuth 2¬†Client Credentials Grant¬†section now.

The Client Credentials Grant flow shown in Figure 6 is the flow and mapping which the OWIN OAuth middleware follows.

Flow steps from Client Credentials Grant  section Sample download performs these steps with:
(A) The client authenticates with the authorization server and requests an access token from the token endpoint. Provider.MatchEndpoint
Provider.ValidateClientAuthentication Provider.ValidateTokenRequest
Provider.GrantClientCredentials
Provider.TokenEndpoint
AccessTokenProvider.CreateAsync
RefreshTokenProvider.CreateAsync
 (B) The authorization server authenticates the client, and if valid, issues an access token.

Here is the sample implementation for Provider.GrantClientCredentials:

privateTaskGrantClientCredetails(OAuthGrantClientCredentialsContext context){var identity =newClaimsIdentity(newGenericIdentity(
        context.ClientId,OAuthDefaults.AuthenticationType), 
        context.Scope.Select(x =>newClaim("urn:oauth:scope", x)));

     context.Validated(identity);returnTask.FromResult(0);}
The code above is intended to explain this section of the tutorial and should not be used in secure or production apps.  Please replace the code with your own secure client management code.

Refresh Token

Refer to the IETF’s OAuth 2¬†Refresh Token¬†section now.

The Refresh Token  flow shown in Figure 2 is the flow and mapping which the OWIN OAuth middleware follows.

Flow steps from Client Credentials Grant  section Sample download performs these steps with:
(G) The client requests a new access token by authenticating with the authorization server and presenting the refresh token. The client authentication requirements are based on the client type and on the authorization server policies. Provider.MatchEndpoint
Provider.ValidateClientAuthentication RefreshTokenProvider.ReceiveAsync
Provider.ValidateTokenRequest
Provider.GrantRefreshToken
Provider.TokenEndpoint
AccessTokenProvider.CreateAsync
RefreshTokenProvider.CreateAsync
(H) The authorization server authenticates the client and validates the refresh token, and if valid, issues a new access token (and, optionally, a new refresh token).

Here is the sample implementation for Provider.GrantRefreshToken:

publicvoidConfigureAuth(IAppBuilder app){// Code removed for clarity     // Refresh token provider which creates and receives refresh token.RefreshTokenProvider=newAuthenticationTokenProvider{OnCreate=CreateRefreshToken,OnReceive=ReceiveRefreshToken,}});}
privatevoidCreateRefreshToken(AuthenticationTokenCreateContext context){
     context.SetToken(context.SerializeTicket());}privatevoidReceiveRefreshToken(AuthenticationTokenReceiveContext context){
     context.DeserializeTicket(context.Token);}

Create a Resource Server which is protected by Access Token

 Create an empty web app project and install following packages in the project:

  • Microsoft.AspNet.WebApi.Owin
  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.Owin.Security.OAuth

Create a startup class and configure authentication and Web API. See AuthorizationServer\ResourceServer\Startup.csin the sample download.

[assembly:OwinStartup(typeof(ResourceServer.Startup))]namespaceResourceServer{publicpartialclassStartup{publicvoidConfiguration(IAppBuilder app){ConfigureAuth(app);ConfigureWebApi(app);}}}

See AuthorizationServer\ResourceServer\App_Start\Startup.Auth.cs in the sample download.

usingMicrosoft.Owin.Cors;usingMicrosoft.Owin.Security.OAuth;usingOwin;namespaceResourceServer{publicpartialclassStartup{publicvoidConfigureAuth(IAppBuilder app){
            app.UseCors(CorsOptions.AllowAll);

            app.UseOAuthBearerAuthentication(newOAuthBearerAuthenticationOptions{});}}}

See AuthorizationServer\ResourceServer\App_Start\Startup.WebApi.cs in the sample download.

usingMicrosoft.Owin.Security.OAuth;usingOwin;usingSystem.Web.Http;namespaceResourceServer{publicpartialclassStartup{publicvoidConfigureWebApi(IAppBuilder app){var config =newHttpConfiguration();// Web API configuration and services// Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(newHostAuthenticationFilter(OAuthDefaults.AuthenticationType));// Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name:"DefaultApi",
                routeTemplate:"api/{controller}/{id}",
                defaults:new{ id =RouteParameter.Optional});

            app.UseWebApi(config);}}}
  • UseCors¬†method allows CORS for all domains.
  • UseOAuthBearerAuthentication¬†method enables OAuth bearer token authentication middleware which will receive and validate bearer token from authorization header in the request.
  • Config.SuppressDefaultHostAuthenticaiton¬†suppresses default host authenticated principal from the app, therefore all requests will be anonymous after this call.
  • HostAuthenticationFilter¬†enables authentication just for the specified authentication type. In this case, it‚Äôs bearer authentication type.

In order to demonstrate the authenticated identity, we create an ApiController to output current user’s claims.

namespaceResourceServer.Controllers{[Authorize]publicclassMeController:ApiController{// GET api/<controller>publicIEnumerable<object>Get(){var identity =User.IdentityasClaimsIdentity;return identity.Claims.Select(c =>new{Type= c.Type,Value= c.Value});}}}

If the authorization server and  the resource server are not on the same computer, the OAuth middleware will use the different machine keys to encrypt and decrypt bearer access token. In order to share the same private key between both projects, we add the same machinekey setting in both web.config files.

<configuration><appSettings><!-- Keys removed for clarity. --></appSettings><system.web><compilationdebug="true"targetFramework="4.5"/><httpRuntimetargetFramework="4.5"/><machineKeydecryptionKey="Enter decryption Key here"validation="SHA1"validationKey="Enter validation Key here"/></system.web><runtime><!-- Keys removed for clarity. --></runtime></configuration>

Create OAuth 2.0 Clients

We use the DotNetOpenAuth.OAuth2.Client  NuGet package to simplify the client code.

Authorization Code Grant Client

This client is an MVC application. It will trigger an authorization code grant flow to get the access token from backend. It has a single page as shown below:

  • The¬†Authorize¬†button will redirect browser to the authorization server to notify the resource owner to grant access to this client.
  • The¬†Refresh¬†button will get a new access token and refresh token using the current refresh token.
  • The¬†Access Protected Resource API¬†button will call the resource server to get current user‚Äôs claims data and show them on the page.

Here is the sample code of the HomeController of the client.

usingConstants;usingDotNetOpenAuth.OAuth2;usingSystem;usingSystem.Net.Http;usingSystem.Web.Mvc;namespaceAuthorizationCodeGrant.Controllers{publicclassHomeController:Controller{privateWebServerClient _webServerClient;publicActionResultIndex(){ViewBag.AccessToken=Request.Form["AccessToken"]??"";ViewBag.RefreshToken=Request.Form["RefreshToken"]??"";ViewBag.Action="";ViewBag.ApiResponse="";InitializeWebServerClient();var accessToken =Request.Form["AccessToken"];if(string.IsNullOrEmpty(accessToken)){var authorizationState = _webServerClient.ProcessUserAuthorization(Request);if(authorizationState !=null){ViewBag.AccessToken= authorizationState.AccessToken;ViewBag.RefreshToken= authorizationState.RefreshToken;ViewBag.Action=Request.Path;}}if(!string.IsNullOrEmpty(Request.Form.Get("submit.Authorize"))){var userAuthorization = _webServerClient.PrepareRequestUserAuthorization(new[]{"bio","notes"});
            userAuthorization.Send(HttpContext);Response.End();}elseif(!string.IsNullOrEmpty(Request.Form.Get("submit.Refresh"))){var state =newAuthorizationState{AccessToken=Request.Form["AccessToken"],RefreshToken=Request.Form["RefreshToken"]};if(_webServerClient.RefreshAuthorization(state)){ViewBag.AccessToken= state.AccessToken;ViewBag.RefreshToken= state.RefreshToken;}}elseif(!string.IsNullOrEmpty(Request.Form.Get("submit.CallApi"))){var resourceServerUri =newUri(Paths.ResourceServerBaseAddress);var client =newHttpClient(_webServerClient.CreateAuthorizingHandler(accessToken));var body = client.GetStringAsync(newUri(resourceServerUri,Paths.MePath)).Result;ViewBag.ApiResponse= body;}returnView();}privatevoidInitializeWebServerClient(){var authorizationServerUri =newUri(Paths.AuthorizationServerBaseAddress);var authorizationServer =newAuthorizationServerDescription{AuthorizationEndpoint=newUri(authorizationServerUri,Paths.AuthorizePath),TokenEndpoint=newUri(authorizationServerUri,Paths.TokenPath)};
         _webServerClient =newWebServerClient(authorizationServer,Clients.Client1.Id,Clients.Client1.Secret);}}}

DotNetOpenAuth requires SSL by default. Since our demo is using HTTP, you need to add following setting in the config file:

<configuration><!-- Markup removed for clarity. --><dotNetOpenAuth><messagingrelaxSslRequirements="true"/></dotNetOpenAuth></configuration>
Security Note: Never disable SSL in a production app. Your login credentials are now being sent in clear-text across the wire. The code above is just for local sample debugging and exploration.

Implicit Grant Client

This client is using JavaScript to:

  1. Open a new window and redirect to the authorize endpoint of the Authorization Server.
  2. Get the access token from URL fragments when it redirects back.

The following image shows this process:

The client should have two pages: one for home page and the other for callback.

Here is the sample JavaScript code found in the Index.cshtml file:

<scripttype="text/javascript">(function($){var authorizeUri ='@(Paths.AuthorizationServerBaseAddress + Paths.AuthorizePath)';var tokenUri ='@(Paths.AuthorizationServerBaseAddress + Paths.TokenPath)';var apiUri ='@(Paths.ResourceServerBaseAddress + Paths.MePath)';var returnUri ='@Paths.ImplicitGrantCallBackPath';

        $('#Authorize').click(function(){var nonce ='my-nonce';var uri = addQueryString(authorizeUri,{'client_id':'7890ab','redirect_uri': returnUri,'state': nonce,'scope':'bio notes','response_type':'token',});

            window.oauth ={};
            window.oauth.signin =function(data){if(data.state !== nonce){return;}

                $('#AccessToken').val(data.access_token);}

            window.open(uri,'Authorize','width=640,height=480');});

        $('#CallApi').click(function(){
            $.ajax(apiUri,{
                beforeSend:function(xhr){
                    xhr.setRequestHeader('Authorization','Bearer '+ $('#AccessToken').val());},
                dataType:'text',
                cache:false,
                success:function(data){
                    console.log(data);
                    $('#output').text(data);}});});function addQueryString(uri, parameters){var delimiter =(uri.indexOf('?')==-1)?'?':'&';for(var parameterName in parameters){var parameterValue = parameters[parameterName];
                uri += delimiter + encodeURIComponent(parameterName)+'='+ encodeURIComponent(parameterValue);
                delimiter ='&';}return uri;}})(jQuery);</script>

Here is the callback handling code in SignIn.cshtml file:

<scripttype="text/javascript">(function($){function getFragment(){if(window.location.hash.indexOf("#")===0){return parseQueryString(window.location.hash.substr(1));}else{return{};}}function parseQueryString(queryString){var data ={},
                pairs, pair, separatorIndex, escapedKey, escapedValue, key, value;if(queryString ===null){return data;}

            pairs = queryString.split("&");for(var i =0; i < pairs.length; i++){
                pair = pairs[i];
                separatorIndex = pair.indexOf("=");if(separatorIndex ===-1){
                    escapedKey = pair;
                    escapedValue =null;}else{
                    escapedKey = pair.substr(0, separatorIndex);
                    escapedValue = pair.substr(separatorIndex +1);}

                key = decodeURIComponent(escapedKey);
                value = decodeURIComponent(escapedValue);

                data[key]= value;}return data;}var fragments = getFragment();if(window.opener && window.opener.oauth && window.opener.oauth.signin){
            window.opener.oauth.signin(fragments);}
        window.close();})(jQuery);</script>
A best practice is to move the JavaScript to an external file and not embed it with the Razor markup. To keep this sample simple, they have been combined.

Resource Owner Password Credentials Grant Client

We uses a console app to demo this client. Here is the code:

classProgram{privatestaticWebServerClient _webServerClient;privatestaticstring _accessToken;staticvoidMain(string[] args){InitializeWebServerClient();Console.WriteLine("Requesting Token...");RequestToken();Console.WriteLine("Access Token: {0}", _accessToken);Console.WriteLine("Access Protected Resource");AccessProtectedResource();}privatestaticvoidInitializeWebServerClient(){var authorizationServerUri =newUri(Paths.AuthorizationServerBaseAddress);var authorizationServer =newAuthorizationServerDescription{AuthorizationEndpoint=newUri(authorizationServerUri,Paths.AuthorizePath),TokenEndpoint=newUri(authorizationServerUri,Paths.TokenPath)};
        _webServerClient =newWebServerClient(authorizationServer,Clients.Client1.Id,Clients.Client1.Secret);}privatestaticvoidRequestToken(){var state = _webServerClient.GetClientAccessToken(new[]{"bio","notes"});
        _accessToken = state.AccessToken;}privatestaticvoidAccessProtectedResource(){var resourceServerUri =newUri(Paths.ResourceServerBaseAddress);var client =newHttpClient(_webServerClient.CreateAuthorizingHandler(_accessToken));var body = client.GetStringAsync(newUri(resourceServerUri,Paths.MePath)).Result;Console.WriteLine(body);}}

Client Credentials Grant Client

Similar to the Resource Owner Password Credentials Grant, here is console app code:

classProgram{privatestaticWebServerClient _webServerClient;privatestaticstring _accessToken;staticvoidMain(string[] args){InitializeWebServerClient();Console.WriteLine("Requesting Token...");RequestToken();Console.WriteLine("Access Token: {0}", _accessToken);Console.WriteLine("Access Protected Resource");AccessProtectedResource();}privatestaticvoidInitializeWebServerClient(){var authorizationServerUri =newUri(Paths.AuthorizationServerBaseAddress);var authorizationServer =newAuthorizationServerDescription{AuthorizationEndpoint=newUri(authorizationServerUri,Paths.AuthorizePath),TokenEndpoint=newUri(authorizationServerUri,Paths.TokenPath)};
        _webServerClient =newWebServerClient(authorizationServer,Clients.Client1.Id,Clients.Client1.Secret);}privatestaticvoidRequestToken(){var state = _webServerClient.ExchangeUserCredentialForToken("test","test",new[]{"bio","notes"});
        _accessToken = state.AccessToken;}privatestaticvoidAccessProtectedResource(){var resourceServerUri =newUri(Paths.ResourceServerBaseAddress);var client =newHttpClient(_webServerClient.CreateAuthorizingHandler(_accessToken));var body = client.GetStringAsync(newUri(resourceServerUri,Paths.MePath)).Result;Console.WriteLine(body);}}
 
Leave a comment

Posted by on April 24, 2014 in C#, OAuth, Web API ASP.NET