PrepareApproveAuthorizationRequest() 공개 메소드

Approves an authorization request.
public PrepareApproveAuthorizationRequest ( DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationRequest authorizationRequest, string userName, IEnumerable scopes = null, Uri callback = null ) : DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationSuccessResponseBase
authorizationRequest DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationRequest The authorization request to approve.
userName string The username of the account that approved the request (or whose data will be accessed by the client).
scopes IEnumerable The scope of access the client should be granted. If null, all scopes in the original request will be granted.
callback System.Uri The Client callback URL to use when formulating the redirect to send the user agent back to the Client.
리턴 DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationSuccessResponseBase
예제 #1
0
        public ActionResult Authorise()
        {
            using (var server = (new OAuth2AuthorizationServer(new X509Certificate2(_absolutePathToPfx, _certificatePassword),
                            new X509Certificate2(_absolutePathToCertificate))))
            {
                var authorizationServer = new AuthorizationServer(server);

                var pendingRequest = authorizationServer.ReadAuthorizationRequest();
                if (pendingRequest == null)
                {
                    throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
                }

                var requestingClient =
                    MvcApplication.DataContext.Clients.First(c => c.ClientIdentifier == pendingRequest.ClientIdentifier);

                // Consider auto-approving if safe to do so.
                if (((OAuth2AuthorizationServer)authorizationServer.AuthorizationServerServices).CanBeAutoApproved(pendingRequest))
                {
                    var approval = authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, HttpContext.User.Identity.Name);
                    return authorizationServer.Channel.PrepareResponse(approval).AsActionResult();
                }

                var model = new AccountAuthorizeModel
                {
                    ClientApp = requestingClient.Name,
                    Scope = pendingRequest.Scope,
                    AuthorizationRequest = pendingRequest,
                };

                return View(model);
            }
        }
		public async Task ImplicitGrant() {
			var coordinatorClient = new UserAgentClient(AuthorizationServerDescription);
			coordinatorClient.ClientCredentialApplicator = null; // implicit grant clients don't need a secret.
			Handle(AuthorizationServerDescription.AuthorizationEndpoint).By(
				async (req, ct) => {
					var server = new AuthorizationServer(AuthorizationServerMock);
					var request = await server.ReadAuthorizationRequestAsync(req, ct);
					Assert.That(request, Is.Not.Null);
					IAccessTokenRequest accessTokenRequest = (EndUserAuthorizationImplicitRequest)request;
					Assert.That(accessTokenRequest.ClientAuthenticated, Is.False);
					var response = server.PrepareApproveAuthorizationRequest(request, ResourceOwnerUsername);
					return await server.Channel.PrepareResponseAsync(response, ct);
				});
			{
				var client = new UserAgentClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories);
				var authState = new AuthorizationState(TestScopes) { Callback = ClientCallback, };
				var request = client.PrepareRequestUserAuthorization(authState, implicitResponseType: true);
				Assert.That(request.ResponseType, Is.EqualTo(EndUserAuthorizationResponseType.AccessToken));
				var authRequestRedirect = await client.Channel.PrepareResponseAsync(request);
				Uri authRequestResponse;
				this.HostFactories.AllowAutoRedirects = false;
				using (var httpClient = this.HostFactories.CreateHttpClient()) {
					using (var httpResponse = await httpClient.GetAsync(authRequestRedirect.Headers.Location)) {
						authRequestResponse = httpResponse.Headers.Location;
					}
				}

				var incoming =
					await client.Channel.ReadFromRequestAsync(new HttpRequestMessage(HttpMethod.Get, authRequestResponse), CancellationToken.None);
				var result = await client.ProcessUserAuthorizationAsync(authState, incoming, CancellationToken.None);
				Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
				Assert.That(result.RefreshToken, Is.Null);
			}
		}
예제 #3
0
        public async Task<ActionResult> Authorize(string username = null, string password = null)
        {
              
            if (username != null)
            {
                if (password != null)
                {
                    var entities = new AzurenEntities();
                    User u;
                    u = username.Contains("@") ? entities.Users.SingleOrDefault(m => m.Email == username) : entities.Users.SingleOrDefault(m => m.Username == username);
                    if (u == null || StringHelper.CalcPassword(password, u.Salt) != u.Password)
                    {
                        return RedirectToAction("Authorize", new { redirect_uri = Request.Params["redirect_uri"], client_id = Request.Params["client_id"], scope = Request.Params["scope"], error = true });
                    }
                    FormsAuthentication.SetAuthCookie(u.Username, true);
                    System.Web.HttpContext.Current.User = new RolePrincipal(new MyIdentity(u.Username, "Forms", true));
                }
            }
            if (!User.Identity.IsAuthenticated)
            {
                return Content("You must loggin first");
            }

            var authServer = new AuthorizationServer(new AuthorizationServerHost());
            var authRequest = await authServer.ReadAuthorizationRequestAsync(Request);
            var grantedResponse = authServer.PrepareApproveAuthorizationRequest(
                authRequest, this.User.Identity.Name, authRequest.Scope);
            IProtocolMessage responseMessage = grantedResponse;
            var response = await authServer.Channel.PrepareResponseAsync(responseMessage);
            return response.AsActionResult();
        }
예제 #4
0
		public async Task<ActionResult> Respond(string request, bool approval) {
			var authServer = new AuthorizationServer(new AuthorizationServerHost());
			var authRequest = await authServer.ReadAuthorizationRequestAsync(new Uri(request));
			IProtocolMessage responseMessage;
			if (approval) {
				var grantedResponse = authServer.PrepareApproveAuthorizationRequest(
					authRequest, this.User.Identity.Name, authRequest.Scope);
				responseMessage = grantedResponse;
			} else {
				var rejectionResponse = authServer.PrepareRejectAuthorizationRequest(authRequest);
				rejectionResponse.Error = Protocol.EndUserAuthorizationRequestErrorCodes.AccessDenied;
				responseMessage = rejectionResponse;
			}

			var response = await authServer.Channel.PrepareResponseAsync(responseMessage);
			return response.AsActionResult();
		}
		public async Task DecodeRefreshToken() {
			var refreshTokenSource = new TaskCompletionSource<string>();
			Handle(AuthorizationServerDescription.AuthorizationEndpoint).By(
				async (req, ct) => {
					var server = new AuthorizationServer(AuthorizationServerMock);
					var request = await server.ReadAuthorizationRequestAsync(req, ct);
					Assert.That(request, Is.Not.Null);
					var response = server.PrepareApproveAuthorizationRequest(request, ResourceOwnerUsername);
					return await server.Channel.PrepareResponseAsync(response);
				});
			Handle(AuthorizationServerDescription.TokenEndpoint).By(
				async (req, ct) => {
					var server = new AuthorizationServer(AuthorizationServerMock);
					var response = await server.HandleTokenRequestAsync(req, ct);
					var authorization = server.DecodeRefreshToken(refreshTokenSource.Task.Result);
					Assert.That(authorization, Is.Not.Null);
					Assert.That(authorization.User, Is.EqualTo(ResourceOwnerUsername));
					return response;
				});

			var client = new WebServerClient(AuthorizationServerDescription);
			try {
				var authState = new AuthorizationState(TestScopes) { Callback = ClientCallback, };
				var authRedirectResponse = await client.PrepareRequestUserAuthorizationAsync(authState);
				this.HostFactories.CookieContainer.SetCookies(authRedirectResponse, ClientCallback);
				Uri authCompleteUri;
				using (var httpClient = this.HostFactories.CreateHttpClient()) {
					using (var response = await httpClient.GetAsync(authRedirectResponse.Headers.Location)) {
						response.EnsureSuccessStatusCode();
						authCompleteUri = response.Headers.Location;
					}
				}

				var authCompleteRequest = new HttpRequestMessage(HttpMethod.Get, authCompleteUri);
				this.HostFactories.CookieContainer.ApplyCookies(authCompleteRequest);
				var result = await client.ProcessUserAuthorizationAsync(authCompleteRequest);
				Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
				Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty);
				refreshTokenSource.SetResult(result.RefreshToken);
			} catch {
				refreshTokenSource.TrySetCanceled();
			}
		}
		public async Task AuthorizationCodeGrant() {
			Handle(AuthorizationServerDescription.AuthorizationEndpoint).By(
				async (req, ct) => {
					var server = new AuthorizationServer(AuthorizationServerMock);
					var request = await server.ReadAuthorizationRequestAsync(req, ct);
					Assert.That(request, Is.Not.Null);
					var response = server.PrepareApproveAuthorizationRequest(request, ResourceOwnerUsername);
					return await server.Channel.PrepareResponseAsync(response, ct);
				});
			Handle(AuthorizationServerDescription.TokenEndpoint).By(
				async (req, ct) => {
					var server = new AuthorizationServer(AuthorizationServerMock);
					return await server.HandleTokenRequestAsync(req, ct);
				});

			var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories);
			var authState = new AuthorizationState(TestScopes) {
				Callback = ClientCallback,
			};
			var authRequestRedirect = await client.PrepareRequestUserAuthorizationAsync(authState);
			this.HostFactories.CookieContainer.SetCookies(authRequestRedirect, ClientCallback);
			Uri authRequestResponse;
			this.HostFactories.AllowAutoRedirects = false;
			using (var httpClient = this.HostFactories.CreateHttpClient()) {
				using (var httpResponse = await httpClient.GetAsync(authRequestRedirect.Headers.Location)) {
					Assert.That(httpResponse.StatusCode, Is.EqualTo(HttpStatusCode.Redirect));
					authRequestResponse = httpResponse.Headers.Location;
				}
			}

			var authorizationResponse = new HttpRequestMessage(HttpMethod.Get, authRequestResponse);
			this.HostFactories.CookieContainer.ApplyCookies(authorizationResponse);
			var result = await client.ProcessUserAuthorizationAsync(authorizationResponse, CancellationToken.None);
			Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
			Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty);
		}
예제 #7
0
        public ActionResult ProcessAuthorization(bool isApproved)
        {
            // Have DotNetOpenAuth read the info we need out of the request
            EndUserAuthorizationRequest pendingRequest = _authorizationServer.ReadAuthorizationRequest();

            if (pendingRequest == null)
            {
                throw new HttpException(Convert.ToInt32(HttpStatusCode.BadRequest), "Missing authorization request.");
            }

            // Make sure the client is one we recognize
            Client requestingClient = _clientRepository.GetById(pendingRequest.ClientIdentifier);

            if (requestingClient == null)
            {
                throw new HttpException(Convert.ToInt32(HttpStatusCode.BadRequest), "Invalid request");
            }

            // Make sure the resource is defined, it definitely should be due to the ResourceAuthenticated attribute
            Resource requestedResource = _resourceRepository.FindWithSupportedScopes(pendingRequest.Scope);

            if (requestedResource == null)
            {
                throw new HttpException(Convert.ToInt32(HttpStatusCode.BadRequest), "Invalid request");
            }

            // See if authorization of this client was approved by the user
            // At this point, the user either agrees to the entire scope requested by the client or none of it.
            // If we gave capability for user to reduce scope to give client less access, some changes would be required here
            IDirectedProtocolMessage authRequest;

            if (isApproved)
            {
                // Add user to our repository if this is their first time
                var requestingUser = _userRepository.GetById(User.Identity.Name);
                if (requestingUser == null)
                {
                    requestingUser = new User {
                        Id = User.Identity.Name, CreateDateUtc = DateTime.UtcNow
                    };
                    _userRepository.Insert(requestingUser);
                    _userRepository.Save();
                }

                // 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.
                _authorizationRepository.Insert(new Authorization
                {
                    ClientId     = requestingClient.Id,
                    Scope        = OAuthUtilities.JoinScopes(pendingRequest.Scope),
                    UserId       = requestingUser.Id,
                    ResourceId   = requestedResource.Id,
                    CreatedOnUtc = DateTime.UtcNow
                });
                _authorizationRepository.Save();

                // Have DotNetOpenAuth generate an approval to send back to the client
                authRequest = _authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, User.Identity.Name);
            }
            else
            {
                // Have DotNetOpenAuth generate a rejection to send back to the client
                authRequest = _authorizationServer.PrepareRejectAuthorizationRequest(pendingRequest);
                // The PrepareResponse call below is giving an error of "The following required parameters were missing from the DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationFailedResponse message: error"
                // unless I do this.....
                var msg = (EndUserAuthorizationFailedResponse)authRequest;
                msg.Error = "User denied your request";
            }

            // This will redirect to the client app using their defined callback, so they can handle
            // the approval or rejection as they see fit
            return(_authorizationServer.Channel.PrepareResponse(authRequest).AsActionResult());
        }
예제 #8
0
        public ActionResult AuthoriseResponse(FormCollection form)
        {
            using (var server = (new OAuth2AuthorizationServer(new X509Certificate2(_absolutePathToPfx, _certificatePassword),
                            new X509Certificate2(_absolutePathToCertificate))))
            {
                var authorizationServer = new AuthorizationServer(server);
                var pendingRequest = authorizationServer.ReadAuthorizationRequest();
                if (pendingRequest == null)
                {
                    throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
                }

                IDirectedProtocolMessage response;
                //if (isApproved)
                if (form["IsApproved"] == "Approve")
                {

                    // 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.DataContext.Users.FirstOrDefault(u => u.Username == System.Web.HttpContext.Current.User.Identity.Name),
                            CreatedOnUtc = DateTime.UtcNow,
                        });
                    MvcApplication.DataContext.SaveChanges(); // 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 = authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, User.Identity.Name);
                }
                else
                {
                    response = authorizationServer.PrepareRejectAuthorizationRequest(pendingRequest);
                }

                return authorizationServer.Channel.PrepareResponse(response).AsActionResult();
            }
        }