Tuesday 18 October 2011

Step by Step Twitter OpenId with DotnetOpenAuth

1] using NuGet a excellent package management system for the Dotnet install DotnetOpenAuth or download it from  SourceForge   DotnetOpenAuth Latest version.

 

2] Then Create your App on Twitter Dev  Do not forget to add Callback URL – if you don’t have anything add  http://www.example.com\mytwitter\

 

3]  you need to use given twitterConsumerKeys and TwitterConsumerSecret keys to request authorisation to your app. Add these keys into Web.config as a appSettings

 

   1: <!-- Twitter sign-up: https://twitter.com/oauth_clients 
   2: --> 
   3:  <add key="twitterConsumerKey" 
   4: value="qjohqNt4kU1iNTQtJSN8Xg" />
   5:  <add 
   6: key="twitterConsumerSecret" value="fo8dzQPx4es0qyULrsmt8IeGWKHndbBvnBtCVp5Hb8" 
   7: />

4] Add below code on Controller Action or on Page Load.



   1:  
   2: var twitter = new 
   3: WebConsumer(TwitterConsumer.ServiceDescription, 
   4: this.TokenManager);
   5:  
   6: // check if Twitter calling back with 
   7: authorization?
   8:  
   9: var accessTokenResponse = 
  10: twitter.ProcessUserAuthorization();
  11:  
  12: if (accessTokenResponse != 
  13: null)
  14:  
  15: {
  16:  
  17: //If you have accesstoek then do 
  18: something 
  19: }
  20:  else if 
  21: (this.AccessToken == 
  22: null)
  23:  
  24: {
  25:  
  26: // If we don't yet have access, immediately request 
  27: it.
  28:  
  29: twitter.Channel.Send(twitter.PrepareRequestUserAuthorization());
  30:  
  31: }

5] add TokenManager



   1:  
   2: private InMemoryTokenManager 
   3: TokenManager
   4:  
   5: {
   6:  
   7: get
   8:  
   9: {
  10:  
  11: var tokenManager = 
  12: (InMemoryTokenManager)Session["TwitterTokenManager"];
  13:  
  14: if (tokenManager == 
  15: null)
  16:  
  17: {
  18:  
  19: string consumerKey = 
  20: ConfigurationManager.AppSettings["twitterConsumerKey"];
  21:  
  22: string consumerSecret = 
  23: ConfigurationManager.AppSettings["twitterConsumerSecret"];
  24:  
  25: if 
  26: (!string.IsNullOrEmpty(consumerKey))
  27:  
  28: {
  29:  
  30: tokenManager = new InMemoryTokenManager(consumerKey, 
  31: consumerSecret);
  32:  
  33: Session["TwitterTokenManager"] = 
  34: tokenManager;
  35:  
  36: }
  37:  
  38: }
  39:  
  40: return 
  41: tokenManager;
  42:  
  43: }
  44:  }
  45:  
  46: 6] and TokenManagerClass
  47: public class InMemoryTokenManager : IConsumerTokenManager, 
  48: IOpenIdOAuthTokenManager
  49:  {
  50:  private 
  51: Dictionary<string, string> tokensAndSecrets = new Dictionary<string, 
  52: string>();
  53:  /// 
  54: <summary>
  55:  /// Initializes a new instance 
  56: of the <see cref="InMemoryTokenManager"/> 
  57: class.
  58:  /// 
  59: </summary>
  60:  /// <param 
  61: name="consumerKey">The consumer 
  62: key.</param>
  63:  /// <param 
  64: name="consumerSecret">The consumer 
  65: secret.</param>
  66:  public 
  67: InMemoryTokenManager(string consumerKey, string 
  68: consumerSecret)
  69:  
  70: {
  71:  if 
  72: (String.IsNullOrEmpty(consumerKey))
  73:  
  74: {
  75:  
  76: throw new 
  77: ArgumentNullException("consumerKey");
  78:  
  79: }
  80:  this.ConsumerKey = 
  81: consumerKey;
  82:  
  83: this.ConsumerSecret = consumerSecret;
  84:  }
  85:  /// 
  86: <summary>
  87:  /// Gets the consumer 
  88: key.
  89:  /// 
  90: </summary>
  91:  /// <value>The consumer 
  92: key.</value>
  93:  public string ConsumerKey { 
  94: get; private set; }
  95:  /// 
  96: <summary>
  97:  /// Gets the consumer 
  98: secret.
  99:  /// 
 100: </summary>
 101:  /// <value>The consumer 
 102: secret.</value>
 103:  public string 
 104: ConsumerSecret { get; private set; }
 105:  #region ITokenManager Members
 106:  /// 
 107: <summary>
 108:  /// Gets the Token Secret 
 109: given a request or access token.
 110:  /// 
 111: </summary>
 112:  /// <param 
 113: name="token">The request or access 
 114: token.</param>
 115:  /// 
 116: <returns>
 117:  /// The secret associated with 
 118: the given token.
 119:  /// 
 120: </returns>
 121:  /// <exception 
 122: cref="ArgumentException">Thrown if the secret cannot be found for the given 
 123: token.</exception>
 124:  public string 
 125: GetTokenSecret(string token)
 126:  
 127: {
 128:  return 
 129: this.tokensAndSecrets[token];
 130:  }
 131:  /// 
 132: <summary>
 133:  /// Stores a newly generated 
 134: unauthorized request token, secret, and 
 135: optional
 136:  /// application-specific parameters 
 137: for later recall.
 138:  /// 
 139: </summary>
 140:  /// <param 
 141: name="request">The request message that resulted in the generation of a new 
 142: unauthorized request token.</param>
 143:  /// 
 144: <param name="response">The response message that includes the unauthorized 
 145: request token.</param>
 146:  /// <exception 
 147: cref="ArgumentException">Thrown if the consumer key is not registered, or a 
 148: required parameter was not found in the parameters 
 149: collection.</exception>
 150:  /// 
 151: <remarks>
 152:  /// Request tokens stored by 
 153: this method SHOULD NOT associate any user account with this 
 154: token.
 155:  /// It usually opens up security holes 
 156: in your application to do so. Instead, you associate a 
 157: user
 158:  /// account with access tokens (not 
 159: request tokens) in the <see 
 160: cref="ExpireRequestTokenAndStoreNewAccessToken"/>
 161:  
 162: /// method.
 163:  /// 
 164: </remarks>
 165:  public void 
 166: StoreNewRequestToken(UnauthorizedTokenRequest request, 
 167: ITokenSecretContainingMessage response)
 168:  
 169: {
 170:  
 171: this.tokensAndSecrets[response.Token] = 
 172: response.TokenSecret;
 173:  }
 174:  /// 
 175: <summary>
 176:  /// Deletes a request token 
 177: and its associated secret and stores a new access token and 
 178: secret.
 179:  /// 
 180: </summary>
 181:  /// <param 
 182: name="consumerKey">The Consumer that is exchanging its request token for an 
 183: access token.</param>
 184:  /// <param 
 185: name="requestToken">The Consumer's request token that should be 
 186: deleted/expired.</param>
 187:  /// <param 
 188: name="accessToken">The new access token that is being issued to the 
 189: Consumer.</param>
 190:  /// <param 
 191: name="accessTokenSecret">The secret associated with the newly issued access 
 192: token.</param>
 193:  /// 
 194: <remarks>
 195:  /// 
 196: <para>
 197:  /// Any scope of granted 
 198: privileges associated with the request token from 
 199: the
 200:  /// original call to <see 
 201: cref="StoreNewRequestToken"/> should be carried 
 202: over
 203:  /// to the new Access 
 204: Token.
 205:  /// 
 206: </para>
 207:  /// 
 208: <para>
 209:  /// To associate a user account 
 210: with the new access token,
 211:  /// <see 
 212: cref="System.Web.HttpContext.User">HttpContext.Current.User</see> may 
 213: be
 214:  /// useful in an ASP.NET web application 
 215: within the implementation of this method.
 216:  /// 
 217: Alternatively you may store the access token here without associating with a 
 218: user account,
 219:  /// and wait until <see 
 220: cref="WebConsumer.ProcessUserAuthorization()"/> 
 221: or
 222:  /// <see 
 223: cref="DesktopConsumer.ProcessUserAuthorization(string, string)"/> return the 
 224: access
 225:  /// token to associate the access token 
 226: with a user account at that point.
 227:  /// 
 228: </para>
 229:  /// 
 230: </remarks>
 231:  public void 
 232: ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string 
 233: requestToken, string accessToken, string 
 234: accessTokenSecret)
 235:  
 236: {
 237:  
 238: this.tokensAndSecrets.Remove(requestToken);
 239:  
 240: this.tokensAndSecrets[accessToken] = 
 241: accessTokenSecret;
 242:  }
 243:  /// 
 244: <summary>
 245:  /// Classifies a token as a 
 246: request token or an access token.
 247:  /// 
 248: </summary>
 249:  /// <param 
 250: name="token">The token to 
 251: classify.</param>
 252:  /// 
 253: <returns>Request or Access token, or invalid if the token is not 
 254: recognized.</returns>
 255:  public TokenType 
 256: GetTokenType(string token)
 257:  
 258: {
 259:  throw new 
 260: NotImplementedException();
 261:  }
 262:  #endregion
 263:  #region IOpenIdOAuthTokenManager Members
 264:  /// 
 265: <summary>
 266:  /// Stores a new request token 
 267: obtained over an OpenID request.
 268:  /// 
 269: </summary>
 270:  /// <param 
 271: name="consumerKey">The consumer 
 272: key.</param>
 273:  /// <param 
 274: name="authorization">The authorization message carrying the request token and 
 275: authorized access scope.</param>
 276:  /// 
 277: <remarks>
 278:  /// 
 279: <para>The token secret is the empty 
 280: string.</para>
 281:  
 282: /// <para>Tokens stored by this method should be 
 283: short-lived to mitigate
 284:  /// possible security 
 285: threats. Their lifetime should be sufficient for 
 286: the
 287:  /// relying party to receive the positive 
 288: authentication assertion and immediately
 289:  /// 
 290: send a follow-up request for the access 
 291: token.</para>
 292:  /// 
 293: </remarks>
 294:  public void 
 295: StoreOpenIdAuthorizedRequestToken(string consumerKey, 
 296: AuthorizationApprovedResponse authorization)
 297:  
 298: {
 299:  
 300: this.tokensAndSecrets[authorization.RequestToken] = 
 301: String.Empty;
 302:  }
 303:  #endregion
 304:  }

 


now run your code and You will be asked for permission to connect to your twitter account.

No comments:

Post a Comment