首页 > 编程语言 >.Net WebAPI程序集成CAS单点登录-API方式(不使用DotNetCasClient)

.Net WebAPI程序集成CAS单点登录-API方式(不使用DotNetCasClient)

时间:2024-04-23 10:47:06浏览次数:16  
标签:WebAPI false string DotNetCasClient CAS Cas window casResult ticket

以下是ashx一般处理程序的示例,且cas登录单独放到了一个按钮中:

1、登录按钮(js) - 

        console.log("cos登录");

        var originStr = window.location.origin;
        window.location.href = "https://cas.your.com/cas/login?service=" + originStr + "/WebUI/Admin";

2、登出按钮(js) - 

function loginOut() {
        $scope.closeAllTabs();
        var para = { "action": "logout" };  // 原来的登出接口
        $.ajax({
            url: ENV.ApiUrl + "bg_user_login.ashx",
            type: "post",
            data: para,
            dataType: "json",
            success: function (result) {
                if (result.success) {
                    $rootScope.loginflag = false;
                    window.sessionStorage["islogin"] = false;
                    window.sessionStorage["userid"] = "";
                    $rootScope.initIndex();
                    $timeout(function () {
                        if (window.sessionStorage["iscaslogin"] === "true") {  // 是cas登录的用户 走cas登出的逻辑
                            var originStr = window.location.origin;
                            window.location.href = "https://cas.your.com/cas/logout?service=" + originStr + "/WebUI/Admin";
                        }
                        else {  // 不是的走原来的逻辑
                            $state.go("tabs.login");
                        }
                    }, 500);
                }
                else {
                    $.show_warning("提示", result.msg);
                }
            }
        })
    };

3、登录页初始化方法的代码

    function init() {
        //#region CAS 第二版
        var href = window.location.href;

        // http://localhost:8098/WebUI/Admin/?ticket=ST-AS#/tabs/login
        if (href.indexOf("ticket") === -1) {
            // 原登录页面的逻辑
        }
        else {
            console.log("cos登录后自动登录MES");

            // 取ticket
            var ticketStr = href;
            ticketStr = ticketStr.replace("#/tabs/default", "");
            ticketStr = ticketStr.replace("#/tabs/login", "");
            ticketStr = ticketStr.split("ticket=")[1];

            $scope.loading();
            
            var hostName1 = window.location.origin;

            http.isPost = false;
            http.Parameter = {
                action: "login_COS",  // CAS登录接口
                serviceHost: hostName1,
                ticket: ticketStr
            };
            
            http.url = "bg_user_login.ashx";
            return http.go().then(function (response) {
                $scope.hideloading();

                if (response.data.success) {
                    window.sessionStorage["iscaslogin"] = true;
                    window.sessionStorage["islogin"] = true;
                    window.sessionStorage["userid"] = response.data.userid;
                    $rootScope.initIndex();

                    //$state.go("tabs.default");
                    window.location.href = window.location.href.replace("?ticket="+ticketStr,"#/tabs/default");  // ?ticket=ST-AS
                } else {
                    window.sessionStorage["iscaslogin"] = false;
                    window.sessionStorage["islogin"] = false;
                    window.sessionStorage["userid"] = "";
                    alert(response.data.msg);
                }
            }, function (error) {
                window.sessionStorage["iscaslogin"] = false;
                window.sessionStorage["islogin"] = false;
                window.sessionStorage["userid"] = "";
                alert(error.data);
            })
        }
        //#endregion CAS 第二版
    }

    //init();

4、CAS登录接口 - 实现验证CAS凭证

  #region 手搓Cos SSO
  // 获取用户casTicket
  string serviceStr = context.Request.Params["serviceHost"];  // casTicket
  string ticketStr = context.Request.Params["ticket"];  // casTicket
  if (string.IsNullOrEmpty(serviceStr))
  {
      context.Response.Write("{\"msg\":\"登录参数[serviceHost]丢失,请检查网页完整性!\",\"success\":false}");  // 改成自己的逻辑
  }
  else if (string.IsNullOrEmpty(ticketStr))
  {
      context.Response.Write("{\"msg\":\"登录参数[ticket]丢失,请检查网页完整性!\",\"success\":false}");  // 改成自己的逻辑
  }
  else
  {
      // https://cas.your.com/cas/serviceValidate?service=http://localhost:8098/WebUI/Admin&ticket=
      string tokenValid_Url = "https://cas.your.com/cas/serviceValidate?" +
      //"service=http://" + serviceStr + "/WebUI/Admin" +
      "service=" + serviceStr + "/WebUI/Admin" +
      "&ticket=" + ticketStr;

      // 验证casTicket是否有效
      CasAuthorizeHelper.CasResult casResult = CasAuthorizeHelper.IsTokenValid_API(tokenValid_Url);
      if (!casResult.Success)
      {
          context.Response.Write("{\"msg\":\"" + casResult.Msg + "\",\"success\":false}");  // 改成自己的逻辑
      }
      else
      {
          // casTicket有效,存储用户信息到Cookie
          string userId = casResult.Data.ToString();

          DateTime dateCookieExpires = DateTime.Now.AddDays(7);  // 默认7天

          List<Model.User> users = new BLL.User().GetUsersByUserId(userId);
          if (users.Count < 1)
          {
              // MES系统中无该用户的信息,请联系MES系统管理员进行添加!   // 改成自己的逻辑
              context.Response.Write("{\"msg\":\"MES系统中无该用户的信息,请联系MES系统管理员进行添加!\",\"success\":false}");
          }
          else if (users.Count > 1)
          {
              // MES系统中存在多个同工号用户,请联系MES系统管理员处理!   // 改成自己的逻辑
              context.Response.Write("{\"msg\":\"MES系统中存在多个同工号用户,请联系MES系统管理员处理!\",\"success\":false}");
          }
          else if (users[0].IsAble == 0)
          {
              context.Response.Write("{\"msg\":\"用户已被禁用!\",\"success\":false}");  // 改成自己的逻辑
          }
          else
          {
              // 改成自己的逻辑
              FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                 2, users[0].UserId, DateTime.Now, dateCookieExpires, false,
                 new JavaScriptSerializer().Serialize(users[0])  //序列化当前用户对象
              );
              string encTicket = FormsAuthentication.Encrypt(ticket);
              HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
              if (dateCookieExpires != new DateTime(9999, 12, 31))    //不是默认时间才设置过期时间,否则会话cookie(先保留该逻辑)
                  cookie.Expires = dateCookieExpires;
              context.Response.Cookies.Add(cookie);

              context.Response.Write("{\"msg\":\"登录成功!\",\"userid\":\"" + users[0].UserId + "\",\"success\":true}");  // 改成自己的逻辑
          }
      }
  }
  #endregion 手搓Cos SSO

5、CasAuthorizeHelper

//using DotNetCasClient;
using System;
using System.Net.Http;

namespace Test
{
    /// <summary>
    /// Cas SSO帮助类
    /// </summary>
    public static class CasAuthorizeHelper
    {
        #region DotNetCasClient的功能
        ///// <summary>
        ///// 从Cookie获取Cas凭证
        ///// </summary>
        ///// <returns></returns>
        //public static CasAuthenticationTicket GetCasAuthorizeTicket()
        //{
        //    CasAuthenticationTicket casTicket = null;
        //    var ticketCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

        //    if (ticketCookie != null && !string.IsNullOrWhiteSpace(ticketCookie.Value))
        //    {
        //        var ticket = FormsAuthentication.Decrypt(ticketCookie.Value);

        //        if (ticket != null && CasAuthentication.ServiceTicketManager != null)
        //        {
        //            casTicket = CasAuthentication.ServiceTicketManager.GetTicket(ticket.UserData);
        //        }
        //    }
        //    return casTicket;
        //}

        ///// <summary>
        ///// 从Cookie获取Cas凭证
        ///// </summary>
        ///// <param name="request"></param>
        ///// <returns></returns>
        //public static CasAuthenticationTicket GetCasAuthorizeTicket(this HttpRequestBase request)
        //{
        //    CasAuthenticationTicket casTicket = null;
        //    var ticketCookie = request.Cookies[FormsAuthentication.FormsCookieName];

        //    if (ticketCookie != null && !string.IsNullOrWhiteSpace(ticketCookie.Value))
        //    {
        //        var ticket = FormsAuthentication.Decrypt(ticketCookie.Value);
        //        if (ticket != null && CasAuthentication.ServiceTicketManager != null)
        //        {
        //            casTicket = CasAuthentication.ServiceTicketManager.GetTicket(ticket.UserData);

        //            //记录登录用户Ticket消息明细信息
        //            //LogUtil.Info("ticket:{0},获取CAS用户认证信息:{1}", ticket.UserData, SerializerUtil.ToJson(casTicket));
        //        }
        //    }
        //    return casTicket;
        //}

        ///// <summary>
        ///// 验证Cas凭证是否有效
        ///// </summary>
        ///// <param name="ticket"></param>
        ///// <returns></returns>
        //public static bool IsTokenValid(CasAuthenticationTicket ticket)
        //{
        //    if (ticket == null) return false;
        //    return CasAuthentication.ServiceTicketManager.VerifyClientTicket(ticket);
        //}

        ///// <summary>
        ///// 清理Cas凭证
        ///// </summary>
        //public static void ClearAuthCookie()
        //{
        //    CasAuthentication.ClearAuthCookie();
        //}
        #endregion DotNetCasClient的功能

        #region 手搓Cas SSO
        /// <summary>
        /// 验证Cas凭证是否有效
        /// </summary>
        /// <param name="tokenValid_Url">验证凭证的地址</param>
        /// <returns></returns>
        public static CasAuthorizeHelper.CasResult IsTokenValid_API(string tokenValid_Url)
        {
            CasResult casResult = new CasResult();

            try
            {
                Uri uri = new Uri(tokenValid_Url);

                HttpResponseMessage response = new HttpClient().GetAsync(uri).Result;
                if (response.IsSuccessStatusCode)  // 调用成功
                {
                    string content = response.Content.ReadAsStringAsync().Result;

                    // 正常:
                    ////<cas:serviceResponse xmlns:cas="1">
                    ////<cas:authenticationSuccess>
                    ////<cas:user></cas:user>
                    ////</cas:authenticationSuccess>
                    ////</cas:serviceResponse>
                    // null:
                    ////<cas:serviceResponse xmlns:cas="1">
                    ////  <cas:authenticationFailure code="INVALID_TICKET">未能够识别出目标 'SVAS'票根</cas:authenticationFailure>
                    ////</cas:serviceResponse>
                    if (string.IsNullOrEmpty(content))
                    {
                        // 凭证验证异常
                        casResult.Success = false;
                        casResult.Msg = string.Concat("通过API校验Cas凭证失败!报文为空!");
                    }

                    string[] contentLine = content.Split('\n');

                    if (contentLine.Length<3)
                    {
                        // 凭证验证异常
                        casResult.Success = false;
                        casResult.Msg = string.Concat("通过API校验Cas凭证失败!报文异常!"+ content);
                    }

                    if (contentLine[1].Contains("authenticationFailure") && contentLine[1].Contains("未能够识别出目标"))
                    {
                        // 凭证无效
                        casResult.Success = false;
                        casResult.Msg = "CAS凭证无效!请刷新页面重新登录!";
                    }
                    else if (contentLine[1].Contains("authenticationSuccess"))
                    {
                        // 凭证有效
                        casResult.Success = true;

                        string userNameStr = contentLine[2];
                        userNameStr = userNameStr.Replace("<cas:user>", "");
                        userNameStr = userNameStr.Replace("</cas:user>", "");
                        casResult.Data = userNameStr.Trim();
                    }
                    else
                    {
                        // 凭证验证异常
                        casResult.Success = false;
                        casResult.Msg = string.Concat("通过API校验Cas凭证失败!报文异常!" + content);
                    }
                }
                else
                {
                    casResult.Success = false;

                    string conStr = response.Content.ReadAsStringAsync()?.Result ?? string.Empty;

                    casResult.Msg = string.Concat("通过API校验Cas凭证失败![", response.StatusCode.ToString(), "]", conStr);
                }
            }
            catch (Exception ex)
            {
                //Debug.WriteLine(@"\tERROR {0}", ex.Message);

                casResult.Success = false;
                casResult.Msg = "通过API校验Cas凭证失败!" + ex.Message;
            }

            return casResult;
        }

        /// <summary>
        /// Cas用方法结果类
        /// </summary>
        public class CasResult
        {
            public bool Success { get; set; }

            public string Msg { get; set; } = string.Empty;

            public object Data { get; set; }

            public object Obj1 { get; set; }
        }
        #endregion 手搓Cas
    }
}

 

标签:WebAPI,false,string,DotNetCasClient,CAS,Cas,window,casResult,ticket
From: https://www.cnblogs.com/qq2806933146xiaobai/p/18152302

相关文章

  • Java switch() case中的switch可用的数据类型 byte,shor,int ,string ,char不能是long
    Javaswitch()case中的switch可用的数据类型   byte,shor,int,string,char1.swtich()里面必须是int和enum--即枚举类型。2.short、char或者byte他会自动转换为int的。。3.long不能自动转换为int,因为long比int范围大..可能会丢失精度..4.java把string也'转化'成int了,用......
  • linux系统是未来_大小写敏感_case_sensitive_编程原生态
    修改py文件......
  • Case表达式
    在发现结果为真的WHEN子句时,CASE表达式的真假值判断会终止,剩余的WHEN子句会被忽略:CASEWHENcol_1IN('a','b')THEN'第一'WHENcol_1IN('a')THEN'第二'ELSE'其他'END注意:统一各分支返回的数据类型.记得写end.写else子句的习惯,否则执行结果默认处理为null......
  • opencascade官网文档学习之OCCT-Shape healing (3)分析 TopoDS_Shape
    Analysis分析Analysisofshapevalidity形状有效性分析ShapeAnalysis软件包提供了用于分析拓扑形状的工具。在执行修复工具之前,没有必要通过这些工具检查形状,因为这些工具用于在修复工具内部执行修复之前的分析。但是,如果您愿意,这些工具可以独立于修复工具用于检测某些形状问......
  • IIS 部署WEBAPI
    ASP.NETCore不再是由IIS工作进程(w3wp.exe)托管,而是使用自托管Web服务器(Kestrel)运行,IIS则是作为反向代理的角色转发请求到Kestrel不同端口的ASP.NETCore程序中,随后就将接收到的请求推送至中间件管道中去,处理完你的请求和相关业务逻辑之后再将HTTP响应数据重新回写到IIS中,最终转达......
  • webapi路由
    ShopController.cspublicclassShopController:ApiControllerBase{[Route("api/v1/shop/watermark")][HttpPost]publicApiResultwatermark(dynamicvalue){//watermark/shopname.txtA......
  • casl 同构授权js 框架
    casl同构授权js框架,提供了web前端以及后端的集成支持(使用相同的api)包含的特性多功能 灵活的基于subject以及属性的授权处理同构 同时支持前端以及后端类型安全 基于ts开发小巧 压缩之后只有6kb声明式的 基于声明式的可以灵活的进行规则的共享,包含了ui,api以及微......
  • 一文读懂.NET WebAPI中FromRoute、FromQuery、FromBody的关键角色与用法
    .NETWebAPI作为一种构建RESTful服务的强大工具,为开发者提供了便捷的方式来定义、处理HTTP请求并返回响应。在设计API接口时,正确地接收和解析客户端发送的数据至关重要。.NETWebAPI提供了一系列特性,如[FromRoute]、[FromQuery]和[FromBody],用于指示控制器方法应如何从不同的请求......
  • UnSafe CAS 操作
    UnSafe目录UnSafe乐观锁compareAndSwapIntgetObjectVolatileputObjectobjectFieldOffset乐观锁CAS原子操作compareAndSwapInt从var1对象的起始指针移动var2位,如果该位置上存储的值等于var4,那么将该值修改成var5var1比较对象var2指针偏移量var4条件值var5新值......
  • ABP -Vnext框架一步一步入门落地教程——使用ABP -Vnext创建一个WEBAPI接口(二)
    人生需要指引,而复制是成功最快的方式,兄弟们让我们发车吧————代码大牛ljy开发主题:何谓开发应用服务端在官方开发教程这一段的内容叫做开发应用服务端,作为现在前后端分离的开发模式来说,一个应用就分为前端页面框架和后端API,页面框架调用WEBAPI实现业务就完事了。所以咱们今天......