django Ad域認證, 免設置ldap 免用戶名密碼登錄


django ad 認證 免設置ldap  免用戶名密碼登錄

,采用C# windos iis 自帶域身份驗證,提供身份認證接口  可以對接java python php等語言

搭建ad 域認證站點, 可對接django java php 等項目

1.采用iis windos 域認證完成,必須有一台加域的windows 服務器

2.必須了解asp.net mvc 基礎,以及項目發布

3.實現方式  類似微信認證登錄采用oath2方式(第三方系統-->ad 域認證站點-->獲得code-->跳轉會第三方系統-->通過code 獲取當前用戶域信息)

 

實現效果

 

 

項目結構

C# 代碼如下: https://github.com/wangcongxing/OAuthWebApp

生成數據庫遷移:

Enable-Migrations

 

Update-Database -verbose

 using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace OAuthWebApp.Models.Entities
{
    public class appInfo
    {
        public Guid Id { get; set; }

        [StringLength(255)]
        [Display(Name = "應用名稱")]
        [Required(ErrorMessage = "應用名稱")]
        public string appName { get; set; }

        [StringLength(255)]
        [Display(Name = "應用Id")]
        [Required(ErrorMessage = "應用Id")]
        public string appid { get; set; }

        [StringLength(255)]
        [Display(Name = "應用秘鑰")]
        [Required(ErrorMessage = "應用秘鑰")]
        public string appsecret { get; set; }

        [StringLength(255)]
        [Display(Name = "回調地址")]
        [Required(ErrorMessage = "回調地址")]
        public string redirectUrl { get; set; }

        [Display(Name = "創建時間")]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm:ss}")]
        public DateTime? creationTime { get; set; }

        [Display(Name = "修改時間")]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm:ss}")]
        public DateTime? lastWriteTime { get; set; }

        [StringLength(255)]
        [Display(Name = "創建者")]
        public string author { get; set; }

        [StringLength(255)]
        [Display(Name = "修改者")]
        public string editor { get; set; }
    }
}

 

using OAuthWebApp.Models;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace OAuthWebApp.Controllers
{
    public class HomeController : Controller
    {
        ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379");
        //ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("server1:6379,server2:6379");
        [Authorize]
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
        [HttpGet]
        [Authorize]
        public ActionResult authorize(string appid = "", string state = "")
        {
            if (string.IsNullOrEmpty(appid))
                return Json(new { code = 0, msg = "參數有誤,appid不能為空!" }, JsonRequestBehavior.AllowGet);
            using (ApplicationDbContext _context = new ApplicationDbContext())
            {
                var item = _context.appInfos.Where(x => x.appid.Equals(appid)).FirstOrDefault();
                if (item != null)
                {
                    //ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("server1:6379,server2:6379");
                    string config = redis.Configuration;

                    //step-2: Accessing a redis database 連接到Redis數據庫
                    IDatabase db = redis.GetDatabase();

                    //step-3: 通過db使用Redis API (http://redis.io/commands
                    string code = System.Guid.NewGuid().ToString();
                    db.StringSet(code + "_" + item.appid, User.Identity.Name, new TimeSpan(0, 5, 0), When.Always, CommandFlags.None);
                    //string value = string.Empty;
                    //if (db.KeyExists("mykey"))
                    //{
                    //    value = db.StringGet("mykey");
                    // }
                    return Redirect(item.redirectUrl + "?code=" + code + "&state=" + state);
                }
                else
                    return Json(new { code = 0, msg = "參數有誤,appid不存在或已刪除!" }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 獲取用戶信息
        /// </summary>
        /// <param name="code">用戶code</param>
        /// <returns></returns>

        [AllowAnonymous]
        [HttpPost]
        public ActionResult getUserInfo(string appid, string appsecret, string code)
        {
            try
            {
                if (string.IsNullOrEmpty(appid) || string.IsNullOrEmpty(appsecret) || string.IsNullOrEmpty(code))
                    return Json(new { code = -1, msg = "輸入參數不合法!!!" });
                using (ApplicationDbContext _context = new ApplicationDbContext())
                {
                    var item = _context.appInfos.Where(x => x.appid.Equals(appid) && x.appsecret.Equals(appsecret)).FirstOrDefault();
                    if (item == null)
                        return Json(new { code = -2, msg = "appid或appsecret輸入有誤!!!" });
                    code = code + "_" + item.appid;
                    
                    string config = redis.Configuration;
                    //step-2: Accessing a redis database 連接到Redis數據庫
                    IDatabase db = redis.GetDatabase();
                    string um = db.StringGet(code).ToString();
                    db.KeyDelete(code);
                    return Json(new { code = 1, msg = "seccess", um = um });
                }
            }
            catch (Exception ex)
            {
                return Json(new { code = -3, msg = ex.Message + ex.StackTrace });
            }

        }
    }
}

IIS 設置

 

 

 

django 項目  

https://github.com/wangcongxing/OAuthPy

 

主要代碼views.py

from django.http import JsonResponse, HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.core.cache import cache
import requests, uuid
from urllib.parse import quote
from django.contrib.auth.models import Permission, User
from django.contrib import auth

appid = "wxd1fc775bed1421c6"
appsecret = "070dc5f52dac5bef72673c7d0ee21ae3"

authUrl = "http://localhost:9090/Home/authorize/?appid={}".format(appid)
authUserInfo = "http://localhost:9090/Home/getUserInfo"


# Create your views here.
def login(request):
    code = request.GET.get('code', None)
    state = request.GET.get('state', '')
    redirecturl = request.GET.get("redirectUrl", "/")
    result = requests.post(authUserInfo, data={'appid': appid, 'appsecret': appsecret, "code": code})
    resultJson = result.json()

    resultCode = resultJson["code"]
    resultUm = resultJson["um"]
    if resultCode == 1 and resultUm is not '':
        resultUm = str(resultUm).split("\\")[1]
        obj, created = User.objects.update_or_create(
            defaults={'username': resultUm, 'email': resultUm + "@pingan.com.cn", 'password': uuid.uuid1(),
                      'is_staff': True, 'is_active': True},
            username=resultUm)
        if created:
            print("創建成功")
        else:
            print("更新成功")
        '''
        mpPermission = "XXX新增權限" # 使用前需要手動新增在系統授權-->新建權限組
        #分配默認系統權限(對表的增刪改查權限)
        permission = Permission.objects.filter(codename=mpPermission).first()
        if not permission:
            content_type = ContentType.objects.get_for_model(TemplateRequestLog)
            permission = Permission.objects.create(
                codename=mpPermission,
                name='WeChat User Permission',
                content_type=content_type,
            )
        user.user_permissions.add(permission)
        '''
        auth.login(request, obj)
        return redirect(redirecturl + "?state=" + state)
    else:
        print("登錄失敗,請稍后再試!!!")


def index(request):
    if not request.user.is_authenticated:
        return redirect(authUrl)
    return HttpResponse("首頁")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM