This article gives you an overview of Logon triggers in SQL Server and its usage to control SQL Server authentication.

本文为您概述了SQL Server中的登录触发器及其在控制SQL Server身份验证中的用法。

介绍 (Introduction)

SQL Server provides Windows and SQL authentication method to connect using SSMS or client applications. Security is always a primary focus for DBA, especially in the production environment. We can control database access by providing minimum and appropriate permissions for user work. We can use GRANT or DENY statements in SQL Server to give appropriate task permissions for the individual user.

SQL Server提供Windows和SQL身份验证方法,以使用SSMS或客户端应用程序进行连接。 安全始终是DBA的主要重点,尤其是在生产环境中。 我们可以通过为用户工作提供最小和适当的权限来控制数据库访问。 我们可以在SQL Server中使用GRANT或DENY语句为单个用户赋予适当的任务权限。

SQL Server has the following triggers:

SQL Server具有以下触发器:

  • Data Definition language triggers or DDL riggers 数据定义语言触发器或DDL绑定器
  • Data Manipulation Language or DML triggers 数据处理语言或DML触发器
  • Common language runtime or CLR triggers 公共语言运行时或CLR触发器
  • Logon triggers 登录触发器

In this article, we will explore Logon triggers in SQL Server and its usage.

在本文中,我们将探讨SQL Server中的登录触发器及其用法。

SQL Server中的登录触发器 (Logon triggers in SQL Server)

Triggers is a database code that gets executed in case of a precisely defined event. We can use logon triggers to control the SQL login security. SQL Server automatically executes the logon triggers once a logon event occurs. It gets executed before a user session is established and authentication is successful.

触发器是在精确定义的事件下执行的数据库代码。 我们可以使用登录触发器来控制SQL登录安全性。 登录事件发生后,SQL Server将自动执行登录触发器。 它在建立用户会话和身份验证成功之前被执行。

We use two terms for a database successful connection in any database.

对于任何数据库中的数据库成功连接,我们使用两个术语。

  • Authentication: We specify a username and password to connect using SQL authentication. It is a validation of the user’s credentials 身份验证 :我们指定用户名和密码以使用SQL身份验证进行连接。 这是对用户凭据的验证
  • Authorization: It is a permission that allows you to do specific tasks. You may be authorized to have full access to a specific database but not authorized to make any changes at the instance level 授权:允许您执行特定任务的权限。 您可能被授权拥有对特定数据库的完全访问权限,但无权在实例级别进行任何更改

If any user is unable to authenticate to SQL Server (wrong credentials), SQL Server does not execute the logon triggers. SQL Server starts an implicit transaction before the logon triggers fires. It is independent of any user transaction. In the case of the logon trigger, the transaction count is 1. In case SQL returns an exception, its value sets to zero. It fails the implicit transaction, and the user session is not established. User connection also fails in case of the error having severity more significant than 20 inside the trigger.

如果任何用户无法通过SQL Server进行身份验证(使用错误的凭据),则SQL Server不会执行登录触发器。 SQL Server在登录触发器触发之前启动隐式事务。 它独立于任何用户事务。 对于登录触发器,事务计数为1。如果SQL返回异常,则其值设置为零。 它使隐式事务失败,并且未建立用户会话。 如果错误在触发器内部的严重性大于20,则用户连接也会失败。

Let’s explore the use of cases of logon triggers using examples.

让我们使用示例探讨登录触发器的用例。

使用SQL Server中的登录触发器限制SQL Server连接的总数 (Restrict the total number of SQL Server connections using Logon triggers in SQL Server)

Sometimes, we require to restrict the total number of SQL Server connections. Too many connections might cause performance issues so we can use logon triggers to solve this purpose. By default, SQL Server allows an unlimited number of concurrent connections to SQL Server. You can verify it in the SQL Server properties.

有时,我们需要限制SQL Server连接的总数。 太多的连接可能会导致性能问题,因此我们可以使用登录触发器来解决此目的。 默认情况下,SQL Server允许无限数量的并发连接到SQL Server。 您可以在SQL Server属性中进行验证。

We can use the DMV sys.dm_exec_connections to differentiate the system and user process. In the below query, we create a logon trigger to allow a maximum of three connections. You can see, we use a clause FOR LOGON for the logon triggers.

我们可以使用DMV sys.dm_exec_connections来区分系统和用户进程。 在下面的查询中,我们创建一个登录触发器,以允许最多三个连接。 可以看到,我们在登录触发器中使用了FOR LOGON子句。

  • Note: Do not execute the below code in the production environment. You should limit the maximum connection only if required and after checking your environment requirements
  • 注意:不要在生产环境中执行以下代码。 仅在需要时并在检查环境要求后才应限制最大连接
CREATE TRIGGER tr_LimitMaximumLogins ON ALL SERVER
FOR LOGON
ASBEGINIF(SELECT COUNT(*)FROM sys.dm_exec_sessionsWHERE is_user_process = 1) > 3BEGINPRINT 'This SQL instance allows maximum than three, Connection is Failed';ROLLBACK;END;END;

Once the trigger is created, make three user connections and verify it using DMV.

创建触发器后,进行三个用户连接并使用DMV进行验证。

SELECT COUNT(*) as [CurrentConnected] FROM sys.dm_exec_sessions
WHERE is_user_process = 1

Now, if you try to make an additional connection, you get the Error:17892, and it gives you a message that the user cannot connect due to trigger execution.

现在,如果您尝试建立其他连接,则会收到错误:17892,并且它会提示您用户由于触发执行而无法连接。

Before we move forward, drop this logon trigger using the following query.

在继续之前,请使用以下查询删除此登录触发器。

Drop trigger tr_LimitMaximumLogins ON ALL SERVER

限制用户SQL Server连接数 (Put a Limit on the number of SQL Server connections from a user)

We may face this issue frequently where the user opens many connections and execute the query in all of them. It increases the total number of connections as well as might cause performance issues. We do not want to limit the total number of connections. We require that a user should not be allowed to open more than two connections simultaneously.

当用户打开许多连接并在所有连接中执行查询时,我们可能会经常遇到此问题。 它增加了连接总数,并可能导致性能问题。 我们不想限制连接总数。 我们要求不允许用户同时打开两个以上的连接。

SQL Server DMV sys.dm_exec_connections has a column to give the original login name.

SQL Server DMV sys.dm_exec_connections的一栏中提供了原始登录名。

SELECT is_user_process, original_login_name, *
FROM sys.dm_exec_sessions
where is_user_process=1
ORDER BY login_time DESC

We can use ORIGINAL_LOGIN() to check the login from which the user is connected to SQL Server.

我们可以使用ORIGINAL_LOGIN()来检查用户从中登录到SQL Server的登录名。

In the below trigger definition, we put a check on the maximum connected connections for the user process. We can note that each user can have a maximum of two simultaneous connections using this logon trigger.

在下面的触发器定义中,我们检查了用户进程的最大连接数。 我们可以注意到,使用此登录触发器,每个用户最多可以同时有两个连接。

CREATE TRIGGER tr_LimitUserConnection ON ALL SERVERFOR LOGONASBEGINDECLARE @login NVARCHAR(100);SET @login = ORIGINAL_LOGIN();IF(SELECT COUNT(*)FROM sys.dm_exec_sessionsWHERE is_user_process = 1AND original_login_name = @login) > 2BEGINPRINT 'You are not allowed to have more than two connections- Login by ' + @login + ' Failed';ROLLBACK;END;END;

We get the same error message once a user tries to make a third connection.

用户尝试建立第三次连接后,我们会收到相同的错误消息。

We can verify here that each user can have two simultaneous connections.

我们可以在此处验证每个用户可以同时拥有两个连接。

You can also find an entry in SQL Server logs that depicts that you are not allowed to have more than two connections. It is the custom message we specified in the logon trigger.

您还可以在SQL Server日志中找到一个条目,该条目描述不允许您拥有两个以上的连接。 这是我们在登录触发器中指定的自定义消息。

允许具有特定客户端应用程序的用户使用SQL Server中的登录触发器与SQL Server连接进行连接 (Allow users with the specific client application to connect with SQL Server connections using Logon triggers in SQL Server)

Suppose we do not want users to connect with SQL Server from other than SSMS. We can use the APP_NAME() function to check user client application and define logic in logon trigger to allow connection or not.

假设我们不希望用户通过SSMS以外的其他方式与SQL Server连接。 我们可以使用APP_NAME()函数检查用户客户端应用程序,并在登录触发器中定义逻辑以允许或不允许连接。

--Drop trigger tr_LimitUserApp ON ALL SERVERCREATE TRIGGER tr_LimitUserApp ON ALL SERVERFOR LOGONASBEGINDECLARE @app NVARCHAR(100);SET @app = APP_NAME();IF(@App LIKE 'SQL Server Management Studio')BEGINRETURN;END;ELSEPRINT 'You are not allowed to connect from ' + @app + 'Status:- Failed';ROLLBACK;END;

Here, we can see it disallowed connection from the SQLCMD because we only allowed SSMS to make a connection.

在这里,我们可以看到它不允许来自SQLCMD的连接,因为我们只允许SSMS建立连接。

You can see the custom message in the error log. This custom message helps you to identify the connection issues quickly.

您可以在错误日志中看到自定义消息。 此自定义消息可帮助您快速识别连接问题。

在SQL Server中使用登录触发器在特定时间范围内禁止用户连接 (Disallow user connection at a specific time frame using Logon triggers in SQL Server)

Suppose we do not want any user to connect to the SQL database during night hours. We might be doing database maintenance tasks in these hours. Logon triggers can help in fulfilling this requirement.

假设我们不希望任何用户在夜间连接到SQL数据库。 我们可能会在这几个小时内执行数据库维护任务。 登录触发器可以帮助满足此要求。

Suppose I have a Demo user with [dbcreator] server-level permissions.

假设我有一个具有[dbcreator]服务器级权限的Demo用户。

CREATE LOGIN demo WITH PASSWORD = 'test@123';
GO
ALTER SERVER ROLE [dbcreator] ADD MEMBER [demo];
GO

For the demonstration purposes, let’s say this user works in after office hours. We want the user to login between 6 PM and 6 AM. Outside these hours, SQL Server should restrict access for this specific user.

出于演示目的,假设该用户在下班时间上班。 我们希望用户在下午6点至早上6点之间登录。 在这些时间以外,SQL Server应该限制该特定用户的访问。

In the below trigger script, we use ORIGINIAL_LOGIN() function to validate the user and SQL DATEPART function to check user login hours. If both the conditions met, the user [demo] can log in to SQL Server else he gets an error message.

在下面的触发脚本中,我们使用ORIGINIAL_LOGIN()函数验证用户,并使用SQL DATEPART函数检查用户登录时间。 如果两个条件都满足,则用户[demo]可以登录SQL Server,否则将收到错误消息。

CREATE TRIGGER tr_LimitUserTime ON ALL SERVER
FOR LOGON
ASBEGINIF((ORIGINAL_LOGIN() = 'Demo')AND (DATEPART(Hour, GETDATE()) BETWEEN 06 AND 18))ROLLBACK;END;

In the above trigger code, we do not specify a PRINT statement to log a custom message in the error log. You can see it logs a generic message in the error log, so I recommend using a custom message to give you specific details.

在上面的触发代码中,我们没有指定PRINT语句在错误日志中记录自定义消息。 您可以看到它在错误日志中记录了一条通用消息,因此我建议使用自定义消息为您提供特定的详细信息。

使用登录触发器进行登录审核 (Login Auditing using Logon Triggers)

Sometimes, we require to audit SQL Server instances login events. We have the option to do login auditing in SQL Server properties.

有时,我们需要审核SQL Server实例的登录事件。 我们可以选择在SQL Server属性中执行登录审核。

Once you enable login audit, it logs entries in the SQL Server error log for failed and successful login based on the configured option.

启用登录审核后,它将基于配置的选项在SQL Server错误日志中记录失败和成功登录的条目。

It may fill up the error logs quickly, and you might miss checking useful login events. You can also use logon triggers in SQL Server for this audit purpose.

它可能会Swift填充错误日志,并且您可能会错过检查有用的登录事件的机会。 您也可以将SQL Server中的登录触发器用于此审核目的。

For this purpose, create a SQL table to hold audit events.

为此,创建一个SQL表来保存审核事件。

CREATE TABLE Audit_Logins(Login_Name NVARCHAR(256), Login_Time DATETIME, Host_Name  NVARCHAR(200));

Next, create the logon trigger with the following script.

接下来,使用以下脚本创建登录触发器。

CREATE TRIGGER TR_Audit_logins ON ALL SERVER
FOR LOGON
ASBEGININSERT INTO sqlshack.dbo.Audit_LoginsSELECT ORIGINAL_LOGIN(), GETDATE(), EVENTDATA().value('(/EVENT_INSTANCE/ClientHost)[1]', 'NVARCHAR(128)');END;

In the above code, we use EVENTDATA() to capture the hostnames. It is an XML document in a DDL trigger to capture useful schema details. You can refer to Microsoft docs for more details on eventdata().

在上面的代码中,我们使用EVENTDATA()捕获主机名。 它是DDL触发器中的XML文档,用于捕获有用的架构详细信息。 您可以参考Microsoft文档以获取有关eventdata()的更多详细信息。

Now, query the Audit_Logins table, and you can see login event records getting stored.

现在,查询Audit_Logins表,您可以看到存储的登录事件记录。

禁用SQL Server中的所有登录触发器 (Disable all logon triggers in SQL Server)

You can either plan to remove the logon triggers or disable them if no required. We can use the following script to disable all logon triggers in SQL instance.

您可以计划删除登录触发器,或者在不需要时将其禁用。 我们可以使用以下脚本来禁用SQL实例中的所有登录触发器。

DISABLE TRIGGER ALL ON ALL SERVER

有关SQL Server中的登录触发器的有用要点 (Useful points about Logon triggers in SQL Server)

  • Use the logon triggers with due intelligence. You can block all SQL connections if they are not configured correctly 适当地使用登录触发器。 如果未正确配置所有SQL连接,则可以阻止它们
  • Always perform the demonstration in your test environment 始终在测试环境中进行演示
  • Do not create multiple logon triggers and configure only as per your requirement 不要创建多个登录触发器并仅根据您的要求进行配置
  • We should always be ready with a rollback plan in case you accidentally block all SQL connections 如果您不小心阻塞了所有SQL连接,我们应该始终准备好回滚计划

结论 (Conclusion)

In this article, we explored useful logon triggers in SQL Server. You can use it to restrict SQL logins as per your requirement. It can be useful for audit purposes as well. You should explore these triggers and implement them with proper testing if required.

在本文中,我们探讨了SQL Server中有用的登录触发器。 您可以根据需要使用它来限制SQ​​L登录。 它也可以用于审核目的。 您应该探索这些触发器,并在需要时通过适当的测试来实现它们。

翻译自: https://www.sqlshack.com/an-overview-of-logon-triggers-in-sql-server/

SQL Server中的登录触发器概述相关推荐

  1. SQL Server中的计算列概述

    In this article, we will explore computed columns in SQL Server and their configurations. 在本文中,我们将探讨 ...

  2. sql 会话_在特定会话中禁用SQL Server中的触发器

    sql 会话 This article will focus on the various ways to disable triggers in SQL Server so they won't i ...

  3. sql安装弹出sqlcmd_SQL Server中SQLCMD实用工具概述

    sql安装弹出sqlcmd This article is aimed at helping you understand the sqlcmd utility. Of course, this is ...

  4. sql 触发器嵌套条件_SQL Server中的嵌套触发器

    sql 触发器嵌套条件 Nested Triggers in SQL Server are actions that automatically execute when a certain data ...

  5. 如何将用户迁移到SQL Server中的部分包含的数据库

    介绍 (Introduction) Microsoft introduced the Contained Database feature in SQL Server 2012. In this ar ...

  6. SQL Server中唯一索引和唯一约束之间的区别

    This article gives you an overview of Unique Constraints in SQL and also the Unique SQL Server index ...

  7. c# mysql 触发器 实时,C#-.Net SqlDataAdapter和SQL Server中的触发器

    我在SQL Server中使用触发器,该触发器在SQL Server Management Studio的查询窗口中执行查询时按要求工作.触发器的目的是从一个表中获取最新值(其中一个ID对应于插入的I ...

  8. 如何在SQL Server中使用触发器

    触发器是一种特殊的存储过程,在使用触发器之前可以与存储过程进行比较,触发器主要是通过事件进行触发而被执行的,而存储过程可以通过存储过程名称而被直接调用. 触发器主要优点如下: 触发器是自动的:当对表中 ...

  9. sql azure 语法_Azure SQL Server中的CREATE DATABASE语句概述

    sql azure 语法 In this article, we will review CREATE DATABASE statement in the Azure SQL database wit ...

最新文章

  1. 计算机由那几个基础部分组成,计算机的基本组成由哪些?
  2. CentOS5.8下varnish-2.1.5的安装配置
  3. C语言关于符号#和##
  4. Test435678
  5. C#基础:理解装箱与拆箱
  6. Docker中RocketMQ的安装与使用
  7. 在不使用{}时,else执行到哪里结束
  8. 把函数包起来就是一个R包 - 完整开发指南
  9. 通过Etcd+Confd自动管理Haproxy(多站点)
  10. RWMutex的一道面试题
  11. 转:基于iOS上MDM技术相关资料整理及汇总
  12. (补)20200328:两两交换链表中的节点(leetcode24)
  13. ai人工智能操控什么意思_为什么要建立AI分散式自治组织(AI DAO)
  14. OpenDRIVE坐标系解读
  15. python 大智慧自定义数据_大智慧扩展数据、自定义数据
  16. 数学基础知识总结 —— 1. 常用导数公式
  17. python turtle 画蜡笔小新_蜡笔小新有几集?作者到底怎么死的啊?
  18. OpenGL中的抗锯齿绘线(上)
  19. Android 自定义view完全解析--带你通透了解自定义view
  20. [Python] Python数值取整

热门文章

  1. 三 .数据库(表操作)
  2. 279 Perfect Squares 完美平方数
  3. shell脚本修改文本中匹配行之前的行的方法
  4. gabor变换人脸识别的python实现,att_faces数据集平均识别率99%
  5. ASP基础教程:ASP脚本变量、函数、过程和条件语句
  6. MySQL导入MongoDB
  7. 在Windows 7中安装、配置和使用IIS7和ASP
  8. ES6——函数参数默认值
  9. 计算机网络学习笔记(5. 电路交换)
  10. 【Koa】Error: Cannot find module ‘koa-router‘