//-----------------------------------------------------------------------
//
// Copyright (c) Microsoft. All rights reserved.
//
//-----------------------------------------------------------------------
namespace DotNetOpenAuth.AspNet.Clients {
using System;
using System.Text;
using System.Web;
using System.Web.Security;
///
/// Stores OAuth tokens in the current request's cookie
///
public class AuthenticationOnlyCookieOAuthTokenManager : IOAuthTokenManager {
///
/// Key used for token cookie
///
private const string TokenCookieKey = "OAuthTokenSecret";
///
/// Primary request context.
///
private readonly HttpContextBase primaryContext;
///
/// Initializes a new instance of the class.
///
public AuthenticationOnlyCookieOAuthTokenManager() {
}
///
/// Initializes a new instance of the class.
///
/// The current request context.
public AuthenticationOnlyCookieOAuthTokenManager(HttpContextBase context) {
this.primaryContext = context;
}
///
/// Gets the effective HttpContext object to use.
///
private HttpContextBase Context {
get {
return this.primaryContext ?? new HttpContextWrapper(HttpContext.Current);
}
}
///
/// Gets the token secret from the specified token.
///
/// The token.
///
/// The token's secret
///
public string GetTokenSecret(string token) {
HttpCookie cookie = this.Context.Request.Cookies[TokenCookieKey];
if (cookie == null || string.IsNullOrEmpty(cookie.Values[token])) {
return null;
}
byte[] cookieBytes = HttpServerUtility.UrlTokenDecode(cookie.Values[token]);
byte[] clearBytes = MachineKeyUtil.Unprotect(cookieBytes, TokenCookieKey, "Token:" + token);
string secret = Encoding.UTF8.GetString(clearBytes);
return secret;
}
///
/// Replaces the request token with access token.
///
/// The request token.
/// The access token.
/// The access token secret.
public void ReplaceRequestTokenWithAccessToken(string requestToken, string accessToken, string accessTokenSecret) {
var cookie = new HttpCookie(TokenCookieKey) {
Value = string.Empty,
Expires = DateTime.UtcNow.AddDays(-5)
};
this.Context.Response.Cookies.Set(cookie);
}
///
/// Stores the request token together with its secret.
///
/// The request token.
/// The request token secret.
public void StoreRequestToken(string requestToken, string requestTokenSecret) {
var cookie = new HttpCookie(TokenCookieKey);
if (FormsAuthentication.RequireSSL) {
cookie.Secure = true;
}
byte[] cookieBytes = Encoding.UTF8.GetBytes(requestTokenSecret);
var secretBytes = MachineKeyUtil.Protect(cookieBytes, TokenCookieKey, "Token:" + requestToken);
cookie.Values[requestToken] = HttpServerUtility.UrlTokenEncode(secretBytes);
this.Context.Response.Cookies.Set(cookie);
}
}
}