Day6

34
CSE 136 - Lecture 6 Service Layer WCF Business Layer Security Regular Expression

Transcript of Day6

Page 1: Day6

CSE 136 - Lecture 6

Service Layer WCF Business Layer

Security Regular Expression

Page 2: Day6

Overview

Service is consideredpart of the BusinessLayer

We will wrap DomainModel with a ServiceLayer

We will skipWorkflows

Macro-services (more on this later)

Page 3: Day6

What is Service Layer

Sits between GUI & business logic (part of BLL)

GUI

BLL Server

GUI can be replaced by web-service client

Each GUI has a slightly different objects depending onwhether it’s Web, mobile, windows, or just flat-file thatwill import into another system.

DTO - data transfer objects

Services - May call other services on other systems

Page 4: Day6

What is Service

Service will have a contract (parameters and return values)

parametersreturn value

we will skipthese in 136

we will usedefault values

in vs 2010

Page 5: Day6

Service Layer as services wrapper

Following shows the benefit of a service layer: a unique andremotable point of contact between the UI and middle tier

Macroservice

Macro service – orchestrate the entire flow of transaction.

UpdateGrade()

Microservices

Micro service – more detailed business rules

LookupReason()

ChangeGrade()

EmailStudent()

Page 6: Day6

Design Patterns in Service Layer

Remote Façade Pattern A set of methods that modify the granularity existing

operations already implemented elsewhere. A service is already a remote façade over the business layer

Data Transfer Object Pattern Object that carries data across an application’s boundaries ex: XML file as input format for ChangeGrade()

Adapter Pattern Converts the interface of one class into another interface that

a client expects ex: UCSD GPA system takes in % points also

Proxy Pattern Client will create a proxy, and proxy will communicate with the

service

Page 7: Day6

WCF - windows communication foundation

An SDK for developing and deploying services on Windows

A WCF Service is a unit of functionality exposed to the world can be local or remote, developed by multiple parties

using any technology A WCF Client

is merely the party consuming a service's functionality can be literally anything:

ASP.NET (MVC) JAVA app Mobile apps

A set of .NET libraries

Page 8: Day6

WCF - Same vs cross machines

Same Machine Communication using WCF

Right-lick, add servicereference creates the

proxy for you.

Cross-machine Communication using WCF(for scalability or 3rd party services)

Page 9: Day6

ABC of WCF

This was an interview question A - Address

Every service is associated with a unique address. Where are you?

B - Binding A binding is a consistent set of choices regarding the

transport protocol, message encoding, communication pattern, reliability, security, transaction propagation, and interoperability

How should I talk with you? C - Contract

The contract is a platform-neutral and standard way of describing what the service does.

What am I giving/getting from you.

SSL, call-backs, encryption-key

Page 10: Day6

WCF ABC - Address

Every service is associated with a unique address. The address provides two important elements (1) the location of the service

IP address URL

(2) transport protocol or transport schema used to communicate with the service http net.tcp

Examples net.tcp://localhost:8002/MyService http://www.wcf.org:8001 net.pipe://localhost/MyPipe net.msmq://localhost/MyService

Page 11: Day6

WCF ABC - Binding

Basic Binding - expose a WCF service as a legacy ASMX web service

TCP Binding - Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication

Web Service binding - Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet

IPC Binding - Same-machine communication Others (skip) : MSMQ, Duplex WS, etc

Page 12: Day6

WCF ABC - Contract

The contract is a platform-neutral and standard way of describing what the service does

Service contracts (method definition) Describe which operations the client can perform

on the service Data contracts (parameter types)

Define which data types are passed to and from the service.

WCF defines implicit contracts for built-in types such as int and string, but you can easily define explicit opt-in data contracts for custom types.

Page 13: Day6

WCF ABC quick example

open to WCF clients

method and data

not part of the service

visible to service clients

not visible as a service

Page 14: Day6

WCF Operation

Focus on the client side (1) Request & Reply (for CSE 136)

Most common calls - If no response, client gives up always put try/catch in the client code

(2) One-way Send and forget

(3) Call-back (not for CSE 136) The service is the client and the client becomes the

service HTTP cannot be used for callbacks TCP and the IPC protocols support duplex communication Observer Design Pattern

Page 15: Day6

WCF Instance

Focus on the server side Applications differ in their needs for scalability, performance,

throughput, transactions, and queued calls (1) per-call

services allocate (and destroy) a new service instance per client request

This is the default behavior (2) session

allocate a service instance per client connection. [ServiceContract(SessionMode = SessionMode.Required)]

(3) Singleton all clients share the same service instance across all connections

and activations [ServiceBehavior(InstanceContextMode=InstanceContextMode.Singl

e)

Page 16: Day6

RESTful Services

CRUD : Create, Read, Update, and Delete RESTFul : using http methods

Get - Read Post - Create Put - Update Delete - Delete REST stands for “Representational State

Transfer” Skip for 136

Page 17: Day6

WCF Security (authentication) Verifying that the caller of a service is

indeed who the caller claims to be Windows authentication Username and password X509 certificate Custom mechanism & other 3rd parties No authentication (CSE 136)

Page 18: Day6

Business Logic Layer Security User-based Security

Authorization deals with what the caller (user) is allowed to do.

Callers are mapped to logical roles. (Role ex: Faculty, Staff, or Student)

Code-based Security Authenticate the code source Authorize code for access Enforce the code access

Page 19: Day6

BLL Security : user-identity 1

Common security systems (user-identity based)

ResourceAccess

Attempt

"Ali"Person

SecuritySystem

Selfcheck-in

SecurityConfiguration

Name/nationality profiling

Partial Access

Full Access

Deny Access

check-in @counter

Resource

Get onthe

plane

Page 20: Day6

BLL Security : user-identity 2

Resource protection through the interplay of authentication,authorization, and enforcement

Attempt to Access Resource

Authentication of caller

Authorization

Resource

Enforcement

caller

user/password

securityconfiguration

settings

what you areallowed to access

Page 21: Day6

BBL Security : Code-identity-based 1

Authenticate code identity Information about the origin of a piece of code (such as the

URL where it is run from) are collected and presented to the authorization layer

Ex: Tourist visa from China Authorize code, not users, to access resources

All trust decisions to access protected resources are made for particular pieces of code, based on security settings evolving around information about the origin of code

Ex: Tourism visa from China can visit, not work and study Enforce the authorization

The granularity of enforcement functions on the level of individual pieces of code (such as individual assemblies)

.NET CLR enforces the security Ex: Employer checking for U.S. Visa

Page 22: Day6

BBL Security : Code-identity-based 2

Authenticate code identity Authenticates assemblies By collecting evidence about the assembly Ex: assembly's URL or strong name

Authorize code, not users, to access resources Authorizes assemblies By granting assemblies a set of permissions to

access protected resources (such as the file system or registry)

Enforce the authorization By checking that all assemblies calling to a

protected resource have the appropriate permission to access that resource (.NET CLR)

exe & dll

Signed by Microsoft

Page 23: Day6

.NET code-based Security : Evidence

EvidenceProvides the basic building blocks for how code accesssecurity can work on .NET Framework code

SHA1 Hashis the evidence

• Publisher• Site (url)• Zone (where on the

computer)• Strong name (signed

key)

Page 24: Day6

.NET code-based Security : Policy

Policy

Policy containing Membership and Permission Sets.

What type of code/program can access what resources

Four policies in .NET

(1) Enterprise

(2) Machine code running on this machine

(3) User code running by this user

(4) Applications

Similar to homeland security policy Visitors with “Iraq visa” (membership)has limited access to certain “government buildings" (permission set)

Page 25: Day6

.NET code-based Security : Code Group and membership

Code GroupCode group categorized intofollowing zones:

right-click

Membership

availablezones

Page 26: Day6

.NET code-based Security : Permission set

Permissions

A set ofpermissions

List of availablepermissions

no security check

no access at all

check everypermissionlisted

Page 27: Day6

.NET code-based Security : Example

All code belong to "My Computer" zone running on this machine hasfull-trust permission

All of the above sets up the security policy rules. CLR will checkassembly's evidence and allow/disallow code execution

Ex: In government, policy makers set up security policy. When each person travels witha passport/ID, airport-security executes the security check based on the passport

Ex: immigration document typeVisa, Diplomatic ID, birth-certificate

Ex: Chinese Visa

Page 28: Day6

Regular Expressions 1

What is regular expression pattern describing a certain amount of text a series of letters, digits, dots, underscores,

signs and hyphens What are its common usages

Formatting Validating Parsing

Page 29: Day6

Regular Expressions 2using System.Text.RegularExpressions;

... string phone = "1(888)555-1234"; string strRegex = @"[^0-9]";

Regex match = new Regex(strRegex); phone = match.Replace(phone, ""); // strip non digits

Console.WriteLine(phone);...

anynon-digit

characters

Output: 18885551234

public bool IsInteger (String strNumber){

Regex objNotIntPattern =new Regex("[^0-9-]");Regex objIntPattern =new Regex("^-[0-9]+$|^[0-9]+$");return !objNotIntPattern.IsMatch (strNumber) &&

objIntPattern.IsMatch (strNumber);

}

-154

// Function to Check for AlphaNumeric.public bool IsAlphaNumeric (String strToCheck){

Regex objAlphaNumericPattern=new Regex("[^a- zA-Z0-9]");return !objAlphaNumericPattern.IsMatch (strToCheck);

}

[email protected]

Page 30: Day6

Regular Expression 3

bool IsEmail (string inputEmail) { // @ means it's specific to C#, not to regular expression

string strRegex = @"^([a- zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" + @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a- zA-Z0-9\-]+\" + @".)+))([a- zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

Regex re = new Regex(strRegex);

if (re.IsMatch(inputEmail)) return (true); else return (false); }

[email protected]

[email protected]

,,@..com

Page 31: Day6

Review question

Difference between macro and micro services? What design patterns exist in the services layer? What .NET libraries does 136 use to implement the

service layer? What is the ABC of WCF? Difference between authenticate and authorize? What is security policy? (rules defined) What are the four levels of .NET policies? What is code group? (groups of code in a policy) What is membership? (identify a group of code) What is permission set? (set of permissions assigned

to a group of code)

Page 32: Day6

Your assignment

Due Next Thursday Create a Service Layer project Continue development of your BLL Continue development of unit tests for

your BLL

Just a wrapper project

Page 33: Day6

Lab

Due: Grade your DAL with test cases

Page 34: Day6

References

.NET : Architecting Applications for the Enterprise

Learning WCF