Comparison of Spring and Django security mechanisms

Source: Internet
Author: User
Tags python decorator

For more than a year of Python web development work, yesterday, a classmate asked me Django security mechanism, I am a blank face. Using the company's development framework every day, I know very little about these things, as if to become a real "code farmers", only know it but do not know why. I want to change, so from the network, check the next, write down was checked, the contents are as follows:

Introduced

Spring is a one-stop web framework for Java language development. Includes: SPRINGMVC,SPRING,SPRINGSECURITY,SPRINGAOP and other sub-frameworks. Spring can integrate third-party frameworks such as Hibernate,ibatis in the database access layer. constitutes a complete Web application framework.

Spring uses a large number of policy patterns, template method patterns, and provides hooks to callback third-party APIs, thus consolidating a large number of third-party frameworks.

Django is a one-stop Web application framework for Python language development. It independently developed all frameworks, from the Web tier to the database access layer.

Spring and Django are functionally basic peers and are the foundation platform for Web application development.

Django leverages the advantages of the Python language itself to implement a complete set of Web application frameworks gracefully.

One of the most popular criticisms of spring is that it uses a large number of XML-formatted configuration files. The configuration effort is quite large. After the introduction of annotation in Java5, although the Java source code can be directly added to the configuration. But every time you modify the configuration must recompile the program, it is inconvenient!

Python is a dynamic language, so Django uses Python source code directly as a configuration file. Python programs can be compiled on the fly without the need for an additional compilation process.

This article will make a systematic comparison of the security mechanisms of spring and Django.

A traditional web security solutionHttpRequest interception method

Most Web applications implement security controls on the action layer. The action layer is responsible for receiving requests and emitting response messages at this level.

It is common practice to define permissions for users in the database. Each permission uses a URL identifier.

A cookie is sent to the user's browser after the user logs in. The server also saves this cookie and associates the cookie with a user.

After the user makes the request again, the user object and the appropriate set of permissions are obtained based on the cookie sent to the database to query the corresponding user. stored in HttpRequest or httpsession, or threadlocal.

Write a filter to pre-filter the HTTP request. This URL is not available in the user's permissions. If not, the error message is returned directly, and the request is not sent to the corresponding action method in the URL.

This scheme enables security control at the action layer to effectively intercept unauthorized access.

EJB security mechanism

The EJB framework for Java also has its own role-based set of security control mechanisms. It enables access control of the service to the EJB object, not the action layer, with a lower granularity.

But using EJB security is cumbersome. The role and security model must be defined as required by the EJB, and a large segment of the XML configuration file must be written to specify an access control policy.

Summary:

EJB implements security control in the business layer, which is meaningful for the EJB architecture program. Because EJBs are in the EJB schema, they are service components that are deployed independently. The client accesses it using the RMI remote protocol.

The client for the EJB can be a Web server or a rich client program.

But is it necessary for a schema such as EJB? This has been a long time debate in the industry. Many people, including the author myself, think that the EJB architecture is obsolete.

The rich client program can also communicate with the Web server program over the HTTP protocol. The Web server can support both the B/S and C/s dual architectures.

Web server programs can also provide a TCP/UDP interface for rich client programs to access.

A final question, such as EJB, is it necessary to deploy business components separately? EJB cluster VS Web server cluster who is superior?

The Web server includes both the HTTP interface and the business logic. The Web server can implement cluster deployment just like EJB. The EJB server communicates with the RMI external interface. The Web server uses HTTP external interface communication. It should be said that the EJB cluster does not provide more advantages than the Web server cluster.


Therefore, I think EJB security mechanism is not better than HttpRequest interception security mechanism.

Spring and Django Security mechanisms

Both spring and Django use AOP (aspect-oriented programming) technology to implement security controls.

SPRINGAOP is an AOP framework developed by spring. Using the features of Java dynamic operation, aspect-oriented (AOP) programming is implemented by reflection technology.

The spring framework, which is responsible for security, is the spring security framework. Spring security uses spring AOP for secure control.

Python is inherently support for AOP. Python's adapter functions make it easy to implement AOP.

Python's decorator function is syntactically similar to Java's annotation, but the actual implementation is completely different.

Java's annotation are descriptive data that can be emitted by the runtime.

The counterpart of annotation in Python is doc in Python. Doc is also descriptive data that can be obtained at run time to generate documents such as Javadoc, or to get help from the runtime by helping (module name/class name/function name). The doc in Python is generally not used like Java's annotation.

The adorner function of Python is not metadata that can be obtained at runtime. The adorner function of Python is a normal Python function. Its first argument is a modified function. Therefore, the round in AOP can be implemented directly. We know that AOP consists of 3 interception mechanisms: Before,after and round. Round is both before and after.

So the Python decorator function is directly equivalent to Java's AOP.

Spring Security Safety mechanism

The following is excerpted from the Spring3.0 Guide:

Spring security can be used in a variety of different authentication environments. We recommend that people use spring security for validation rather than a combination of existing container management validation, but this is also supported-as a way to integrate with your own verification system.

What is spring Security's validation?

Let's consider a standard validation scenario that everyone is familiar with.

1. A user wants to log in using an account and password.
2. The system (successful) verifies that the password is correct for this user name.
3. The user's corresponding information is obtained (their role list and so on).
4. Establish a secure environment for users.
5. The user performs a number of actions that are potentially protected by a permission control mechanism, using the current security environment information through authorization of the operation. "Function needs to verify that the user's permissions meet their own requirements. The function must therefore know where to obtain the user's authorization information "

The first three projects performed the validation process, so we can look at the role of Spring security.

1. The username and password are obtained and compared, in a Usernamepasswordauthenticationtoken instance (it is an instance of the authentication interface that we have seen before).
2. This flag is sent to a AuthenticationManager instance for verification.
3.AuthenticationManager Returns a complete authentication instance after the successful checksum.
4. The security environment is established by calling Securitycontextholder.getcontext (). Setauthentication (...), passed to the returned validation object.

SecurityContext cross-Request storage:

In Spring Security, the responsibility for storing the

SecurityContext between requests falls to the Securitycontextpersistencefilter,

Which by default stores the context as an HttpSession attribute between HTTP requests.

It restores the context to the Securitycontextholder for each request and, crucially, clears the Securitycontextholder whe n the request completes.
Technical Description:

SecurityContext is the Spring security framework object that holds user authorization information. Created when the user logs on.

At the beginning of each request, Spring security uses the filter to restore the SecurityContext in HttpSession to Securitycontextholder. Securitycontextholder is a Java class that contains multiple static functions.

Method of Securitycontextholder: public static void SetContext (SecurityContext context) method to save the SecurityContext object to the threadlocal.

Method Prototypes:

SetContext

public static void SetContext (SecurityContext context)

Associates a new securitycontext with the current thread of execution.

Parameters:

Context-the New SecurityContext (May is not null)

The Securitycontextholder.getcontext () method returns the SecurityContext object that is saved in threadlocal.


Because both the action layer and the service layer are executed under the same thread. Therefore, the action layer AOP holds the SecurityContext can be reused by the service layer.

Users should not directly manipulate the SecurityContext object in HttpSession. You should always get the SecurityContext object using the method provided by Securitycontextholder.

At the end of each request, filter clears the SecurityContext object in the current thread. Because threads may be reused. Not clearing may cause security issues.

Spring security can use XML configuration files or Java annotation to declare security restrictions on methods at the business level. Spring security uses spring AOP technology to intercept the business layer method as it executes, using user authorization within the Securitycontextholder.getcontext () object and the authorization declared on the function. If not, an exception is thrown to return. Thus, the security control of the business layer method is realized.

Django Security mechanism

Django uses the concept of apps to implement each sub-framework. The Django Security-responsible sub-framework is the AUTH application.

After the Django user logs in, the user object is saved in HttpSession. In the Aciton layer (the Django term is view, I use the action instead of view in this article for the same purpose as the Java terminology) to get the user object and its Perm authorization collection. The programmer can manually compare the permissions of the user with the permissions required by the action in the action layer to achieve access control.

This is similar to the previous HttpRequest interception method.

However, Django has more than that. Using the Python decorator function, Django can implement declarative security controls for Aciton functions using the syntax of anontation like Spring Security!

Such as:

From django.contrib.auth.decorators import login_required

@login_required

def my_view (Request):

# ...

The @login_required declaration here indicates that the action (View) function must be called by the logged-on user. @login_required is the decorator function for Python.

Further restrictions on access:

From django.contrib.auth.decorators import permission_required

@permission_required (' Polls.can_vote ', login_url= "/login/")

def vote (Request):

# ...

Note that permission_required () also has an optional login_url parameter, which defaults to '/accounts/login/'.

This allows you to restrict the action based on the user's permissions. If the user does not pass the authorization, it returns to the User a login page.

None of this requires a programmer to write a line of code! Amazing, huh?!

Comparison:

The Python Django framework can only perform ACL control on the action layer. Because it does not use filter to save user information in threadlocal. Therefore, user information is not available in the service layer.

Python itself supports AOP, and threadlocal is supported. So Django can also provide security control over business-layer functions like spring security. It's just that Django didn't do it.

Perhaps Django, as a relatively new community, has no energy to do this. Or more likely, the people in the Django community think it's not necessary to implement security controls at the business level. Action Layer Direct Control No, it's done.

Comparison of Spring and Django security mechanisms

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.