Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

token이 없는 로그인 상태 #53

Open
saebyeok0306 opened this issue Oct 13, 2023 · 2 comments
Open

token이 없는 로그인 상태 #53

saebyeok0306 opened this issue Oct 13, 2023 · 2 comments
Assignees
Labels
fix 버그 수정

Comments

@saebyeok0306
Copy link
Collaborator

상황

  1. 로그인을 했다가 브라우저를 완전히 종료 후 다시 접속했을 때
  2. 쿠키 정보는 날라가고, 로그인 상태정보는 남아있어서 로그인이 유지되는걸로 표기됨.
  3. 이 상태에서 인증이 필요한 API 호출시, HTTP Status 500 에러와 "Internal Server Error" response message를 반환함.

해결포인트

  1. @jwt_required() 에서 Error를 반환하는게 아니고, Response로 500 Error와 Message를 반환함. > 어떻게 캐치?
  2. 리프레쉬 토큰도 사용하고 있으니 의미있게 쓰려면 쿠키정보가 브라우저를 종료했을 때 사라지면 안됨.
  3. 쿠키가 사라지지 않게 Expires/Max-Age 값을 넣어줘야?
@saebyeok0306 saebyeok0306 added the fix 버그 수정 label Oct 13, 2023
@saebyeok0306 saebyeok0306 self-assigned this Oct 13, 2023
@saebyeok0306
Copy link
Collaborator Author

jwt_required()Flask-JWT-Extended 같은 라이브러리에서 주로 사용되는 데코레이터로, JWT 토큰을 필요로 하는 Flask 라우트에 대한 접근을 제어합니다. 이 데코레이터가 발생시킬 수 있는 에러를 핸들링하려면 다음과 같은 방법을 사용할 수 있습니다.

  1. 커스텀 에러 핸들러 정의
    Flask-JWT-Extended에서는 커스텀 에러 핸들러를 정의하여 특정 에러에 대한 처리를 할 수 있습니다.
from flask_jwt_extended import JWTManager

jwt = JWTManager(app)

@jwt.expired_token_loader
def my_expired_token_callback(expired_token):
    token_type = expired_token['type']
    return jsonify({'msg': 'The {} token has expired'.format(token_type)}), 401

@jwt.invalid_token_loader
def my_invalid_token_callback(invalid_token):
    return jsonify({'msg': 'Invalid token'}), 422  # change 422 to any status code you want
  1. before_request 사용
    Flask의 before_request 훅을 사용하여 각 요청이 처리되기 전에 토큰 유효성을 검사하고 에러를 핸들링할 수 있습니다.
@app.before_request
def before_request_func():
    try:
        jwt_required()(lambda: None)()
    except Exception as e:
        # 여기서 에러를 핸들링
  1. try-except 사용 (데코레이터 감싸기)
    jwt_required() 데코레이터를 감싸는 또 다른 데코레이터를 작성하여 에러를 캐치할 수 있습니다.
from functools import wraps

def jwt_required_with_error_handling():
    @wraps(fn)
    def wrapper(*args, **kwargs):
        try:
            return jwt_required()(fn)(*args, **kwargs)
        except Exception as e:
            # 여기서 에러를 핸들링
    return wrapper

@app.route('/protected', methods=['GET'])
@jwt_required_with_error_handling
def protected_route():
    return jsonify({'msg': 'This is a protected route.'})

위의 방법 중 하나를 선택하여 jwt_required() 데코레이터가 발생시킬 수 있는 에러를 핸들링할 수 있습니다.

@ssfic3380 윤석님이 남긴 내용 가져옴.

@saebyeok0306
Copy link
Collaborator Author

토큰쿠키의 Expires를 지정하려면

  1. JWT_ACCESS_TOKEN_EXPIRES

How long an access token should be valid before it expires. This can be a datetime.timedelta, dateutil.relativedelta, or a number of seconds (Integer).

If set to False tokens will never expire. This is dangerous and should be avoided in most case

This can be overridden on a per token basis by passing the expires_delta argument to flask_jwt_extended.create_access_token()

Default: datetime.timedelta(minutes=15)

  1. JWT_REFRESH_TOKEN_EXPIRES

How long a refresh token should be valid before it expires. This can be a datetime.timedelta, dateutil.relativedelta, or a number of seconds (Integer).

If set to False tokens will never expire. This is dangerous and should be avoided in most case

This can be overridden on a per token basis by passing the expires_delta argument to flask_jwt_extended.create_refresh_token()

Default: datetime.timedelta(days=30)

  1. JWT_SESSION_COOKIE

Controls if the cookies will be set as session cookies, which are deleted when the browser is closed.

Default: True > False

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
fix 버그 수정
Projects
None yet
Development

No branches or pull requests

1 participant