实现基于ldap认证登录认证以及token认证:
主要库:flask ,mongo,redis,ldap
1.代码
1.1目录结构
auth-manage
├── bin
│ ├── start.sh
│ └── stop.sh
├── conf
│ └── conf.ini
├── data
├── logs
│ └── auth-manage.log
└── project
├── auth_api.py
└── auth_manage.py
1.2启停脚本
1.2.1 启动脚本start.sh
#!/bin/sh
basepath=$(cd `dirname $0`; pwd)
echo $basepath
nohup python3 $basepath/../project/auth_api.py 2>&1 /dev/null &
1.2.2停止脚本stop.sh
#!/bin/bash
name='auth_api.py'
pid=$(ps -ef|grep "../project/$name"|grep -v grep|awk '{print $2}')
if [ -z "$pid" ];then
echo 'process is not alived'
else
echo 'kill process'
kill -9 $pid
pid=$(ps -ef|grep "../project/$name"|grep -v grep|awk '{print $2}')
if [ -z "$pid" ];then
echo 'kill process success'
else
echo 'kill process error'
fi
fi
1.3配置文件conf.ini
[log]
loglevel = debug
logname = auth-manage.log
interval = 1
backupCount = 7
when = MIDNIGHT
encoding = utf-8
[mongodb]
host = xxxxx
dbname = devops
user = xxxxx
password = xxxx
[ldap]
host = xxxx.com
port = 389
base_dn = ou=xxx,dc=xxxx,dc=com
user_dn = cn=xxx,ou=Public,dc=xxxx,dc=com
password = xxxxx
[redis]
host = xxxxxx
port = 6379
db = 0
redis_expire = 3600
password = xxxxxx
1.4工程代码auth_manage.py
# -*- coding: UTF-8 -*-
import os
import sys
import time
import logging
import configparser
import re
from logging.handlers import TimedRotatingFileHandler
import json
import requests
from multiprocessing import Process,Lock
import threading
import hashlib
import datetime
import pymongo
from pymongo import MongoClient, DESCENDING
from bs4 import BeautifulSoup
from ldap3 import (
Server,
Connection,
SUBTREE,
LEVEL,
ALL_ATTRIBUTES,
RESTARTABLE,
SAFE_RESTARTABLE,
MODIFY_REPLACE,
MODIFY_DELETE,
)
from ldap3.protocol.microsoft import show_deleted_control
from ldap3.utils.dn import safe_rdn
from ldap3.core.exceptions import LDAPException, LDAPInvalidCredentialsResult
import redis
import base64
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CONF_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),'conf','conf.ini')
def getNowTime():
return time.strftime(r'%Y%m%d%H%M%S',time.localtime(time.time()))
class param():
def __init__(self,confPath):
# self.conf = configparser.ConfigParser()
self.conf = configparser.RawConfigParser()
self.conf.read(confPath)
self.log_init()
self.mongodb_init()
self.ldap_init()
self.redis_init()
def log_init(self):
self.log = {}
self.log['loglevel'] = self.conf.get('log','loglevel')
self.log['logname'] = self.conf.get('log','logname')
self.log['interval'] = self.conf.getint('log','interval')
self.log['backupCount'] = self.conf.getint('log','backupCount')
self.log['when'] = self.conf.get('log','when')
self.log['encoding'] = self.conf.get('log','encoding')
def mongodb_init(self):
self.mongodb = {}
self.mongodb['host'] = self.conf.get('mongodb','host').split(',')
self.mongodb['dbname'] = self.conf.get('mongodb','dbname')
self.mongodb['user'] = self.conf.get('mongodb','user')
self.mongodb['password'] = self.conf.get('mongodb','password')
def ldap_init(self):
self.ldap = {}
self.ldap['host'] = self.conf.get('ldap','host')
self.ldap['port'] = int(self.conf.get('ldap','port'))
self.ldap['base_dn'] = self.conf.get('ldap','base_dn')
self.ldap['user_dn'] = self.conf.get('ldap','user_dn')
self.ldap['password'] = self.conf.get('ldap','password')
def redis_init(self):
self.redis = {}
self.redis['host'] = self.conf.get('redis','host')
self.redis['port'] = self.conf.get('redis','port')
self.redis['db'] = self.conf.get('redis','db')
self.redis['password'] = self.conf.get('redis','password')
self.redis['redis_expire'] = self.conf.get('redis','redis_expire')
class Auth():
def __init__(self,conf_path):
self.param = param(conf_path)
# log
self.param.log['logname'] = os.path.join(BASE_DIR,'logs',self.param.log['logname'])
self.logger_init(**self.param.log)
self.mongodb_init(**self.param.mongodb)
self.ldap_init(**self.param.ldap)
self.redis_init(**self.param.redis)
# 初始化部分-------
def logger_init(self,loglevel,logname,interval,backupCount,when,encoding):
logger = logging.getLogger('log')
logger.setLevel(logging.DEBUG)
# 移除掉所有的handler
while logger.hasHandlers():
for i in logger.handlers:
logger.removeHandler(i)
# file log
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
fh = TimedRotatingFileHandler(logname, when=when, interval=interval, backupCount=backupCount,encoding=encoding)
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHandler(fh)
# console log
self.logger = logger
def redis_init(self,host,port,db,password,redis_expire):
self.logger.debug("begin init redis connection")
try:
self.redis_expire = int(redis_expire)
self.redis_cli = redis.Redis(host=host, port=port, db=db,password=password,decode_responses=True)
# self.redis_cli = redis.Redis(host=host, port=port, db=db,password=password)
except Exception as e:
self.logger.error("Failed to connect to redis!")
self.logger.error(str(e))
raise e
self.logger.debug("connect to redis success!")
def ldap_init(self,host, port, user_dn, password, base_dn):
self.logger.debug("begin init ldap connection")
try:
# self.server = Server(host=host, port=port, use_ssl=True)
self.server = Server(host=host, port=port)
self.base_dn = base_dn
self.conn = Connection(
self.server,
user_dn,
password,
check_names=True,
auto_bind=False,
raise_exceptions=True,
)
except Exception as e:
self.logger.error("Failed to connect to ldap!")
self.logger.error(str(e))
raise e
self.logger.debug("connect to ldap success!")
def mongodb_init(self,host,dbname,user,password):
self.logger.debug("begin init mongodb connection")
try:
self.client = pymongo.MongoClient(host)
self.db = self.client[dbname]
self.db.authenticate(user,password)
except Exception as e:
self.logger.error("Failed to connect to MongoDB!")
self.logger.error(str(e))
raise e
self.logger.debug("connect to MongoDB success!")
def auth_by_ldap(self, name, password):
allowed_page = []
try:
self.conn.rebind()
search_res = self.conn.search(
search_base=self.base_dn,
search_filter="(&(objectClass=person)(sAMAccountName={}))".format(name),
search_scope=SUBTREE,
attributes=["objectGUID", "sAMAccountName"],
)
if search_res:
entry = self.conn.response[0]
else:
entry = ""
self.conn.unbind()
except Exception as e:
self.logger.error(f"search res error as: {e}")
search_res = ""
entry = ""
if search_res:
user_dn = entry["dn"]
try:
# 这个connect是通过你的用户名和密码还有上面搜到的入口搜索来查询的
user_conn = Connection(
self.server,
user=user_dn,
password=password,
check_names=True,
auto_bind=False,
raise_exceptions=True,
)
self.logger.debug(str(user_conn))
user_conn.rebind()
user_conn.unbind()
except LDAPInvalidCredentialsResult as e:
self.logger.error(str(e))
error_txt = ""
if "52e" in e.message:
error_txt = "密码不正确!"
elif "775" in e.message:
error_txt = "账号已锁定, 请联系管理员或等待自动解锁!"
elif "533" in e.message:
error_txt = "账号已禁用!"
elif "773" in e.message:
error_txt = "用户登陆前必须修改密码!"
else:
error_txt = "认证失败, 请联系管理员检查该账号!"
self.logger.error(error_txt)
return(error_txt,allowed_page)
# 正确-success 不正确-invalidCredentials
if user_conn.result["description"] == "success":
if "attributes" in entry:
rs = self.db.devopsuser.find_one({'username':name})
if rs:
result = self.db.devopsrole.find_one({'role':rs['role']})
normalpages = result['normalpage']
for np in normalpages:
if np:
if np["permission"] != "":
allowed_page.append(np['nid'])
return('CORRECT',allowed_page)
else:
self.db.devopsuser.insert_one({'username':name,'role':'guest'})
result = self.db.devopsrole.find_one({'role':'guest'})
normalpages = result['normalpage']
for np in normalpages:
if np:
if np["permission"] != "":
allowed_page.append(np['nid'])
return('CORRECT',allowed_page)
else:
self.logger.error('user_conn result data abnormal')
return('user_conn result data abnormal',allowed_page)
else:
self.logger.error('search res faild')
return('search res faild',allowed_page)
def login(self,user_id):
self.user_id = user_id
result = generate_token()
token = result[0]
create_time = result[1]
expire_time = result[2]
if self.user_id == 'guest':
self.redis_cli.set(self.user_id, token)
else:
self.redis_cli.set(self.user_id, token, ex=self.redis_expire)
return token,create_time,expire_time
def check(self, user_id,token):
self.user_id = user_id
if self.redis_cli.exists(self.user_id):
timetoken = self.redis_cli.get(self.user_id)
if timetoken == token:
status = checkout_token(timetoken)
if status == 1:
new_result = generate_token()
new_token = new_result[0]
create_time = new_result[1]
expire_time = new_result[2]
self.redis_cli.set(self.user_id, new_token,ex=self.redis_expire)
return("SUCCESS",new_token,create_time,expire_time)
else:
return ("SESSION-EXPIRED","0","0","0")
else:
return ("INVALID-TOKEN","0","0","0")
else:
return ("FAILURE","0","0","0")
def md5(arg):
md5_pwd = hashlib.md5(bytes('demaxiya', encoding='utf-8'))
md5_pwd.update(bytes(arg, encoding='utf-8'))
return md5_pwd.hexdigest()
def generate_token(aging=3600):
sha1_token = hashlib.sha1(os.urandom(24)).hexdigest()
create_time = int(time.time())
time_group = str(create_time)+":"+str(aging)
time_token = base64.urlsafe_b64encode(time_group.encode("utf-8")).decode("utf-8").strip().lstrip().rstrip('=')
token = sha1_token+time_token
expire_time = create_time + 3600
return token,create_time,expire_time
def checkout_token(token):
result = {}
decode_time = safe_b64decode(token[40:]).decode('utf-8')
decode_split_time = decode_time.split(':')
decode_create_time = decode_split_time[0]
decode_aging_time = decode_split_time[1]
now_time = int(time.time())
difference_time = now_time-int(decode_create_time)
if difference_time > int(decode_aging_time):
result = 0
else:
result = 1
return result
def safe_b64decode(s):
length = len(s) % 4
for i in range(length):
s = s+'='
return base64.b64decode(s)
1.5 flask代码auth_api.py
# -*- coding: UTF-8 -*-
from flask import Flask, abort, request, make_response, jsonify, Response, render_template
from flask_cors import CORS
import json
import auth_manage
import os
import re
app = Flask(__name__)
UM = auth_manage.Auth(auth_manage.CONF_PATH)
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/auth/login', methods=['GET', 'POST'])
def user_login():
info = {}
r_dict = {}
token = "0"
token_expire_time = "0"
if request.method == 'POST':
if request.json:
userid = request.json['userid']
passwd = request.json['passwd']
else:
userid = request.form['userid']
passwd = request.form['passwd']
result = UM.auth_by_ldap(userid, passwd)
if result[0] == "CORRECT":
result_token = UM.login(userid)
token = result_token[0]
token_expire_time = result_token[2]
# r_dict['result'] = result[0]
r_dict['token'] = token
r_dict['page'] = result[1]
r_dict['token_expire_time'] = str(token_expire_time)
r_dict['userid'] = userid
info['status'] = 200
info['result'] = ""
info['data'] = r_dict
return json.dumps(info)
else:
info['status'] = 500
info['result'] = result[0]
info['data'] = ""
return json.dumps(info)
else:
info['status'] = 500
info['result'] = "please use POST request"
info['data'] = ""
return json.dumps(info)
@app.route('/api/auth/tokenauth', methods=['GET', 'POST'])
def token_check():
info = {}
r_dict = {}
if request.method == 'POST':
if request.json:
userid = request.json['userid']
token = request.json['token']
else:
userid = request.form['userid']
token = request.form['token']
result = UM.check(userid,token)
if result[0] == "SUCCESS":
r_dict['token'] = result[1]
r_dict['token_expire_time'] = str(result[3])
r_dict['userid'] = userid
info['status'] = 200
info['result'] = ""
info['data'] = r_dict
return json.dumps(info)
else:
info['status'] = 500
info['result'] = result[0]
info['data'] = ""
return json.dumps(info)
else:
info['status'] = 500
info['result'] = "please use POST request"
info['data'] = ""
return json.dumps(info)
if __name__ == '__main__':
CORS(app, supports_credentials=True)
app.run(host='0.0.0.0', port="10086",debug=True)
2.数据库表结构
2.1 表devopsuser 一条数据
{
"_id" : ObjectId("62bd3f8bacf7357197acf178"),
"role" : "admin",
"username" : "zhangsan"
}
2.2 表devopsrole一条数据
{
"_id" : ObjectId("62bc14c7029deb74beb1b7ba"),
"role" : "admin",
"normalpage" : [
{
"name" : "xxx",
"nid" : "yyy",
"permission" : "W"
},
{
}
]
}