mirror of
https://github.com/jumpserver/jumpserver.git
synced 2026-01-26 13:25:10 +00:00
[Update] 支持 OpenID 认证 (#2008)
* [Update] core支持openid登录,coco还不支持 * [Update] coco支持openid登录 * [Update] 修改注释 * [Update] 修改 OpenID Auth Code Backend 用户认证失败返回None, 不是Anonymoususer * [Update] 修改OpenID Code用户认证异常捕获 * [Update] 修改OpenID Auth Middleware, check用户是否单点退出的异常捕获 * [Update] 修改config_example Auth OpenID 配置 * [Update] 登录页面添加 更多登录方式 * [Update] 重构OpenID认证架构 * [Update] 修改小细节 * [Update] OpenID用户认证成功后,更新用户来源 * [update] 添加OpenID用户登录成功日志
This commit is contained in:
0
apps/authentication/__init__.py
Normal file
0
apps/authentication/__init__.py
Normal file
1
apps/authentication/admin.py
Normal file
1
apps/authentication/admin.py
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
10
apps/authentication/apps.py
Normal file
10
apps/authentication/apps.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class AuthenticationConfig(AppConfig):
|
||||
name = 'authentication'
|
||||
|
||||
def ready(self):
|
||||
from . import signals_handlers
|
||||
super().ready()
|
||||
|
||||
1
apps/authentication/models.py
Normal file
1
apps/authentication/models.py
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
20
apps/authentication/openid/__init__.py
Normal file
20
apps/authentication/openid/__init__.py
Normal file
@@ -0,0 +1,20 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
|
||||
from django.conf import settings
|
||||
from .models import Client
|
||||
|
||||
|
||||
def new_client():
|
||||
"""
|
||||
:return: authentication.models.Client
|
||||
"""
|
||||
return Client(
|
||||
server_url=settings.AUTH_OPENID_SERVER_URL,
|
||||
realm_name=settings.AUTH_OPENID_REALM_NAME,
|
||||
client_id=settings.AUTH_OPENID_CLIENT_ID,
|
||||
client_secret=settings.AUTH_OPENID_CLIENT_SECRET
|
||||
)
|
||||
|
||||
|
||||
client = new_client()
|
||||
90
apps/authentication/openid/backends.py
Normal file
90
apps/authentication/openid/backends.py
Normal file
@@ -0,0 +1,90 @@
|
||||
# coding:utf-8
|
||||
#
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.conf import settings
|
||||
|
||||
from . import client
|
||||
from common.utils import get_logger
|
||||
from authentication.openid.models import OIDT_ACCESS_TOKEN
|
||||
|
||||
UserModel = get_user_model()
|
||||
|
||||
logger = get_logger(__file__)
|
||||
|
||||
BACKEND_OPENID_AUTH_CODE = \
|
||||
'authentication.openid.backends.OpenIDAuthorizationCodeBackend'
|
||||
|
||||
|
||||
class BaseOpenIDAuthorizationBackend(object):
|
||||
|
||||
@staticmethod
|
||||
def user_can_authenticate(user):
|
||||
"""
|
||||
Reject users with is_active=False. Custom user models that don't have
|
||||
that attribute are allowed.
|
||||
"""
|
||||
is_active = getattr(user, 'is_active', None)
|
||||
return is_active or is_active is None
|
||||
|
||||
def get_user(self, user_id):
|
||||
try:
|
||||
user = UserModel._default_manager.get(pk=user_id)
|
||||
except UserModel.DoesNotExist:
|
||||
return None
|
||||
|
||||
return user if self.user_can_authenticate(user) else None
|
||||
|
||||
|
||||
class OpenIDAuthorizationCodeBackend(BaseOpenIDAuthorizationBackend):
|
||||
|
||||
def authenticate(self, request, **kwargs):
|
||||
logger.info('1.openid code backend')
|
||||
|
||||
code = kwargs.get('code')
|
||||
redirect_uri = kwargs.get('redirect_uri')
|
||||
|
||||
if not code or not redirect_uri:
|
||||
return None
|
||||
|
||||
try:
|
||||
oidt_profile = client.update_or_create_from_code(
|
||||
code=code,
|
||||
redirect_uri=redirect_uri
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
|
||||
else:
|
||||
# Check openid user single logout or not with access_token
|
||||
request.session[OIDT_ACCESS_TOKEN] = oidt_profile.access_token
|
||||
|
||||
user = oidt_profile.user
|
||||
|
||||
return user if self.user_can_authenticate(user) else None
|
||||
|
||||
|
||||
class OpenIDAuthorizationPasswordBackend(BaseOpenIDAuthorizationBackend):
|
||||
|
||||
def authenticate(self, request, username=None, password=None, **kwargs):
|
||||
logger.info('2.openid password backend')
|
||||
|
||||
if not settings.AUTH_OPENID:
|
||||
return None
|
||||
|
||||
elif not username:
|
||||
return None
|
||||
|
||||
try:
|
||||
oidt_profile = client.update_or_create_from_password(
|
||||
username=username, password=password
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
|
||||
else:
|
||||
user = oidt_profile.user
|
||||
return user if self.user_can_authenticate(user) else None
|
||||
|
||||
42
apps/authentication/openid/middleware.py
Normal file
42
apps/authentication/openid/middleware.py
Normal file
@@ -0,0 +1,42 @@
|
||||
# coding:utf-8
|
||||
#
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth import logout
|
||||
from django.utils.deprecation import MiddlewareMixin
|
||||
from django.contrib.auth import BACKEND_SESSION_KEY
|
||||
|
||||
from . import client
|
||||
from common.utils import get_logger
|
||||
from .backends import BACKEND_OPENID_AUTH_CODE
|
||||
from authentication.openid.models import OIDT_ACCESS_TOKEN
|
||||
|
||||
logger = get_logger(__file__)
|
||||
|
||||
|
||||
class OpenIDAuthenticationMiddleware(MiddlewareMixin):
|
||||
"""
|
||||
Check openid user single logout (with access_token)
|
||||
"""
|
||||
|
||||
def process_request(self, request):
|
||||
|
||||
# Don't need openid auth if AUTH_OPENID is False
|
||||
if not settings.AUTH_OPENID:
|
||||
return
|
||||
|
||||
# Don't need check single logout if user not authenticated
|
||||
if not request.user.is_authenticated:
|
||||
return
|
||||
|
||||
elif request.session[BACKEND_SESSION_KEY] != BACKEND_OPENID_AUTH_CODE:
|
||||
return
|
||||
|
||||
# Check openid user single logout or not with access_token
|
||||
try:
|
||||
client.openid_connect_client.userinfo(
|
||||
token=request.session.get(OIDT_ACCESS_TOKEN))
|
||||
|
||||
except Exception as e:
|
||||
logout(request)
|
||||
logger.error(e)
|
||||
159
apps/authentication/openid/models.py
Normal file
159
apps/authentication/openid/models.py
Normal file
@@ -0,0 +1,159 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
|
||||
from django.db import transaction
|
||||
from django.contrib.auth import get_user_model
|
||||
from keycloak.realm import KeycloakRealm
|
||||
from keycloak.keycloak_openid import KeycloakOpenID
|
||||
from ..signals import post_create_openid_user
|
||||
|
||||
OIDT_ACCESS_TOKEN = 'oidt_access_token'
|
||||
|
||||
|
||||
class OpenIDTokenProfile(object):
|
||||
|
||||
def __init__(self, user, access_token, refresh_token):
|
||||
"""
|
||||
:param user: User object
|
||||
:param access_token:
|
||||
:param refresh_token:
|
||||
"""
|
||||
self.user = user
|
||||
self.access_token = access_token
|
||||
self.refresh_token = refresh_token
|
||||
|
||||
def __str__(self):
|
||||
return "{}'s OpenID token profile".format(self.user.username)
|
||||
|
||||
|
||||
class Client(object):
|
||||
|
||||
def __init__(self, server_url, realm_name, client_id, client_secret):
|
||||
self.server_url = server_url
|
||||
self.realm_name = realm_name
|
||||
self.client_id = client_id
|
||||
self.client_secret = client_secret
|
||||
self.realm = self.new_realm()
|
||||
self.openid_client = self.new_openid_client()
|
||||
self.openid_connect_client = self.new_openid_connect_client()
|
||||
|
||||
def new_realm(self):
|
||||
"""
|
||||
:param authentication.openid.models.Realm realm:
|
||||
:return keycloak.realm.Realm:
|
||||
"""
|
||||
return KeycloakRealm(
|
||||
server_url=self.server_url,
|
||||
realm_name=self.realm_name,
|
||||
headers={}
|
||||
)
|
||||
|
||||
def new_openid_connect_client(self):
|
||||
"""
|
||||
:rtype: keycloak.openid_connect.KeycloakOpenidConnect
|
||||
"""
|
||||
openid_connect = self.realm.open_id_connect(
|
||||
client_id=self.client_id,
|
||||
client_secret=self.client_secret
|
||||
)
|
||||
return openid_connect
|
||||
|
||||
def new_openid_client(self):
|
||||
"""
|
||||
:rtype: keycloak.keycloak_openid.KeycloakOpenID
|
||||
"""
|
||||
|
||||
return KeycloakOpenID(
|
||||
server_url='%sauth/' % self.server_url,
|
||||
realm_name=self.realm_name,
|
||||
client_id=self.client_id,
|
||||
client_secret_key=self.client_secret,
|
||||
)
|
||||
|
||||
def update_or_create_from_password(self, username, password):
|
||||
"""
|
||||
Update or create an user based on an authentication username and password.
|
||||
|
||||
:param str username: authentication username
|
||||
:param str password: authentication password
|
||||
:return: authentication.models.OpenIDTokenProfile
|
||||
"""
|
||||
token_response = self.openid_client.token(
|
||||
username=username, password=password
|
||||
)
|
||||
|
||||
return self._update_or_create(token_response=token_response)
|
||||
|
||||
def update_or_create_from_code(self, code, redirect_uri):
|
||||
"""
|
||||
Update or create an user based on an authentication code.
|
||||
Response as specified in:
|
||||
|
||||
https://tools.ietf.org/html/rfc6749#section-4.1.4
|
||||
|
||||
:param str code: authentication code
|
||||
:param str redirect_uri:
|
||||
:rtype: authentication.models.OpenIDTokenProfile
|
||||
"""
|
||||
|
||||
token_response = self.openid_connect_client.authorization_code(
|
||||
code=code, redirect_uri=redirect_uri)
|
||||
|
||||
return self._update_or_create(token_response=token_response)
|
||||
|
||||
def _update_or_create(self, token_response):
|
||||
"""
|
||||
Update or create an user based on a token response.
|
||||
|
||||
`token_response` contains the items returned by the OpenIDConnect Token API
|
||||
end-point:
|
||||
- id_token
|
||||
- access_token
|
||||
- expires_in
|
||||
- refresh_token
|
||||
- refresh_expires_in
|
||||
|
||||
:param dict token_response:
|
||||
:rtype: authentication.openid.models.OpenIDTokenProfile
|
||||
"""
|
||||
|
||||
userinfo = self.openid_connect_client.userinfo(
|
||||
token=token_response['access_token'])
|
||||
|
||||
with transaction.atomic():
|
||||
user, _ = get_user_model().objects.update_or_create(
|
||||
username=userinfo.get('preferred_username', ''),
|
||||
defaults={
|
||||
'email': userinfo.get('email', ''),
|
||||
'first_name': userinfo.get('given_name', ''),
|
||||
'last_name': userinfo.get('family_name', '')
|
||||
}
|
||||
)
|
||||
|
||||
oidt_profile = OpenIDTokenProfile(
|
||||
user=user,
|
||||
access_token=token_response['access_token'],
|
||||
refresh_token=token_response['refresh_token'],
|
||||
)
|
||||
|
||||
if user:
|
||||
post_create_openid_user.send(sender=user.__class__, user=user)
|
||||
|
||||
return oidt_profile
|
||||
|
||||
def __str__(self):
|
||||
return self.client_id
|
||||
|
||||
|
||||
class Nonce(object):
|
||||
"""
|
||||
The openid-login is stored in cache as a temporary object, recording the
|
||||
user's redirect_uri and next_pat
|
||||
"""
|
||||
|
||||
def __init__(self, redirect_uri, next_path):
|
||||
import uuid
|
||||
self.state = uuid.uuid4()
|
||||
self.redirect_uri = redirect_uri
|
||||
self.next_path = next_path
|
||||
|
||||
0
apps/authentication/openid/tests.py
Normal file
0
apps/authentication/openid/tests.py
Normal file
102
apps/authentication/openid/views.py
Normal file
102
apps/authentication/openid/views.py
Normal file
@@ -0,0 +1,102 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
|
||||
import logging
|
||||
|
||||
from django.urls import reverse
|
||||
from django.conf import settings
|
||||
from django.core.cache import cache
|
||||
from django.views.generic.base import RedirectView
|
||||
from django.contrib.auth import authenticate, login
|
||||
from django.http.response import (
|
||||
HttpResponseBadRequest,
|
||||
HttpResponseServerError,
|
||||
HttpResponseRedirect
|
||||
)
|
||||
|
||||
from . import client
|
||||
from .models import Nonce
|
||||
from users.models import LoginLog
|
||||
from users.tasks import write_login_log_async
|
||||
from common.utils import get_request_ip
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_base_site_url():
|
||||
return settings.BASE_SITE_URL
|
||||
|
||||
|
||||
class LoginView(RedirectView):
|
||||
|
||||
def get_redirect_url(self, *args, **kwargs):
|
||||
nonce = Nonce(
|
||||
redirect_uri=get_base_site_url() + reverse(
|
||||
"authentication:openid-login-complete"),
|
||||
|
||||
next_path=self.request.GET.get('next')
|
||||
)
|
||||
|
||||
cache.set(str(nonce.state), nonce, 24*3600)
|
||||
|
||||
self.request.session['openid_state'] = str(nonce.state)
|
||||
|
||||
authorization_url = client.openid_connect_client.\
|
||||
authorization_url(
|
||||
redirect_uri=nonce.redirect_uri, scope='code',
|
||||
state=str(nonce.state)
|
||||
)
|
||||
|
||||
return authorization_url
|
||||
|
||||
|
||||
class LoginCompleteView(RedirectView):
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
if 'error' in request.GET:
|
||||
return HttpResponseServerError(self.request.GET['error'])
|
||||
|
||||
if 'code' not in self.request.GET and 'state' not in self.request.GET:
|
||||
return HttpResponseBadRequest()
|
||||
|
||||
if self.request.GET['state'] != self.request.session['openid_state']:
|
||||
return HttpResponseBadRequest()
|
||||
|
||||
nonce = cache.get(self.request.GET['state'])
|
||||
|
||||
if not nonce:
|
||||
return HttpResponseBadRequest()
|
||||
|
||||
user = authenticate(
|
||||
request=self.request,
|
||||
code=self.request.GET['code'],
|
||||
redirect_uri=nonce.redirect_uri
|
||||
)
|
||||
|
||||
cache.delete(str(nonce.state))
|
||||
|
||||
if not user:
|
||||
return HttpResponseBadRequest()
|
||||
|
||||
login(self.request, user)
|
||||
|
||||
data = {
|
||||
'username': user.username,
|
||||
'mfa': int(user.otp_enabled),
|
||||
'reason': LoginLog.REASON_NOTHING,
|
||||
'status': True
|
||||
}
|
||||
self.write_login_log(data)
|
||||
|
||||
return HttpResponseRedirect(nonce.next_path or '/')
|
||||
|
||||
def write_login_log(self, data):
|
||||
login_ip = get_request_ip(self.request)
|
||||
user_agent = self.request.META.get('HTTP_USER_AGENT', '')
|
||||
tmp_data = {
|
||||
'ip': login_ip,
|
||||
'type': 'W',
|
||||
'user_agent': user_agent
|
||||
}
|
||||
data.update(tmp_data)
|
||||
write_login_log_async.delay(**data)
|
||||
4
apps/authentication/signals.py
Normal file
4
apps/authentication/signals.py
Normal file
@@ -0,0 +1,4 @@
|
||||
from django.dispatch import Signal
|
||||
|
||||
|
||||
post_create_openid_user = Signal(providing_args=('user',))
|
||||
33
apps/authentication/signals_handlers.py
Normal file
33
apps/authentication/signals_handlers.py
Normal file
@@ -0,0 +1,33 @@
|
||||
from django.http.request import QueryDict
|
||||
from django.contrib.auth.signals import user_logged_out
|
||||
from django.dispatch import receiver
|
||||
from django.conf import settings
|
||||
from .openid import client
|
||||
from .signals import post_create_openid_user
|
||||
|
||||
|
||||
@receiver(user_logged_out)
|
||||
def on_user_logged_out(sender, request, user, **kwargs):
|
||||
if not settings.AUTH_OPENID:
|
||||
return
|
||||
|
||||
query = QueryDict('', mutable=True)
|
||||
query.update({
|
||||
'redirect_uri': settings.BASE_SITE_URL
|
||||
})
|
||||
|
||||
openid_logout_url = "%s?%s" % (
|
||||
client.openid_connect_client.get_url(
|
||||
name='end_session_endpoint'),
|
||||
query.urlencode()
|
||||
)
|
||||
|
||||
request.COOKIES['next'] = openid_logout_url
|
||||
|
||||
|
||||
@receiver(post_create_openid_user)
|
||||
def on_post_create_openid_user(sender, user=None, **kwargs):
|
||||
if user and user.username != 'admin':
|
||||
user.source = user.SOURCE_OPENID
|
||||
user.save()
|
||||
|
||||
1
apps/authentication/tests.py
Normal file
1
apps/authentication/tests.py
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
1
apps/authentication/urls/api_urls.py
Normal file
1
apps/authentication/urls/api_urls.py
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
16
apps/authentication/urls/view_urls.py
Normal file
16
apps/authentication/urls/view_urls.py
Normal file
@@ -0,0 +1,16 @@
|
||||
# coding:utf-8
|
||||
#
|
||||
|
||||
from django.urls import path
|
||||
from authentication.openid import views
|
||||
|
||||
app_name = 'authentication'
|
||||
|
||||
urlpatterns = [
|
||||
# openid
|
||||
path('openid/login/', views.LoginView.as_view(), name='openid-login'),
|
||||
path('openid/login/complete/', views.LoginCompleteView.as_view(),
|
||||
name='openid-login-complete'),
|
||||
|
||||
# other
|
||||
]
|
||||
1
apps/authentication/views.py
Normal file
1
apps/authentication/views.py
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
Reference in New Issue
Block a user