tnblog
首页
视频
资源
登录

.net MVC IIS 无需Secret 的Microsoft登录

1416人阅读 2024/9/13 13:28 总访问:3660447 评论:0 收藏:0 手机
分类: .net后台框架

.netcore

IIS 无需Secret 的Microsoft登录

核心代码

  1. public static class FMicsorftLoginHepler
  2. {
  3. // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
  4. // The Client ID (a.k.a. Application ID) is used by the application to uniquely identify itself to Azure AD
  5. static string clientId = System.Configuration.ConfigurationManager.AppSettings["ida:ClientId"];
  6. // RedirectUri is the URL where the user will be redirected to after they sign in
  7. static string redirectUrl = System.Configuration.ConfigurationManager.AppSettings["ida:RedirectUrl"];
  8. // Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
  9. static string tenant = System.Configuration.ConfigurationManager.AppSettings["ida:Tenant"];
  10. // Authority is the URL for authority, composed by Azure Active Directory endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com)
  11. static string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["ida:Authority"], tenant);
  12. /// <summary>
  13. /// Configure OWIN to use OpenIdConnect
  14. /// </summary>
  15. /// <param name="app"></param>
  16. public static void Configuration(this IAppBuilder app)
  17. {
  18. app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
  19. app.UseKentorOwinCookieSaver();
  20. app.UseCookieAuthentication(new CookieAuthenticationOptions
  21. {
  22. CookieManager = new SystemWebCookieManager(),
  23. CookieName = "MaterialWizardWeb_AuthCookie"
  24. });
  25. app.UseOpenIdConnectAuthentication(
  26. new OpenIdConnectAuthenticationOptions
  27. {
  28. // Sets the ClientId, authority, RedirectUri as obtained from web.config
  29. ClientId = clientId,
  30. Authority = authority,
  31. //RedirectUri = redirectUrl,
  32. // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
  33. PostLogoutRedirectUri = redirectUrl,
  34. //Scope is the requested scope: OpenIdConnectScopes.OpenIdProfileis equivalent to the string 'openid profile': in the consent screen, this will result in 'Sign you in and read your profile'
  35. Scope = OpenIdConnectScope.OpenIdProfile,
  36. // ResponseType is set to request the id_token - which contains basic information about the signed-in user
  37. ResponseType = OpenIdConnectResponseType.IdToken,
  38. // ValidateIssuer set to false to allow work accounts from any organization to sign in to your application
  39. // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name or Id (example: contoso.onmicrosoft.com)
  40. // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
  41. TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = false },
  42. // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
  43. Notifications = new OpenIdConnectAuthenticationNotifications
  44. {
  45. SecurityTokenValidated = OnSecurityTokenValidated,
  46. RedirectToIdentityProvider = OnRedirectToIdentityProvider,
  47. AuthenticationFailed = OnAuthenticationFailed
  48. }
  49. }
  50. );
  51. }
  52. private static Task OnSecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
  53. {
  54. ClaimsIdentity claimsId = context.AuthenticationTicket.Identity;
  55. //email dell'utente
  56. string upn = context.AuthenticationTicket.Identity.Name;
  57. string oerlikonAlias = upn.Substring(0, upn.IndexOf('@'));
  58. using (FinderContext dal = new FinderContext())
  59. {
  60. var userobj = dal.Users.FirstOrDefault(x => x.Short_Key == oerlikonAlias);
  61. if (userobj == null)
  62. {
  63. //Save a new one
  64. userobj = new User
  65. {
  66. Keyed_Name = upn,
  67. Short_Key = oerlikonAlias
  68. };
  69. dal.Users.Add(userobj);
  70. dal.SaveChanges();
  71. }
  72. var roleanduser = dal.RequestPathPermissionRoleAssociatedUser.FirstOrDefault(x => x.User_ID == userobj.ID);
  73. if (roleanduser == null)
  74. {
  75. var baserole = dal.RequestPathPermissionRoles.FirstOrDefault(x => x.Default);
  76. if (baserole != null)
  77. {
  78. roleanduser = new RequestPathPermissionRoleAssociatedUser()
  79. {
  80. Role_ID = baserole.ID,
  81. User_ID = userobj.ID
  82. };
  83. roleanduser.UpdateTime();
  84. dal.RequestPathPermissionRoleAssociatedUser.Add(roleanduser);
  85. dal.SaveChanges();
  86. }
  87. }
  88. else
  89. {
  90. roleanduser.UpdateTime();
  91. dal.SaveChanges();
  92. }
  93. claimsId.AddClaim(new Claim(ClaimTypes.Role, roleanduser.Role_ID.ToString()));
  94. }
  95. claimsId.AddClaim(new Claim(ClaimTypes.Name, oerlikonAlias));
  96. claimsId.AddClaim(new Claim(ClaimTypes.Email, upn));
  97. return Task.FromResult(0);
  98. }
  99. private static Task OnRedirectToIdentityProvider(RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> ctx)
  100. {
  101. bool isAjaxRequest = (ctx.Request.Headers != null && ctx.Request.Headers["X-Requested-With"] == "XMLHttpRequest");
  102. if (isAjaxRequest)
  103. {
  104. ctx.Response.Headers.Remove("Set-Cookie");
  105. ctx.State = NotificationResultState.HandledResponse;
  106. }
  107. return Task.FromResult(0);
  108. }
  109. /// <summary>
  110. /// Handle failed authentication requests by redirecting the user to the home page with an error in the query string
  111. /// </summary>
  112. /// <param name="context"></param>
  113. /// <returns></returns>
  114. private static Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
  115. {
  116. context.HandleResponse();
  117. context.Response.Redirect(GetErrorUrl(context.Exception.Message));
  118. return Task.FromResult(0);
  119. }
  120. private static string GetErrorUrl(string errormessage)
  121. {
  122. return $"{redirectUrl}/Home/Error?errormessage={errormessage}";
  123. }
  124. }


Startup中启用。

  1. [assembly: OwinStartup(typeof(INFinderDevExpress.Startup))]
  2. namespace INFinderDevExpress
  3. {
  4. public class Startup
  5. {
  6. public void Configuration(IAppBuilder app)
  7. {
  8. app.Configuration();
  9. app.MapSignalR();
  10. }
  11. }
  12. }

同时支持windows登录和微软登录代码如下

  1. public class WindowsLoginHelper
  2. {
  3. public (bool, WindowsIdentity) Login(string UserName, string Password, string Domain)
  4. {
  5. string text1 = Domain.Trim();
  6. string text2 = UserName.Trim();
  7. text2 = text2.Replace("/", @"/");
  8. int num1 = text2.IndexOf("//");
  9. if (num1 != -1)
  10. {
  11. text1 = text2.Substring(0, num1);
  12. text2 = text2.Substring(num1 + 1);
  13. }
  14. else
  15. {
  16. num1 = text2.IndexOf('@');
  17. if (num1 != -1)
  18. {
  19. text1 = text2.Substring(num1 + 1);
  20. text2 = text2.Substring(0, num1);
  21. }
  22. }
  23. return this.authenticateUser(text2, Password.Trim(), text1);
  24. }
  25. private (bool, WindowsIdentity) authenticateUser(string UserName, string Password, string Domain)
  26. {
  27. bool flag1 = false;
  28. try
  29. {
  30. int num1;
  31. IntPtr ptr1;
  32. if (!WindowsLoginHelper.LogonUser(UserName, Domain, Password, 2, 0, out num1))
  33. {
  34. return (flag1,null);
  35. }
  36. ptr1 = new IntPtr(num1);
  37. WindowsIdentity identity1 = new WindowsIdentity(ptr1);
  38. WindowsPrincipal principal1 = new WindowsPrincipal(identity1);
  39. HttpContext.Current.User = principal1;
  40. FormsAuthentication.SetAuthCookie(principal1.Identity.Name,false);
  41. //FormsAuthentication.RedirectFromLoginPage(UserName, false);
  42. flag1 = true;
  43. return (flag1, identity1);
  44. }
  45. catch (Exception ex)
  46. {
  47. }
  48. return (flag1, null);
  49. }
  50. public (bool, string) Login2(string UserName, string Password, string Domain)
  51. {
  52. string text1 = Domain.Trim();
  53. string text2 = UserName.Trim();
  54. text2 = text2.Replace("/", @"/");
  55. int num1 = text2.IndexOf("//");
  56. if (num1 != -1)
  57. {
  58. text1 = text2.Substring(0, num1);
  59. text2 = text2.Substring(num1 + 1);
  60. }
  61. else
  62. {
  63. num1 = text2.IndexOf('@');
  64. if (num1 != -1)
  65. {
  66. text1 = text2.Substring(num1 + 1);
  67. text2 = text2.Substring(0, num1);
  68. }
  69. }
  70. return this.authenticateUser2(text2, Password.Trim(), text1);
  71. }
  72. private (bool, string) authenticateUser2(string UserName, string Password, string Domain)
  73. {
  74. bool flag1 = false;
  75. try
  76. {
  77. int num1;
  78. IntPtr ptr1;
  79. if (!WindowsLoginHelper.LogonUser(UserName, Domain, Password, 2, 0, out num1))
  80. {
  81. return (flag1, null);
  82. }
  83. ptr1 = new IntPtr(num1);
  84. WindowsIdentity identity1 = new WindowsIdentity(ptr1);
  85. WindowsPrincipal principal1 = new WindowsPrincipal(identity1);
  86. HttpContext.Current.User = principal1;
  87. FormsAuthentication.SetAuthCookie(principal1.Identity.Name, false);
  88. //FormsAuthentication.RedirectFromLoginPage(UserName, false);
  89. flag1 = true;
  90. return (flag1, principal1.Identity.Name);
  91. }
  92. catch (Exception ex)
  93. {
  94. }
  95. return (flag1, null);
  96. }
  97. [DllImport("advapi32.dll")]
  98. public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out int phToken);
  99. }


SelectLoginPage是选择登录的页面。

  1. /// <summary>
  2. /// Send an OpenID Connect sign-in request.
  3. /// Alternatively, you can just decorate the SignIn method with the [Authorize] attribute
  4. /// </summary>
  5. public void SignIn()
  6. {
  7. if (!Request.IsAuthenticated)
  8. {
  9. HttpContext.GetOwinContext().Authentication.Challenge(
  10. new AuthenticationProperties { RedirectUri = System.Configuration.ConfigurationManager.AppSettings["ida:RedirectUrl"] },
  11. OpenIdConnectAuthenticationDefaults.AuthenticationType);
  12. }
  13. }
  14. [AllowAnonymous]
  15. [HttpPost]
  16. public ActionResult WindowsLogin(RequestWindowsLoginModelDto dto)
  17. {
  18. var username = dto.username;
  19. var password = dto.password;
  20. var domain = "INDOM";
  21. WindowsLoginHelper loginHelper = new WindowsLoginHelper();
  22. var (resultpd,resultstr) = loginHelper.Login2(username, password, domain);
  23. // 如果失败重新登录
  24. if (!resultpd)
  25. {
  26. return RedirectToAction("SelectLoginPage", "Home");
  27. }
  28. var claims = new List<System.Security.Claims.Claim>()
  29. {
  30. new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name,resultstr),
  31. new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role,"WindowsRole")
  32. };
  33. var claimsidentity = new System.Security.Claims.ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationType);
  34. var authmanager = HttpContext.GetOwinContext().Authentication;
  35. authmanager.SignIn(claimsidentity);
  36. return RedirectToAction("Index", "Home");
  37. }
  38. public ActionResult SelectLoginPage()
  39. {
  40. return View();
  41. }
  1. public class RequestWindowsLoginModelDto
  2. {
  3. public string username { get; set; }
  4. public string password { get; set; }
  5. }


在filter中可以进行是否授权的判断。

  1. filterContext.HttpContext.Request.IsAuthenticated

欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739

评价
这一世以无限游戏为使命!
排名
2
文章
657
粉丝
44
评论
93
docker中Sware集群与service
尘叶心繁 : 想学呀!我教你呀
一个bug让程序员走上法庭 索赔金额达400亿日元
叼着奶瓶逛酒吧 : 所以说做程序员也要懂点法律知识
.net core 塑形资源
剑轩 : 收藏收藏
映射AutoMapper
剑轩 : 好是好,这个对效率影响大不大哇,效率高不高
ASP.NET Core 服务注册生命周期
剑轩 : http://www.tnblog.net/aojiancc2/article/details/167
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术