Table of contents
1.
Introduction
2.
What is Grails?
3.
Security
3.1.
What Grails Performs
4.
Protection against Attacks
4.1.
Injection of SQL
4.2.
Phishing
4.3.
Cross-site scripting injection or XSS
4.4.
Fake cross-site requests
4.5.
URL or HTML injection
5.
Denying services
5.1.
Recognizable IDs
6.
Preventing Cross-Site Scripting (XSS)
6.1.
Configuration
7.
Object Encoding and Decoding,
7.1.
Codec Types
7.2.
Standard Codec
7.2.1.
HTMLCodec
7.2.2.
XMLCodec
7.2.3.
HTMLJSCodec
7.2.4.
URLCodec
8.
Authentication
9.
Safety Plug-Ins
10.
Security Spring
11.
Frequently Asked Questions
11.1.
What is the use of Grails?
11.2.
Which is preferable, Grails or Spring?
11.3.
Why is Spring Security used?
11.4.
How do you build a grails project?
11.5.
Does grails use Spring?
12.
Conclusion
Last Updated: Mar 27, 2024
Easy

Grails-Security

Author Saksham Gupta
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hello Ninjas, You must have heard about Grails but wondered about Grails-Security. Don't worry; we have got you covered. In this article, we will cover the topic of Grails-Security.

Intro

But before that, let's learn more about grails.

What is Grails?

Grails is a groovy-based web framework that facilitates quick construction. Grails is a framework for high productivity. Grails was initially known as Groovy on Rails when it was first released in 2005, but the name was changed in 2006 due to a disagreement with the inventor of Ruby on Rails. Grail's purpose was to create a Java Web Framework by combining technologies such as Hibernate and Spring into a single interface.

Grails?

Now let's see what security means in Grails-Security.

Security

Neither Java Servlets nor Grails is more or less secure than the other under Grails-Security. However, due to the design of the JVM that powers the code. Java servlets (and thus Grails) are safe and immune to standard buffer overflow and malformed URL vulnerabilities.

Security

Grails can take a few steps to avoid typical errors and make developing secure apps easier to write. Developer mistakes often cause web security issues.

What Grails Performs

 In  Grails-Security by default, Grails contains a few built-in safety features.

  • All standard DB access through GORM domain objects is SQL escaped to stop SQL injection threats.
    But what is GORM Ninja?
    GORM is Grails' implementation of object relational mapping (ORM). Hibernate, a well-liked and adaptable open source ORM solution, is used internally. However, because of Groovy's dynamic nature and its static and dynamic typing, as well as Grails' convention, developing Grails domain classes requires much less configuration.
  • Scaffolding's default templates HTML when presented, escape all data fields.
  • To avoid code injection, all of Grails' link-creating tags—including link, form, createLink, create a link to, and others.
  • To prevent injection attacks, Grails offers codecs, JS, and URLs that make it simple to escape data when rendered as HTML.

Protection against Attacks

Injection of SQL

In  Grails-Security it's not a problem because Hibernate, the technology that underpins GORM domain classes, automatically escapes data when committing to the DB.

However, shoddy dynamic HQL code that uses unchecked request parameters is still conceivable. For instance, the actions listed below are susceptible to HQL injection attacks:

Wait a min Ninjas, what is HQL?
In contrast to SQL, which operates on tables and columns, Hibernate Query Language (HQL) operates on persistent objects and their properties. HQL is an object-oriented query language.

def vulnerable() {
    def books = Book.find("Whereas book b.title ='" + params.title + "'")
}

or the equivalent call made with a GString:

def vulnerable() {
    def books = Book.find("Whereas bookb.title ='${params.title}'")
}

Avoid doing this. Instead of passing in parameters, use named or positional parameters:

def safe() {
    def books = Book.find("Whereas book b.title = ?",
                          [params.title])
}

Phishing

This is essentially a public relations issue to prevent sabotage of your branding and a stated customer communication policy. Customers must understand how to recognize legitimate emails.

Cross-site scripting injection or XSS

Your application must make every effort to confirm that incoming requests came from it and not from another website. 

Cross Site Injection

Additionally, confirming that any data values generated into views are properly escaped is important. For instance, you must ensure that no one should insert JST or other HTML into data. Or tags that are being viewed by others while delivered to HTML or XHTML.

Fake cross-site requests

CSRF(Cross-site request forgery) includes the transmission of illegal orders from a user that a website trusts. An example would be if a link to your website was embedded on another website while the user was still authenticated.

The user token feature on your forms is the good approach to reducing the risk from these attacks. For further details on utilising it, see Handling Duplicate Form Submissions. Avoiding remember-me cookies is another precaution.

URL or HTML injection

In  Grails-Security here, incorrect information is provided, and when it is later used to build a link on a page, clicking on it will not result in the desired behaviour and may reroute you to another website or change the request parameters.

HTML injection

The codecs provided by Grails simplify handling HTML/URL injection, and all of the tag libraries used by Grails use encodeAsURL when necessary. You must be careful to do this if you develop your tags that produce URLs.

Denying services

In this situation, load balancers and other devices are more likely to be helpful. Excessive queries might still cause issues, for instance, when an attacker sets a link to the maximum value for a result set, forcing a question to go beyond the server's memory limits or slowing down the system. In this case, the best action is sanitizing request parameters before giving them to dynamic finders or other GORM query methods.

int limit = 100
def safeMax = Math.min(params.max?.to integer() ?: limit, limit) // limit to 100 results
return Book.list(max:safeMax)

Recognizable IDs

Numerous applications utilise the final component of the URL as the "id" of an object they want to retrieve from GORM or another source. These are simple to estimate because they are often sequential numbers, especially in the case of GORM.

Therefore, before sending the response to the user, you must assert that the asking user is authorized to see the object with the requested id.

By not doing this, you are practicing "security by obscurity," which is always vulnerable, just like when you use the password "letmein" as your default.

Every unprotected URL must be viewed as potentially open to the public.

Preventing Cross-Site Scripting (XSS)

Attacks involving cross-site scripting (XSS) are a systematic penetration method for web apps. Typically, they entail filling out a form with HTML or JS code that, when displayed, causes the browser to act up. It may be as easy as displaying an alert box, or it could be a lot worse, such as the ability to access the session cookies of other users.

The answer is to hide all suspect user input from view when displayed on a page. For instance,

<script>alert('Got ya!');</script>

Will develop

&lt;script&gt;alert('Got ya!');&lt;/script&gt;

deliver the effects of the harmful input ineffective.

To be safe, Grails, by default, escapes all text in $ expressions in GSPs. All common GSP tags are secure and escape any pertinent attribute values.

How can you prevent Grails from escaping some stuff, then? As long as the HTML is trustworthy, there are legitimate use cases for storing it in the DB and delivering it directly. When this happens, you can instruct Grails to generate the content "raw" or without any escapes:

<section>${raw(page.content)}</section>

This page's raw() method is accessible from GSP pages, tag libraries, and controllers.

Configuration

It is advised that you examine the configuration of a freshly made Grails application to gain insight into how Grails handles XSS protection.When a cookie is marked with the Http-Only flag, the browser is informed that the server should only view the cookie in question. It is prohibited for the client script to attempt to access the cookie. The application has a configuration option for this. As shown in the YML configuration file below:

server:
    session:
        cookie:
            domain: example.org
            HTTP-only: true
            path: /
            secure: true

GSP uses several different codecs when writing the page to the response. The following is a description of the codecs configured in the codecs block:

Expression - Any code found in $.. expressions are encoded using the expression codec. HTML encoding is the default for freshly built applications.

Scriptlet: Used for GSP script output (%%, %=% blocks). HTML encoding is used by default for newly developed applications.

GSP tag:- libraries' output is encoded using Taglib. For new applications, the default is none since, in most cases, it is up to the tag author to select the encoding for a particular tag, and by providing none, Grails maintains compatibility with earlier tag libraries.

Static parts: - Used to encrypt the unprocessed markup that a GSP page outputs.

Object Encoding and Decoding,

The idea of dynamic encoding or decoding methods is supported by Grails. Grails come with a collection of common codecs. Developers can submit their own codecs to Grails through a straightforward interface, and such codecs will be recognised at runtime.

Encoding and Decoding

Codec Types

A Grails codec class can have both a decode, and an encode closure. The Grails framework dynamically loads codecs from the grails-app/utils/ directory when a Grails application launches.

The framework searches for class names that follow the convention Codec in the directory grails-app/utils/. For instance, HTMLCodec is one of the default codecs included with Grails.

Standard Codec

HTMLCodec

This codec carries out HTML escaping and unescaping, allowing values to be safely rendered on an HTML page without adding any HTML tags or affecting the page's layout. For instance, if you were to render the value "Don't you know that 2 > 1?" within an attribute, such as the value attribute of an input field, you wouldn't be able to display this securely within an HTML page since the > will appear to close a tag.

XMLCodec

This codec handles escaping and unescaping of XML. It escapes the following characters: & , < , > , " , ' , \\\\ , @ , ` ,non-breaking space (u00a0), line separator (u2028), and paragraph separator (u2029).

HTMLJSCodec

Encoding for HTML and JS is done using this codec. It is employed to stop a few DOM-XSS vulnerabilities. For instructions on preventing DOM-based XSS attacks, see the OWASP - DOM-based XSS Prevention Cheat Sheet.

URLCodec

When generating URLs for links, form actions, or whenever data is needed to generate a URL, URL encoding is necessary. As an illustration, "Apple & Blackberry" will not function properly as a parameter in a GET request since the ampersand will break parameter parsing. This prevents illegal characters from getting into the URL and affecting its meaning.

Authentication

Since there are numerous ways to handle authentication, Grails lacks a default authentication mechanism. However, employing interceptors makes it straightforward to construct a basic authentication scheme. This is adequate for direct use cases, but it's far better to utilise a well-known security framework, such as Spring Security or the Shiro plugin.

Safety Plug-Ins

Consider using the spring security core plugin if you require features other than simple authentication, such as authorisation, roles, etc.

Security Spring

The Spring Security project, which offers a flexible, extendable framework for creating various authentication and authorization systems, is the foundation upon which the Spring Security plugins are created. Since the plugins are modular, you can add only the features your application requires. The official security plugins for Grails are actively supported and maintained as Spring Security plugins.

Frequently Asked Questions

What is the use of Grails?

Web applications can be quickly created with Grails thanks to its scaffolding features. And enables quick project creation. Grails is based on the convention over setting idea, allowing the programme to auto-wire based on naming schemes.

Which is preferable, Grails or Spring?

Reviewers found Grails to be generally easier to use, set up, and conduct business with when comparing the two options. Reviewers, however, preferred Spring Framework's simplicity of management. Reviewers believed that Spring Framework and Grails better fit their businesses needs.

Why is Spring Security used?

Spring Security is the clear choice for implementing application-level security in Spring applications. Its overall goal is to provide you with a highly customisable method of implementing authentication, authorisation, and protection against common attacks.

How do you build a grails project?

Use the Grails Application Forge to create your Grails project by going to start.grails.org. After selecting your project type, Grails version, and Profile, click "Generate Project" to receive a ZIP file. There is no need to install Grails!

Does grails use Spring?

The usage of Spring's transaction management by Grails is arguably the most significant. In addition, many plugins exploit the Spring integration offered by Java libraries, as I've already hinted at. Grails applications are Spring applications.

Conclusion

In this article, we have learned about  Grails-Security And Configuring Additional Beans and understanding Runtime Spring with the Beans DSL. If you want to learn more articles like  Grails-Security, spring boot, click the link below.

Spring Boot Architecture.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JS, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations. 
Happy Learning Ninja! 

Live masterclass