Skip to content

Instantly share code, notes, and snippets.

@mgroves
Created April 11, 2012 09:58
Show Gist options
  • Select an option

  • Save mgroves/2358332 to your computer and use it in GitHub Desktop.

Select an option

Save mgroves/2358332 to your computer and use it in GitHub Desktop.
using System.Web.Mvc;
using AopBlog.Models.Repositories;
using AopBlog.Models.Services;
namespace AopBlog.Areas.Manage.Controllers
{
public class AccountController : Controller
{
readonly IAuthorizationService _authService;
readonly IAuthorRepository _authorRepo;
public AccountController(IAuthorRepository authorRepoRepository, IAuthorizationService authService)
{
_authorRepo = authorRepoRepository;
_authService = authService;
}
public ViewResult LogOn()
{
return View();
}
public void TwitterOAuth()
{
_authService.RequestOAuthAuthentication();
}
public RedirectToRouteResult OAuth()
{
var response = _authService.ProcessAuthentication();
if (response.IsAuthenticated)
{
if (_authorRepo.AuthorIsAuthorized(response.ScreenName))
{
_authService.CreateAuthCookie(response.ScreenName, response.AccessToken);
return RedirectToAction("Index", "Home");
}
return RedirectToAction("Unauthorized", new {response.ScreenName});
}
return RedirectToAction("LogOn");
}
public ViewResult Unauthorized(string screenName)
{
ViewBag.ScreenName = screenName;
return View();
}
}
}
using System;
using System.Web;
using System.Web.Security;
using AopBlog.Helpers;
using DotNetOpenAuth.ApplicationBlock;
using DotNetOpenAuth.OAuth;
using DotNetOpenAuth.OAuth.ChannelElements;
namespace AopBlog.Models.Services
{
public interface IAuthorizationService
{
void RequestOAuthAuthentication();
OauthAuthenticationToken ProcessAuthentication();
void CreateAuthCookie(string username, string accessToken);
}
public class AuthorizationService : IAuthorizationService
{
readonly IConsumerTokenManager _tokenManager;
readonly HttpContext _httpContext;
public AuthorizationService(IConsumerTokenManager tokenManager, HttpContext httpContext)
{
_tokenManager = tokenManager;
_httpContext = httpContext;
}
public void RequestOAuthAuthentication()
{
var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, _tokenManager);
//Create the URL that we want Twitter to redirect the user to
var oAuthUrl = new Uri(_httpContext.Request.Url.Scheme + "://" + _httpContext.Request.Url.Authority + "/Manage/Account/OAuth");
oAuthUrl = oAuthUrl.SetPort(80);
// If we don't yet have access, immediately request it.
twitter.Channel.Send(twitter.PrepareRequestUserAuthorization(oAuthUrl, null, null));
}
public OauthAuthenticationToken ProcessAuthentication()
{
var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, _tokenManager);
var oauthToken = twitter.ProcessUserAuthorization();
var token = new OauthAuthenticationToken();
token.IsAuthenticated = oauthToken != null;
if (token.IsAuthenticated)
{
token.AccessToken = oauthToken.AccessToken;
token.ScreenName = oauthToken.ExtraData["screen_name"];
}
return token;
}
public void CreateAuthCookie(string username, string token)
{
//Get ASP.NET to create a forms authentication cookie (based on settings in web.config)~
var cookie = FormsAuthentication.GetAuthCookie(username, false);
//Decrypt the cookie
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
//Create a new ticket using the details from the generated cookie, but store the username &
//token passed in from the authentication method
var newticket = new FormsAuthenticationTicket(
ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration,
ticket.IsPersistent, token);
// Encrypt the ticket & store in the cookie
cookie.Value = FormsAuthentication.Encrypt(newticket);
// Update the outgoing cookies collection.
_httpContext.Response.Cookies.Set(cookie);
}
}
}
using System;
using System.Collections.Generic;
using AopBlog.Framework;
using DotNetOpenAuth.OAuth.ChannelElements;
using DotNetOpenAuth.OAuth.Messages;
namespace AopBlog.Models.Services
{
public class ConsumerTokenManager : IConsumerTokenManager
{
private readonly Dictionary<string, string> tokensAndSecrets = new Dictionary<string, string>();
public ConsumerTokenManager()
{
ConsumerKey = BlogConfig.TwitterOauthApiKey;
ConsumerSecret = BlogConfig.TwitterOauthSecretKey;
}
#region ITokenManager Members
public string ConsumerKey { get; private set; }
public string ConsumerSecret { get; private set; }
public string GetTokenSecret(string token)
{
return this.tokensAndSecrets[token];
}
public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response)
{
this.tokensAndSecrets[response.Token] = response.TokenSecret;
}
public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret)
{
this.tokensAndSecrets.Remove(requestToken);
this.tokensAndSecrets[accessToken] = accessTokenSecret;
}
/// <summary>
/// Classifies a token as a request token or an access token.
/// </summary>
/// <param name="token">The token to classify.</param>
/// <returns>Request or Access token, or invalid if the token is not recognized.</returns>
public TokenType GetTokenType(string token)
{
throw new NotImplementedException();
}
#endregion
}
}
using System.Web.Mvc;
namespace AopBlog.Areas.Manage.Controllers
{
public class HomeController : Controller
{
[Authorize]
public ViewResult Index()
{
return View();
}
}
}
namespace AopBlog.Models.Services
{
public class OauthAuthenticationToken
{
public bool IsAuthenticated { get; set; }
public string AccessToken { get; set; }
public string ScreenName { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment