1- namespace OAuthClient {
2- using System ;
3- using System . Collections . Generic ;
4- using System . Globalization ;
5- using System . Linq ;
6- using System . Net ;
7- using System . ServiceModel ;
8- using System . ServiceModel . Channels ;
9- using System . ServiceModel . Security ;
10- using System . Web ;
11- using System . Web . UI ;
12- using System . Web . UI . WebControls ;
13- using DotNetOpenAuth . OAuth2 ;
14-
15- using SampleResourceServer ;
16-
17- public partial class SampleWcf2 : System . Web . UI . Page {
18- /// <summary>
19- /// The OAuth 2.0 client object to use to obtain authorization and authorize outgoing HTTP requests.
20- /// </summary>
21- private static readonly WebServerClient Client ;
22-
23- /// <summary>
24- /// The details about the sample OAuth-enabled WCF service that this sample client calls into.
25- /// </summary>
26- private static AuthorizationServerDescription authServerDescription = new AuthorizationServerDescription {
27- TokenEndpoint = new Uri ( "http://localhost:50172/OAuth/Token" ) ,
28- AuthorizationEndpoint = new Uri ( "http://localhost:50172/OAuth/Authorize" ) ,
29- } ;
30-
31- /// <summary>
32- /// Initializes static members of the <see cref="SampleWcf2"/> class.
33- /// </summary>
34- static SampleWcf2 ( ) {
35- Client = new WebServerClient ( authServerDescription , "sampleconsumer" , "samplesecret" ) ;
36- }
37-
38- /// <summary>
39- /// Gets or sets the authorization details for the logged in user.
40- /// </summary>
41- /// <value>The authorization details.</value>
42- /// <remarks>
43- /// Because this is a sample, we simply store the authorization information in memory with the user session.
44- /// A real web app should store at least the access and refresh tokens in this object in a database associated with the user.
45- /// </remarks>
46- private static IAuthorizationState Authorization {
47- get { return ( AuthorizationState ) HttpContext . Current . Session [ "Authorization" ] ; }
48- set { HttpContext . Current . Session [ "Authorization" ] = value ; }
49- }
50-
51- protected void Page_Load ( object sender , EventArgs e ) {
52- if ( ! IsPostBack ) {
53- // Check to see if we're receiving a end user authorization response.
54- var authorization = Client . ProcessUserAuthorization ( ) ;
55- if ( authorization != null ) {
56- // We are receiving an authorization response. Store it and associate it with this user.
57- Authorization = authorization ;
58- Response . Redirect ( Request . Path ) ; // get rid of the /?code= parameter
59- }
60- }
61-
62- if ( Authorization != null ) {
63- // Indicate to the user that we have already obtained authorization on some of these.
64- foreach ( var li in this . scopeList . Items . OfType < ListItem > ( ) . Where ( li => Authorization . Scope . Contains ( li . Value ) ) ) {
65- li . Selected = true ;
66- }
67- this . authorizationLabel . Text = "Authorization received!" ;
68- if ( Authorization . AccessTokenExpirationUtc . HasValue ) {
1+ namespace OAuthClient {
2+ using System ;
3+ using System . Collections . Generic ;
4+ using System . Globalization ;
5+ using System . Linq ;
6+ using System . Net ;
7+ using System . ServiceModel ;
8+ using System . ServiceModel . Channels ;
9+ using System . ServiceModel . Security ;
10+ using System . Web ;
11+ using System . Web . UI ;
12+ using System . Web . UI . WebControls ;
13+ using DotNetOpenAuth . OAuth2 ;
14+
15+ using SampleResourceServer ;
16+
17+ public partial class SampleWcf2 : System . Web . UI . Page {
18+ /// <summary>
19+ /// The OAuth 2.0 client object to use to obtain authorization and authorize outgoing HTTP requests.
20+ /// </summary>
21+ private static readonly WebServerClient Client ;
22+
23+ /// <summary>
24+ /// The details about the sample OAuth-enabled WCF service that this sample client calls into.
25+ /// </summary>
26+ private static AuthorizationServerDescription authServerDescription = new AuthorizationServerDescription {
27+ TokenEndpoint = new Uri ( "http://localhost:50172/OAuth/Token" ) ,
28+ AuthorizationEndpoint = new Uri ( "http://localhost:50172/OAuth/Authorize" ) ,
29+ } ;
30+
31+ /// <summary>
32+ /// Initializes static members of the <see cref="SampleWcf2"/> class.
33+ /// </summary>
34+ static SampleWcf2 ( ) {
35+ Client = new WebServerClient ( authServerDescription , "sampleconsumer" , "samplesecret" ) ;
36+ }
37+
38+ /// <summary>
39+ /// Gets or sets the authorization details for the logged in user.
40+ /// </summary>
41+ /// <value>The authorization details.</value>
42+ /// <remarks>
43+ /// Because this is a sample, we simply store the authorization information in memory with the user session.
44+ /// A real web app should store at least the access and refresh tokens in this object in a database associated with the user.
45+ /// </remarks>
46+ private static IAuthorizationState Authorization {
47+ get { return ( AuthorizationState ) HttpContext . Current . Session [ "Authorization" ] ; }
48+ set { HttpContext . Current . Session [ "Authorization" ] = value ; }
49+ }
50+
51+ protected void Page_Load ( object sender , EventArgs e ) {
52+ if ( ! IsPostBack ) {
53+ // Check to see if we're receiving a end user authorization response.
54+ var authorization = Client . ProcessUserAuthorization ( ) ;
55+ if ( authorization != null ) {
56+ // We are receiving an authorization response. Store it and associate it with this user.
57+ Authorization = authorization ;
58+ Response . Redirect ( Request . Path ) ; // get rid of the /?code= parameter
59+ }
60+ }
61+
62+ if ( Authorization != null ) {
63+ // Indicate to the user that we have already obtained authorization on some of these.
64+ foreach ( var li in this . scopeList . Items . OfType < ListItem > ( ) . Where ( li => Authorization . Scope . Contains ( li . Value ) ) ) {
65+ li . Selected = true ;
66+ }
67+ this . authorizationLabel . Text = "Authorization received!" ;
68+ if ( Authorization . AccessTokenExpirationUtc . HasValue ) {
6969 TimeSpan timeLeft = Authorization . AccessTokenExpirationUtc . Value - DateTime . UtcNow ;
70- this . authorizationLabel . Text += string . Format ( CultureInfo . CurrentCulture , " (access token expires in {0} minutes)" , Math . Round ( timeLeft . TotalMinutes , 1 ) ) ;
71- }
72- }
73-
74- this . getNameButton . Enabled = this . getAgeButton . Enabled = this . getFavoriteSites . Enabled = Authorization != null ;
75- }
76-
77- protected void getAuthorizationButton_Click ( object sender , EventArgs e ) {
78- string [ ] scopes = ( from item in this . scopeList . Items . OfType < ListItem > ( )
79- where item . Selected
80- select item . Value ) . ToArray ( ) ;
81-
82- Client . RequestUserAuthorization ( scopes ) ;
83- }
84-
85- protected void getNameButton_Click ( object sender , EventArgs e ) {
86- try {
87- this . nameLabel . Text = CallService ( client => client . GetName ( ) ) ;
88- } catch ( SecurityAccessDeniedException ) {
89- this . nameLabel . Text = "Access denied!" ;
90- }
91- }
92-
93- protected void getAgeButton_Click ( object sender , EventArgs e ) {
94- try {
95- int ? age = CallService ( client => client . GetAge ( ) ) ;
96- this . ageLabel . Text = age . HasValue ? age . Value . ToString ( CultureInfo . CurrentCulture ) : "not available" ;
97- } catch ( SecurityAccessDeniedException ) {
98- this . ageLabel . Text = "Access denied!" ;
99- }
100- }
101-
102- protected void getFavoriteSites_Click ( object sender , EventArgs e ) {
103- try {
104- string [ ] favoriteSites = CallService ( client => client . GetFavoriteSites ( ) ) ;
105- this . favoriteSitesLabel . Text = string . Join ( ", " , favoriteSites ) ;
106- } catch ( SecurityAccessDeniedException ) {
107- this . favoriteSitesLabel . Text = "Access denied!" ;
108- }
109- }
110-
111- private T CallService < T > ( Func < DataApiClient , T > predicate ) {
112- if ( Authorization == null ) {
113- throw new InvalidOperationException ( "No access token!" ) ;
114- }
115-
116- var wcfClient = new DataApiClient ( ) ;
117-
118- // Refresh the access token if it expires and if its lifetime is too short to be of use.
119- if ( Authorization . AccessTokenExpirationUtc . HasValue ) {
120- if ( Client . RefreshToken ( Authorization , TimeSpan . FromSeconds ( 30 ) ) ) {
70+ this . authorizationLabel . Text += string . Format ( CultureInfo . CurrentCulture , " (access token expires in {0} minutes)" , Math . Round ( timeLeft . TotalMinutes , 1 ) ) ;
71+ }
72+ }
73+
74+ this . getNameButton . Enabled = this . getAgeButton . Enabled = this . getFavoriteSites . Enabled = Authorization != null ;
75+ }
76+
77+ protected void getAuthorizationButton_Click ( object sender , EventArgs e ) {
78+ string [ ] scopes = ( from item in this . scopeList . Items . OfType < ListItem > ( )
79+ where item . Selected
80+ select item . Value ) . ToArray ( ) ;
81+
82+ Client . RequestUserAuthorization ( scopes ) ;
83+ }
84+
85+ protected void getNameButton_Click ( object sender , EventArgs e ) {
86+ try {
87+ this . nameLabel . Text = CallService ( client => client . GetName ( ) ) ;
88+ } catch ( SecurityAccessDeniedException ) {
89+ this . nameLabel . Text = "Access denied!" ;
90+ }
91+ }
92+
93+ protected void getAgeButton_Click ( object sender , EventArgs e ) {
94+ try {
95+ int ? age = CallService ( client => client . GetAge ( ) ) ;
96+ this . ageLabel . Text = age . HasValue ? age . Value . ToString ( CultureInfo . CurrentCulture ) : "not available" ;
97+ } catch ( SecurityAccessDeniedException ) {
98+ this . ageLabel . Text = "Access denied!" ;
99+ }
100+ }
101+
102+ protected void getFavoriteSites_Click ( object sender , EventArgs e ) {
103+ try {
104+ string [ ] favoriteSites = CallService ( client => client . GetFavoriteSites ( ) ) ;
105+ this . favoriteSitesLabel . Text = string . Join ( ", " , favoriteSites ) ;
106+ } catch ( SecurityAccessDeniedException ) {
107+ this . favoriteSitesLabel . Text = "Access denied!" ;
108+ }
109+ }
110+
111+ private T CallService < T > ( Func < DataApiClient , T > predicate ) {
112+ if ( Authorization == null ) {
113+ throw new InvalidOperationException ( "No access token!" ) ;
114+ }
115+
116+ var wcfClient = new DataApiClient ( ) ;
117+
118+ // Refresh the access token if it expires and if its lifetime is too short to be of use.
119+ if ( Authorization . AccessTokenExpirationUtc . HasValue ) {
120+ if ( Client . RefreshToken ( Authorization , TimeSpan . FromSeconds ( 30 ) ) ) {
121121 TimeSpan timeLeft = Authorization . AccessTokenExpirationUtc . Value - DateTime . UtcNow ;
122- this . authorizationLabel . Text += string . Format ( CultureInfo . CurrentCulture , " - just renewed for {0} more minutes)" , Math . Round ( timeLeft . TotalMinutes , 1 ) ) ;
123- }
124- }
125-
126- var httpRequest = ( HttpWebRequest ) WebRequest . Create ( wcfClient . Endpoint . Address . Uri ) ;
127- Client . AuthorizeRequest ( httpRequest , Authorization . AccessToken ) ;
128-
129- var httpDetails = new HttpRequestMessageProperty ( ) ;
130- httpDetails . Headers [ HttpRequestHeader . Authorization ] = httpRequest . Headers [ HttpRequestHeader . Authorization ] ;
131- using ( var scope = new OperationContextScope ( wcfClient . InnerChannel ) ) {
132- OperationContext . Current . OutgoingMessageProperties [ HttpRequestMessageProperty . Name ] = httpDetails ;
133- return predicate ( wcfClient ) ;
134- }
135- }
136- }
122+ this . authorizationLabel . Text += string . Format ( CultureInfo . CurrentCulture , " - just renewed for {0} more minutes)" , Math . Round ( timeLeft . TotalMinutes , 1 ) ) ;
123+ }
124+ }
125+
126+ var httpRequest = ( HttpWebRequest ) WebRequest . Create ( wcfClient . Endpoint . Address . Uri ) ;
127+ ClientBase . AuthorizeRequest ( httpRequest , Authorization . AccessToken ) ;
128+
129+ var httpDetails = new HttpRequestMessageProperty ( ) ;
130+ httpDetails . Headers [ HttpRequestHeader . Authorization ] = httpRequest . Headers [ HttpRequestHeader . Authorization ] ;
131+ using ( var scope = new OperationContextScope ( wcfClient . InnerChannel ) ) {
132+ OperationContext . Current . OutgoingMessageProperties [ HttpRequestMessageProperty . Name ] = httpDetails ;
133+ return predicate ( wcfClient ) ;
134+ }
135+ }
136+ }
137137}
0 commit comments