summaryrefslogtreecommitdiffstats
path: root/samples/OAuthAuthorizationServer/Controllers
diff options
context:
space:
mode:
Diffstat (limited to 'samples/OAuthAuthorizationServer/Controllers')
-rw-r--r--samples/OAuthAuthorizationServer/Controllers/AccountController.cs155
-rw-r--r--samples/OAuthAuthorizationServer/Controllers/OAuthController.cs180
2 files changed, 183 insertions, 152 deletions
diff --git a/samples/OAuthAuthorizationServer/Controllers/AccountController.cs b/samples/OAuthAuthorizationServer/Controllers/AccountController.cs
index 9c755ea..b2c725b 100644
--- a/samples/OAuthAuthorizationServer/Controllers/AccountController.cs
+++ b/samples/OAuthAuthorizationServer/Controllers/AccountController.cs
@@ -1,78 +1,95 @@
-namespace OAuthAuthorizationServer.Controllers {
- using System;
- using System.Linq;
- using System.Threading.Tasks;
- using System.Web.Mvc;
- using System.Web.Security;
- using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OpenId;
- using DotNetOpenAuth.OpenId.RelyingParty;
- using OAuthAuthorizationServer.Code;
- using OAuthAuthorizationServer.Models;
+namespace OAuthAuthorizationServer.Controllers
+{
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId;
+ using DotNetOpenAuth.OpenId.RelyingParty;
+ using OAuthAuthorizationServer.Code;
+ using OAuthAuthorizationServer.Models;
+ using System;
+ using System.Linq;
+ using System.Threading.Tasks;
+ using System.Web.Mvc;
+ using System.Web.Security;
- [HandleError]
- public class AccountController : Controller {
- // **************************************
- // URL: /Account/LogOn
- // **************************************
- public ActionResult LogOn() {
- return View();
- }
+ [HandleError]
+ public class AccountController : Controller
+ {
+ // **************************************
+ // URL: /Account/LogOn
+ // **************************************
+ public ActionResult LogOn()
+ {
+ return View();
+ }
- [HttpPost]
- public async Task<ActionResult> LogOn(LogOnModel model, string returnUrl) {
- if (ModelState.IsValid) {
- var rp = new OpenIdRelyingParty();
- var request = await rp.CreateRequestAsync(model.UserSuppliedIdentifier, Realm.AutoDetect, new Uri(Request.Url, Url.Action("Authenticate")));
- if (request != null) {
- if (returnUrl != null) {
- request.AddCallbackArguments("returnUrl", returnUrl);
- }
+ [HttpPost]
+ public async Task<ActionResult> LogOn(LogOnModel model, string returnUrl)
+ {
+ if (ModelState.IsValid)
+ {
+ var rp = new OpenIdRelyingParty();
+ var request = await rp.CreateRequestAsync(model.UserSuppliedIdentifier, Realm.AutoDetect, new Uri(Request.Url, Url.Action("Authenticate")));
+ if (request != null)
+ {
+ if (returnUrl != null)
+ {
+ request.AddCallbackArguments("returnUrl", returnUrl);
+ }
- var response = await request.GetRedirectingResponseAsync();
- return response.AsActionResult();
- } else {
- ModelState.AddModelError(string.Empty, "The identifier you supplied is not recognized as a valid OpenID Identifier.");
- }
- }
+ var response = await request.GetRedirectingResponseAsync();
+ Response.ContentType = response.Content.Headers.ContentType.ToString();
+ return response.AsActionResult();
+ }
+ else
+ {
+ ModelState.AddModelError(string.Empty, "The identifier you supplied is not recognized as a valid OpenID Identifier.");
+ }
+ }
- // If we got this far, something failed, redisplay form
- return View(model);
- }
+ // If we got this far, something failed, redisplay form
+ return View(model);
+ }
- public async Task<ActionResult> Authenticate(string returnUrl) {
- var rp = new OpenIdRelyingParty();
- var response = await rp.GetResponseAsync(Request);
- if (response != null) {
- switch (response.Status) {
- case AuthenticationStatus.Authenticated:
- // Make sure we have a user account for this guy.
- string identifier = response.ClaimedIdentifier; // convert to string so LinqToSQL expression parsing works.
- if (MvcApplication.DataContext.Users.FirstOrDefault(u => u.OpenIDClaimedIdentifier == identifier) == null) {
- MvcApplication.DataContext.Users.InsertOnSubmit(new User {
- OpenIDFriendlyIdentifier = response.FriendlyIdentifierForDisplay,
- OpenIDClaimedIdentifier = response.ClaimedIdentifier,
- });
- }
+ public async Task<ActionResult> Authenticate(string returnUrl)
+ {
+ var rp = new OpenIdRelyingParty();
+ var response = await rp.GetResponseAsync(Request);
+ if (response != null)
+ {
+ switch (response.Status)
+ {
+ case AuthenticationStatus.Authenticated:
+ // Make sure we have a user account for this guy.
+ string identifier = response.ClaimedIdentifier; // convert to string so LinqToSQL expression parsing works.
+ if (MvcApplication.DataContext.Users.FirstOrDefault(u => u.OpenIDClaimedIdentifier == identifier) == null)
+ {
+ MvcApplication.DataContext.Users.InsertOnSubmit(new User
+ {
+ OpenIDFriendlyIdentifier = response.FriendlyIdentifierForDisplay,
+ OpenIDClaimedIdentifier = response.ClaimedIdentifier,
+ });
+ }
- FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false);
- return this.Redirect(returnUrl ?? Url.Action("Index", "Home"));
- default:
- ModelState.AddModelError(string.Empty, "An error occurred during login.");
- break;
- }
- }
+ FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false);
+ return this.Redirect(returnUrl ?? Url.Action("Index", "Home"));
- return this.View("LogOn");
- }
+ default:
+ ModelState.AddModelError(string.Empty, "An error occurred during login.");
+ break;
+ }
+ }
- // **************************************
- // URL: /Account/LogOff
- // **************************************
- public ActionResult LogOff() {
- FormsAuthentication.SignOut();
+ return this.View("LogOn");
+ }
- return RedirectToAction("Index", "Home");
- }
- }
-}
+ // **************************************
+ // URL: /Account/LogOff
+ // **************************************
+ public ActionResult LogOff()
+ {
+ FormsAuthentication.SignOut();
+
+ return RedirectToAction("Index", "Home");
+ }
+ }
+} \ No newline at end of file
diff --git a/samples/OAuthAuthorizationServer/Controllers/OAuthController.cs b/samples/OAuthAuthorizationServer/Controllers/OAuthController.cs
index 3ab4096..3e512cb 100644
--- a/samples/OAuthAuthorizationServer/Controllers/OAuthController.cs
+++ b/samples/OAuthAuthorizationServer/Controllers/OAuthController.cs
@@ -1,94 +1,108 @@
-namespace OAuthAuthorizationServer.Controllers {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Security.Cryptography;
- using System.Threading.Tasks;
- using System.Web;
- using System.Web.Mvc;
- using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OAuth2;
- using OAuthAuthorizationServer.Code;
- using OAuthAuthorizationServer.Models;
+namespace OAuthAuthorizationServer.Controllers
+{
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2;
+ using OAuthAuthorizationServer.Code;
+ using OAuthAuthorizationServer.Models;
+ using System;
+ using System.Linq;
+ using System.Net;
+ using System.Threading.Tasks;
+ using System.Web;
+ using System.Web.Mvc;
- public class OAuthController : Controller {
- private readonly AuthorizationServer authorizationServer = new AuthorizationServer(new OAuth2AuthorizationServer());
+ public class OAuthController : Controller
+ {
+ private readonly AuthorizationServer authorizationServer = new AuthorizationServer(new OAuth2AuthorizationServer());
- /// <summary>
- /// The OAuth 2.0 token endpoint.
- /// </summary>
- /// <returns>The response to the Client.</returns>
- public async Task<ActionResult> Token() {
- var request = await this.authorizationServer.HandleTokenRequestAsync(this.Request, this.Response.ClientDisconnectedToken);
- return request.AsActionResult();
- }
+ /// <summary>
+ /// The OAuth 2.0 token endpoint.
+ /// </summary>
+ /// <returns>The response to the Client.</returns>
+ public async Task<ActionResult> Token()
+ {
+ var request = await this.authorizationServer.HandleTokenRequestAsync(this.Request, this.Response.ClientDisconnectedToken);
+ Response.ContentType = request.Content.Headers.ContentType.ToString();
+ return request.AsActionResult();
+ }
- /// <summary>
- /// Prompts the user to authorize a client to access the user's private data.
- /// </summary>
- /// <returns>The browser HTML response that prompts the user to authorize the client.</returns>
- [Authorize, AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
- [HttpHeader("x-frame-options", "SAMEORIGIN")] // mitigates clickjacking
- public async Task<ActionResult> Authorize() {
- var pendingRequest = await this.authorizationServer.ReadAuthorizationRequestAsync(Request, Response.ClientDisconnectedToken);
- if (pendingRequest == null) {
- throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
- }
+ /// <summary>
+ /// Prompts the user to authorize a client to access the user's private data.
+ /// </summary>
+ /// <returns>The browser HTML response that prompts the user to authorize the client.</returns>
+ [Authorize, AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
+ [HttpHeader("x-frame-options", "SAMEORIGIN")] // mitigates clickjacking
+ public async Task<ActionResult> Authorize()
+ {
+ var pendingRequest = await this.authorizationServer.ReadAuthorizationRequestAsync(Request, Response.ClientDisconnectedToken);
+ if (pendingRequest == null)
+ {
+ throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
+ }
- var requestingClient = MvcApplication.DataContext.Clients.First(c => c.ClientIdentifier == pendingRequest.ClientIdentifier);
+ var requestingClient = MvcApplication.DataContext.Clients.First(c => c.ClientIdentifier == pendingRequest.ClientIdentifier);
- // Consider auto-approving if safe to do so.
- if (((OAuth2AuthorizationServer)this.authorizationServer.AuthorizationServerServices).CanBeAutoApproved(pendingRequest)) {
- var approval = this.authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, HttpContext.User.Identity.Name);
- var response = await this.authorizationServer.Channel.PrepareResponseAsync(approval, Response.ClientDisconnectedToken);
- return response.AsActionResult();
- }
+ // Consider auto-approving if safe to do so.
+ if (((OAuth2AuthorizationServer)this.authorizationServer.AuthorizationServerServices).CanBeAutoApproved(pendingRequest))
+ {
+ var approval = this.authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, HttpContext.User.Identity.Name);
+ var response = await this.authorizationServer.Channel.PrepareResponseAsync(approval, Response.ClientDisconnectedToken);
+ Response.ContentType = response.Content.Headers.ContentType.ToString();
+ return response.AsActionResult();
+ }
- var model = new AccountAuthorizeModel {
- ClientApp = requestingClient.Name,
- Scope = pendingRequest.Scope,
- AuthorizationRequest = pendingRequest,
- };
+ var model = new AccountAuthorizeModel
+ {
+ ClientApp = requestingClient.Name,
+ Scope = pendingRequest.Scope,
+ AuthorizationRequest = pendingRequest,
+ };
- return View(model);
- }
+ return View(model);
+ }
- /// <summary>
- /// Processes the user's response as to whether to authorize a Client to access his/her private data.
- /// </summary>
- /// <param name="isApproved">if set to <c>true</c>, the user has authorized the Client; <c>false</c> otherwise.</param>
- /// <returns>HTML response that redirects the browser to the Client.</returns>
- [Authorize, HttpPost, ValidateAntiForgeryToken]
- public async Task<ActionResult> AuthorizeResponse(bool isApproved) {
- var pendingRequest = await this.authorizationServer.ReadAuthorizationRequestAsync(Request, Response.ClientDisconnectedToken);
- if (pendingRequest == null) {
- throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
- }
+ /// <summary>
+ /// Processes the user's response as to whether to authorize a Client to access his/her private data.
+ /// </summary>
+ /// <param name="isApproved">if set to <c>true</c>, the user has authorized the Client; <c>false</c> otherwise.</param>
+ /// <returns>HTML response that redirects the browser to the Client.</returns>
+ [Authorize, HttpPost, ValidateAntiForgeryToken]
+ public async Task<ActionResult> AuthorizeResponse(bool isApproved)
+ {
+ var pendingRequest = await this.authorizationServer.ReadAuthorizationRequestAsync(Request, Response.ClientDisconnectedToken);
+ if (pendingRequest == null)
+ {
+ throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
+ }
- IDirectedProtocolMessage response;
- if (isApproved) {
- // The authorization we file in our database lasts until the user explicitly revokes it.
- // You can cause the authorization to expire by setting the ExpirationDateUTC
- // property in the below created ClientAuthorization.
- var client = MvcApplication.DataContext.Clients.First(c => c.ClientIdentifier == pendingRequest.ClientIdentifier);
- client.ClientAuthorizations.Add(
- new ClientAuthorization {
- Scope = OAuthUtilities.JoinScopes(pendingRequest.Scope),
- User = MvcApplication.LoggedInUser,
- CreatedOnUtc = DateTime.UtcNow,
- });
- MvcApplication.DataContext.SubmitChanges(); // submit now so that this new row can be retrieved later in this same HTTP request
+ IDirectedProtocolMessage response;
+ if (isApproved)
+ {
+ // The authorization we file in our database lasts until the user explicitly revokes it.
+ // You can cause the authorization to expire by setting the ExpirationDateUTC
+ // property in the below created ClientAuthorization.
+ var client = MvcApplication.DataContext.Clients.First(c => c.ClientIdentifier == pendingRequest.ClientIdentifier);
+ client.ClientAuthorizations.Add(
+ new ClientAuthorization
+ {
+ Scope = OAuthUtilities.JoinScopes(pendingRequest.Scope),
+ User = MvcApplication.LoggedInUser,
+ CreatedOnUtc = DateTime.UtcNow,
+ });
+ MvcApplication.DataContext.SubmitChanges(); // submit now so that this new row can be retrieved later in this same HTTP request
- // In this simple sample, the user either agrees to the entire scope requested by the client or none of it.
- // But in a real app, you could grant a reduced scope of access to the client by passing a scope parameter to this method.
- response = this.authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, User.Identity.Name);
- } else {
- response = this.authorizationServer.PrepareRejectAuthorizationRequest(pendingRequest);
- }
+ // In this simple sample, the user either agrees to the entire scope requested by the client or none of it.
+ // But in a real app, you could grant a reduced scope of access to the client by passing a scope parameter to this method.
+ response = this.authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, User.Identity.Name);
+ }
+ else
+ {
+ response = this.authorizationServer.PrepareRejectAuthorizationRequest(pendingRequest);
+ }
- var preparedResponse = await this.authorizationServer.Channel.PrepareResponseAsync(response, Response.ClientDisconnectedToken);
- return preparedResponse.AsActionResult();
- }
- }
-}
+ var preparedResponse = await this.authorizationServer.Channel.PrepareResponseAsync(response, Response.ClientDisconnectedToken);
+ Response.ContentType = preparedResponse.Content.Headers.ContentType.ToString();
+ return preparedResponse.AsActionResult();
+ }
+ }
+} \ No newline at end of file