Home > Articles > Programming > Windows Programming

This chapter is from the book

2.3 Implementing SQL-Based Authentication and Authorization

Application-specific authentication and authorization can be implemented using a relational database server. The authentication process is simply a matter of prompting (forcing) the user to enter a user ID and a password and then looking up that user ID and password in the database to make sure they are valid. If a principal enters a valid user ID and password, they are authenticated. An invalid user ID and password are not authenticated, and the principal is denied access to any secure resources.

As already discussed in this chapter, typical B2B applications require a matrix of authorization levels, and the authority to access resources must be granted based on multiple criteria, such as the principal's identity, employer, role, and so on.

Resources can be Web pages, documents on the Web site, SOAP methods, portions of Web pages that display data from internal systems, and so forth. A resource could be anything on the B2B site to which you may want to control access.

An authorization process to control access to resources requires that all of the secured resources be listed in the database. In other words, there must to be a row in a database table for each resource that you want to protect.

In Chapters 3 through 5, you will work through an ASP.NET Web Forms example that secures access to documents on a Web site. This chapter contains the code that creates the database the Web Forms application uses.

To work through the Chapter 2 code, create a SQL Server database named "ManufacturerA," and execute the SQL commands in the code listings here. Then enter the data shown later in the chapter to test the database and get it ready for use in Chapter 3.

Run the SQL DDL (data definition language) code shown in Listing 2-1 to create in your "ManufacturerA" database a Documents table that will be used to control access to documents.

LISTING 2-1 Table Linking Permission Lists and Documents

CREATE TABLE Documents (
    DocID varchar (20) NOT NULL ,
    Name varchar (20),
    MimeType varchar (20),
    FilePath varchar (250)
)

The DocID field is the unique identifier, the key field, for each document. The Name field is the name of the document that is displayed on the Web page as a hyper-link, which users can click to see the document. The MimeType is the file type, and the FilePath field points to the location where each document can be accessed and sent out to browsers that request it.

The DocID field is also a foreign key that is used to link each document to Permission List records. A link table is used to link permission lists with documents. Run the SQL code shown in Listing 2-2 to create this table.

LISTING 2-2 Table Linking Permission Lists and Documents

CREATE TABLE PLDocument (
    PermissionListID int NULL ,
    DocumentID varchar (20)
)

A permission list is a collection of criteria. The PermissionLists table holds the permission lists. Create the PermissionLists table defined in Listing 2-3.

LISTING 2-3 Permission List Table

CREATE TABLE PermissionLists (
    PLKey int NOT NULL ,
    Company varchar (50),
    CompanyCategory varchar (50),
    Person varchar (50),
    Role varchar (50)
)

In Listing 2-3, the PLKey field is the primary key for the table and the unique identifier for each permission list. Each permission list is a unique combination of Company, CompanyCategory (which is used to classify companies), Person, and Role.

The intent is for each field to be AND'ed together to determine a unique level of access. For example, a permission list with "Viewstar" as the Company and "Executive Staff" as the Role means that a principal has to be both an employee of Viewstar and a member of the executive staff in order to qualify for that permission. In this case, the CompanyCategory and Person fields would be populated with some value, an "any" symbol of some kind that would indicate there are no restrictions on those fields.

These permissions are linked to documents using the PLDocument table. For example, if a particular document had the just mentioned Viewstar/Executive Staff permission as its lone permission, only principals who are executives of Viewstar would be authorized to access that document. If more than one permission is linked to a particular document, those permissions are OR'ed together, meaning that a principal need only qualify for one of the permissions to gain access to that document.

Permission lists are also associated with principals. This is implemented in the PLPerson table. Run the code to create the PLPerson table defined in Listing 2-4.

LISTING 2-4 Table Linking Permission Lists and Persons

CREATE TABLE PLPerson (
    PermissionListID int NULL ,
    PersonID varchar (20) NULL
)

There also needs to be a table that holds person data. Run the SQL code to create the table that holds person data that is shown in Listing 2-5.

LISTING 2-5 Table Containing Person Data

CREATE TABLE Persons (
    UserID varchar (20) NOT NULL ,
    Password varchar (50) NOT NULL
)

In Listing 2-5, the UserID field is the primary key for the table, and it is the unique identifier for each permission list. Of course, there would be several other fields in the Persons table of a real B2B application. These fields might include such information as each person's employer, role or roles, contact information, and so forth. The schema is simplified here for clarity.

The Password field holds the user's password. It is specified here as 50 characters in length to accommodate encrypted passwords. An even better idea than storing encrypted passwords is storing the passwords as hash values, which are more difficult to reverse.

You could use a message digest algorithm such as MD5 or SHA-1 to distill each password into a value of 128 or 256 bits in length, which you could store in the database instead of the password itself. Performing a search for "MD5" or "SHA-1" with a Web search engine will net you a long list of resources that will help you implement these message digest functions in your applications.

NOTE

In real B2B applications, the passwords should never be stored in clear text in the database. Ideally, passwords should be stored as Hash values, which would make the passwords extremely difficult to decipher.

Each user in the database could potentially be associated with several permissions. It is a matter of comparing each person's attributes—such as his or her employer, role, and so on— with the permission lists in the PermissionLists table and then putting a record in the PLPerson table for each permission for which the person qualifies.

Each person and each document are associated with permission lists. This is illustrated in Figure 2-3.

Figure 2-3FIGURE 2-3 Relationship Between Persons, Permission Lists, and Documents

The SQL code to enforce these relationships in a Microsoft SQL Server database is shown in Listing 2-6. Run this code to create these constraints in your Manu-facturerA database.

LISTING 2-6 Constraints to Enforce Relationships with Permission Lists

ALTER TABLE PermissionLists WITH NOCHECK ADD
    CONSTRAINT PK_PermissionLists PRIMARY KEY CLUSTERED
    (
        PLKey
    ) ON [PRIMARY]
GO
ALTER TABLE Documents WITH NOCHECK ADD
    CONSTRAINT PK_Documents PRIMARY KEY CLUSTERED
    (
        DocID
    ) ON [PRIMARY]
GO
ALTER TABLE Persons WITH NOCHECK ADD
    CONSTRAINT PK_Persons PRIMARY KEY CLUSTERED
    (
        UserID
    ) ON [PRIMARY]
GO
ALTER TABLE PLDocument ADD
    CONSTRAINT FK_PLDocument_Documents FOREIGN KEY
    (
        DocumentID
    ) REFERENCES Documents (
        DocID
    ),
    CONSTRAINT FK_PLDocument_PermissionLists FOREIGN KEY
    (
        PermissionListID
    ) REFERENCES PermissionLists (
        PLKey
    )
GO
ALTER TABLE PLPerson ADD
    CONSTRAINT FK_PLPerson_PermissionLists FOREIGN KEY
    (
        PermissionListID
    ) REFERENCES PermissionLists (
        PLKey
    ),
    CONSTRAINT FK_PLPerson_Persons FOREIGN KEY
    (
        PersonID
    ) REFERENCES Persons (
        UserID
    )
GO

In a production application, there are no doubt other constraints that you would want to add. For instance, you might want to add a constraint on the Permis-sionLists table to enforce the uniqueness of the combination of the CompanyCate-gory, Person, and Role fields (recall that each record is a unique combination of those fields).

Given a person, it is easy to write a SQL query that returns the IDs of the documents that the person can access. The SQL SELECT statement in Listing 2-7 returns the documents that a principal is authorized to access. In Listing 2-7, the personID of 'SidSalesman' could be a parameter, which is passed into the query to generalize it for use with any person in the database. To make this example a bit more concrete, enter data into the PermissionLists table, as shown in Table 2-1.

LISTING 2-7 Query to Return the Documents a Principal Can Access

SELECT DISTINCT pldocument.documentid from pldocument, plperson
WHERE pldocument.permissionlistID = plperson.permissionlistID
AND plperson.personID = 'SidSalesman'

The example Data in Table 2-1 shows ten permission lists, each of which is a unique combination of the fields. The "0" in the fields indicates that there is no restriction on that field for that particular permission. For example, PermissionList 8 requires that the principal have a role of "Sales Staff," but there are no other restrictions. To qualify for that permission, the principal must have the "Sales Staff" role but could be employed by any company of any category.

TABLE 2-1 Example Data in PermissionList Table

PLKEY

COMPANY

CATEGORY

PERSON

ROLE

1

0

0

SamSiteAdmin

0

10

0

Gold

0

Executive Staff

2

0

0

0

Developer

3

0

Gold

0

0

4

T & R Tech

0

0

0

5

T & R Tech

0

0

Executive Staff

6

Viewstar

0

0

0

7

Viewstar

0

0

Executive Staff

8

0

0

0

Sales Staff

9

0

SiteOwner

0

0


PermissionList 9 is interesting because it uses a category of "SiteOwner." In this scheme, there is a company table that contains all of the information for each company. The company that owns the B2B Web site is given a category of "SiteOwner." PermissionList 1 is a very restrictive permission. Only a principal with a Person ID of SamSiteAdmin qualifies for that permission.

Enter data in the PLDocument table so that it is populated as shown in Table 2-2. Because of the foreign key constraints, you will first need to add records in the Documents table that correspond to the DocID entries shown in Table 2-2. For now, you can just fill in the DocID field in the Documents table and leave the other fields blank. It goes without saying that you will enter each DocID only once in the Document table. After entering the DocIDs, enter the data in Table 2-2 in the PLDocument table. There is a one-to-many relationship between the Documents table and the PLDocument table, which is why there are duplicate DocIDs in Table 2-2.

You can see that GoldQuotas and GoldPaymentTerms are accessible only by Permission 10, which is only the executive staff of companies with a Gold category. You can also see that most of the admin documents are limited to Permission 1, which is restricted to PersonID SamSiteAdmin.

Enter data so that the PLPerson table is populated as shown in Table 2-3. Table 2-3 is sorted by PersonID so that you can see what is happening with each person.

TABLE 2-2 Example Data in PLDocument Table

DOCID

PERMISSIONLISTID

AdminProcedures

1

AdminPolicy

1

ContentCodes

8

ContentCodes

9

TRTechContract

5

ViewstarContract

7

DevHowTo

2

EastRegionProdInfo

4

EastRegionProdInfo

6

GoldPricing

3

GoldQuotas

10

GoldPaymentTerms

10

SalesLit

3

SalesLit

8


TABLE 2-3 Example Data in PLPerson Table

PERSONID

PERMISSIONLISTID

ElmerEmployee

9

EdTRExecutive

3

EdTRExecutive

4

EdTRExecutive

5

PeterProgrammer

2

SamSiteAdmin

1

SamSiteAdmin

10

SamSiteAdmin

2

SamSiteAdmin

3

SamSiteAdmin

4

SamSiteAdmin

6

SamSiteAdmin

8

SamSiteAdmin

9

SidSalesman

3

SidSalesman

6

ValViewStarExec

3

ValViewStarExec

6

ValViewStarExec

7

ValViewStarExec

8

VickiViewStar

6


Because of the foreign key constraints, you will first need to add in the Persons table records that correspond to the PersonID entries shown in Table 2-3. For now, you can just fill in the Password field in the Person table with "1234." After entering the PersonIDs in the Persons table, enter the data in Table 2-3 in the PLPerson table.

PersonID SamSiteAdmin has been given almost every permission in the system. This is because he is the system administrator and must have access to lots of places. The only permissions he doesn't have are 5 and 7, which are the Viewstar and T & R Tech executive staff permissions. (In a real implementation, the system administrator would probably qualify for those permissions as well.) PersonID ElmerEmployee has only one permission, that of SiteOwner. He is apparently an employee of the company that owns the B2B Web site, but he hasn't been given much access to it.

TABLE 2-4 Resources that PersonID EdTRExecutive Is Authorized to Access

RESOURCEID

TRTechContract

EastRegionProdInfo

GoldPricing

SalesLit


PersonID EdTRExecutive is apparently an executive with T&R Tech. Running the SQL query in Listing 2-7 with PersonID = 'EdTRExecutive' yields the documents in Table 2-4.

A stored procedure can be created for SQL Server that takes the PersonID and DocumentID as input parameters and returns an output parameter indicating whether that person has access to that document. The stored procedure is shown in Listing 2-8. This stored procedure does a count of the documents that match this document ID and that are among the documents this person is permitted to access. Of course, there is only one document with this document ID, and it may or may not be among the documents this user is permitted to see, so the count will be either 0 or 1. That makes it handy to use in an if condition in C# code. You actually get to use this stored procedure in an ASP.NET Web page in Chapter 3.

LISTING 2-8 Stored Procedure That returns 0 or 1 if the Principal Has Access

CREATE PROCEDURE sp_UserHasAccessToDoc
@userid VARCHAR(20), @docid VARCHAR(20), @HasAccess INT OUTPUT AS
SELECT @HasAccess = COUNT(*) FROM documents
WHERE DocID = @docid AND DocID IN
(SELECT DISTINCT pldocument.documentid from pldocument, plperson
WHERE pldocument.permissionlistID = plperson.permissionlistID
AND plperson.personID = @userid)
GO

Using these tables and SQL queries to retrieve the documents that a principal can access is pretty straightforward. It would certainly also be possible to create HTML forms that enable content managers on the B2B Web site to manage the data in these tables using a Web browser.

To extend this scheme so it secures the data that is posted on the B2B Web site from internal information systems, developers will have to find a way to limit the data coming out of those internal information systems based on the permissions for each principal. Depending on the capabilities and limitations of those information systems, this may be easy, or it may be difficult.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020