ReadAuthorizationRequest() 개인적인 메소드

private ReadAuthorizationRequest ( System.Web.HttpRequestBase request = null ) : DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationRequest
request System.Web.HttpRequestBase
리턴 DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationRequest
예제 #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);
            }
        }
예제 #2
0
        public ActionResult Authorize()
        {
            // 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");
            }

            // Ensure client is allowed to use the requested scopes
            if (!pendingRequest.Scope.IsSubsetOf(requestingClient.SupportedScopes))
            {
                throw new HttpException(Convert.ToInt32(HttpStatusCode.BadRequest), "Invalid request");
            }

            // Consider auto-approving if safe, so user doesn't have to authorize repeatedly.
            // Leaving this step out for now

            // Show user the authorization page by which they can authorize this client to access their
            // data within the resource determined by the requested scopes
            var model = new AccountAuthorizeModel
            {
                Client = requestingClient,
                Scopes = requestingClient.Scopes.Where(x => pendingRequest.Scope.Contains(x.Identifier)).ToList(),
                AuthorizationRequest = pendingRequest
            };

            return(View(model));
        }
예제 #3
0
        public ActionResult AuthoriseResponse(bool isApproved)
        {
            using (OAuth2AuthorizationServer server = (new OAuth2AuthorizationServer(new X509Certificate2(ConfigurationManager.AppSettings["AbsolutePathToPfx"], ConfigurationManager.AppSettings["CertificatePassword"]),
                            new X509Certificate2(ConfigurationManager.AppSettings["AbsolutePathToCertificate"]))))
            {
                AuthorizationServer authorizationServer = new AuthorizationServer(server);
                var pendingRequest = authorizationServer.ReadAuthorizationRequest();
                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.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();
            }
        }
예제 #4
0
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            // Figure out what resource the request is intending to access to see if the
            // user has already authenticated to with it
            EndUserAuthorizationRequest pendingRequest = _authorizationServer.ReadAuthorizationRequest();

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

            try
            {
                _targetResource = _resourceRepository.FindWithSupportedScopes(pendingRequest.Scope);

                // Above will return null if no resource supports all of the requested scopes
                if (_targetResource == null)
                {
                    throw new HttpException(Convert.ToInt32(HttpStatusCode.BadRequest), "Bad authorization request.");
                }
            }
            catch (Exception)
            {
                throw new HttpException(Convert.ToInt32(HttpStatusCode.BadRequest), "Bad authorization request.");
            }

            // User is considered authorized if in possession of token that originated from the resource's login page,
            // Name of token is determined by the resource configuration
            string tokenName      = _targetResource.AuthenticationTokenName;
            string encryptedToken = httpContext.Request[tokenName]; //could be in cookie if previously logged in, or querystring if just logged in

            if (string.IsNullOrWhiteSpace(encryptedToken))
            {
                // No token, so unauthorized
                return(false);
            }

            // Validate this thing came from us via shared secret with the resource's login page
            // The implementation here ideally could be generalized a bit better or standardized
            string encryptionKey  = _targetResource.AuthenticationKey;
            string decryptedToken = EncodingUtility.Decode(encryptedToken, encryptionKey);

            string[] tokenContentParts = decryptedToken.Split(';');

            string   name        = tokenContentParts[0];
            DateTime loginDate   = DateTime.Parse(tokenContentParts[1]);
            bool     storeCookie = bool.Parse(tokenContentParts[2]);

            if ((DateTime.Now.Subtract(loginDate) > TimeSpan.FromDays(7)))
            {
                // Expired, remove cookie if present and flag user as unauthorized
                httpContext.Response.Cookies.Remove(tokenName);
                return(false);
            }

            // Things look good.
            // Set principal for the authorization server
            IIdentity identity = new GenericIdentity(name);

            httpContext.User = new GenericPrincipal(identity, null);

            // If desired, persist cookie so user doesn't have to authenticate with the resource over and over
            var cookie = new HttpCookie(tokenName, encryptedToken);

            if (storeCookie)
            {
                cookie.Expires = DateTime.Now.AddDays(7); // could parameterize lifetime
            }
            httpContext.Response.AppendCookie(cookie);
            return(true);
        }