def clean_csrf_token(cls, csrf_token, payload): is_valid = _compare_masked_tokens(csrf_token, payload["csrfToken"]) if not is_valid: raise ValidationError({ "csrfToken": ValidationError( "Invalid csrf token", code=AccountErrorCode.JWT_INVALID_CSRF_TOKEN.value, ) })
def validate_refresh_token(refresh_token, data): csrf_token = data.get("csrfToken") if not refresh_token: raise ValidationError({ "refreshToken": ValidationError("Missing token.", code=PluginErrorCode.NOT_FOUND.value) }) try: refresh_payload = jwt_decode(refresh_token, verify_expiration=True) except PyJWTError: raise ValidationError({ "refreshToken": ValidationError( "Unable to decode the refresh token.", code=PluginErrorCode.INVALID.value, ) }) if not data.get("refreshToken"): if not refresh_payload.get(CSRF_FIELD): raise ValidationError({ CSRF_FIELD: ValidationError( "Missing CSRF token in refresh payload.", code=PluginErrorCode.INVALID.value, ) }) if not csrf_token: raise ValidationError({ "csrfToken": ValidationError( "CSRF token needs to be provided.", code=PluginErrorCode.INVALID.value, ) }) is_valid = _compare_masked_tokens(csrf_token, refresh_payload[CSRF_FIELD]) if not is_valid: raise ValidationError({ "csrfToken": ValidationError( "CSRF token doesn't match.", code=PluginErrorCode.INVALID.value, ) })
def get(self, request, *args, **kwargs): provider = kwargs.get('provider') if provider == 'naver': # 프로바이더가 naver 일 경우 csrf_token = request.GET.get('state') code = request.GET.get('code') if not _compare_masked_tokens(csrf_token, request.COOKIES.get('csrftoken')): # state(csrf_token)이 잘못된 경우 messages.error(request, '잘못된 경로로 로그인하셨습니다.', extra_tags='danger') print("Not match") return redirect(self.failure_url) is_success, error = self.login_with_naver(csrf_token, code) if not is_success: # 로그인 실패할 경우 messages.error(request, error, extra_tags='danger') return redirect(self.success_url if is_success else self.failure_url) return redirect(self.failure_url)
def clean_csrf_token(cls, csrf_token, payload): if not csrf_token: msg = "CSRF token is required when refreshToken is provided by the cookie" raise ValidationError({ "csrf_token": ValidationError( msg, code=AccountErrorCode.REQUIRED.value, ) }) is_valid = _compare_masked_tokens(csrf_token, payload["csrfToken"]) if not is_valid: raise ValidationError({ "csrf_token": ValidationError( "Invalid csrf token", code=AccountErrorCode.JWT_INVALID_CSRF_TOKEN.value, ) })
def process_view(self, request, callback, callback_args, callback_kwargs): if getattr(request, "csrf_processing_done", False): return None # Wait until request.META["CSRF_COOKIE"] has been manipulated before # bailing out, so that get_token still works if getattr(callback, "csrf_exempt", False): return None # Assume that anything not defined as 'safe' by RFC7231 needs protection if request.method not in ("GET", "HEAD", "OPTIONS", "TRACE"): if getattr(request, "_dont_enforce_csrf_checks", False): # Mechanism to turn off CSRF checks for test suite. # It comes after the creation of CSRF cookies, so that # everything else continues to work exactly the same # (e.g. cookies are sent, etc.), but before any # branches that call reject(). return self._accept(request) if request.is_secure(): # Suppose user visits http://example.com/ # An active network attacker (man-in-the-middle, MITM) sends a # POST form that targets https://example.com/detonate-bomb/ and # submits it via JavaScript. # # The attacker will need to provide a CSRF cookie and token, but # that's no problem for a MITM and the session-independent # secret we're using. So the MITM can circumvent the CSRF # protection. This is true for any HTTP connection, but anyone # using HTTPS expects better! For this reason, for # https://example.com/ we need additional protection that treats # http://example.com/ as completely untrusted. Under HTTPS, # Barth et al. found that the Referer header is missing for # same-domain requests in only about 0.2% of cases or less, so # we can use strict Referer checking. referer = request.META.get("HTTP_REFERER") # -- Change from original here -- # # Only checks referer if it is present. # It's not a failure condition if the referer is not present. # Our site is HTTPS-only which does not need to rely on # referer checking. Above example does not apply. if referer is not None: referer = urlparse(referer) # Make sure we have a valid URL for Referer. if "" in (referer.scheme, referer.netloc): return self._reject(request, REASON_MALFORMED_REFERER) # Ensure that our Referer is also secure. if referer.scheme != "https" and not referer.netloc.endswith( ".onion"): return self._reject(request, REASON_INSECURE_REFERER) # If there isn't a CSRF_COOKIE_DOMAIN, require an exact match # match on host:port. If not, obey the cookie rules (or those # for the session cookie, if CSRF_USE_SESSIONS). good_referer = (settings.SESSION_COOKIE_DOMAIN if settings.CSRF_USE_SESSIONS else settings.CSRF_COOKIE_DOMAIN) if good_referer is not None: server_port = request.get_port() if server_port not in ("443", "80"): good_referer = "%s:%s" % (good_referer, server_port) else: try: # request.get_host() includes the port. good_referer = request.get_host() except DisallowedHost: pass # Create a list of all acceptable HTTP referers, including the # current host if it's permitted by ALLOWED_HOSTS. good_hosts = list(settings.CSRF_TRUSTED_ORIGINS) if good_referer is not None: good_hosts.append(good_referer) if not any( is_same_domain(referer.netloc, host) for host in good_hosts): reason = REASON_BAD_REFERER % referer.geturl() return self._reject(request, reason) csrf_token = self._get_token(request) if csrf_token is None: # No CSRF cookie. For POST requests, we insist on a CSRF cookie, # and in this way we can avoid all CSRF attacks, including login # CSRF. return self._reject(request, REASON_NO_CSRF_COOKIE) # Check non-cookie token for match. request_csrf_token = "" if request.method == "POST": try: request_csrf_token = request.POST.get( "csrfmiddlewaretoken", "") except OSError: # Handle a broken connection before we've completed reading # the POST data. process_view shouldn't raise any # exceptions, so we'll ignore and serve the user a 403 # (assuming they're still listening, which they probably # aren't because of the error). pass if request_csrf_token == "": # Fall back to X-CSRFToken, to make things easier for AJAX, # and possible for PUT/DELETE. request_csrf_token = request.META.get( settings.CSRF_HEADER_NAME, "") request_csrf_token = _sanitize_token(request_csrf_token) if not _compare_masked_tokens(request_csrf_token, csrf_token): return self._reject(request, REASON_BAD_TOKEN) return self._accept(request)
def get(self, request): code = request.GET.get('code') state = request.GET.get('state', None) csrf_token = request.META.get("CSRF_COOKIE", None) if not code: raise Http404 # if csrf_token doesn't match, raise 403 if not _compare_masked_tokens(state, csrf_token): raise Http403 # fetch access token r = requests.post(STRIPE_TOKEN_URL, data={ 'client_secret': settings.STRIPE_SECRET_KEY, 'grant_type': 'authorization_code', 'code': code, 'scope': 'read_only' }) response_json = r.json() if r.ok: stripe_user_id = response_json['stripe_user_id'] # livemode = response_json['livemode'] sa, created = StripeAccount.objects.get_or_create( stripe_user_id=stripe_user_id) # if livemode: # sa.livemode_access_token = response_json['access_token'] # sa.livemode_stripe_publishable_key = response_json['stripe_publishable_key'] # else: # sa.testmode_access_token = response_json['access_token'] # sa.testmode_stripe_publishable_key = response_json['stripe_publishable_key'] sa.scope = response_json['scope'] # sa.token_type = response_json['token_type'] # sa.refresh_token = response_json['refresh_token'] if not sa.creator: sa.creator = request.user sa.creator_username = request.user.username sa.owner = request.user sa.owner_username = request.user.username sa.status_detail = 'active' sa.save() # retrieve account info stripe.api_key = settings.STRIPE_SECRET_KEY stripe.api_version = settings.STRIPE_API_VERSION stripe_set_app_info(stripe) account = stripe.Account.retrieve(stripe_user_id) sa.account_name = account.get('display_name', '') sa.email = account.get('email', '') sa.default_currency = account.get('default_currency', '') sa.country = account.get('country', '') sa.save() msg_string = _('Success!') else: sa = None msg_string = '{0} - {1}'.format(response_json['error'], response_json['error_description']) return render(request, self.template_name, { 'sa': sa, 'msg_string': msg_string })