Table of contents
1.
Introduction
2.
Securing Spring Boot Applications
3.
Log-in View
4.
Usage of Vaadin’s Login Form component
5.
Spring Security Dependencies
6.
Log-Out Capability
7.
Security Configuration Class
7.1.
Never Use Hard-coded Credentials in Production
8.
Annotating the View Classes
9.
Frequently Asked Questions
9.1.
Was enable application security?
9.2.
What is global Security in the WebSphere application server?
9.3.
What happens when I enable security defaults?
9.4.
In the event that global Security is enabled during installation, what is the default user registry?
9.5.
What is Dynatrace application security?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

Enabling Security

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Vaadin Flow's built-in security helpers enable a view-based access control mechanism in a Spring Boot application with the bare minimum of Spring Security configurations. Based on various access level annotations, this view-based access control mechanism enables you to flexibly secure views in Vaadin Flow applications. The view-based access control mechanism explicitly uses the annotations @AnonymousAllowed@PermitAll, @RolesAllowed, and @DenyAll on view classes to define the access control rules.

Securing Spring Boot Applications

The most well-liked security products in the Java ecosystem, such as Spring Security, JAAS, and Apache Shiro, are fully compatible with Vaadin. Vaadin Flow has built-in security helpers that are most practical to use with Spring Security, though the security framework of your choice is available. Compared to using the Spring Security framework directly or another security framework, these built-in helpers with Spring Security make it simpler, faster, and safer to secure your Vaadin applications.

Spring Security

Add the following to the project (if they don't already exist) to activate the mechanism in a Vaadin Flow Spring Boot application without any security:

  • An account view.
  • Dependencies for Spring Security.
  • Logging out ability

 

A class that extends VaadinWebSecurityConfigurerAdapter for security configuration.

One of the annotations @AnonymousAllowed, @PermitAll, or @RolesAllowed on each view class.

shows the picture of enabling security

Log-in View

Many authentications and authorization mechanisms must have a log-in view to be able to direct anonymous users to that page before granting access to view any protected resources.

LoginView.java

@Route("login")

@PageTitle("Login")
public class LoginView extends VerticalLayout implements BeforeEnterObserver {
   private LoginForm login = new LoginForm();
   public LoginView() {
       addClassName("login-view");
       setSizeFull();


       setJustifyContentMode(JustifyContentMode.CENTER);
       setAlignItems(Alignment.CENTER);


       login.setAction("lgn");


       add(new H1("Tst Applictn"), login);
   }


   @Override
   public void beforeEnter(BeforeEnterEvent beforeEnterEvent) {
       if(beforeEnterEvent.getLocation()
           .getQueryParameters()
           .getParameters()
           .containsKey("rrr")) {
           login.setError(true);
       }
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Shows vaadin

Usage of Vaadin’s Login Form component

For simplicity in this implementation, we use Vaadin's Login Form component in this example. You are free to use your log-in view; however, there is no requirement.

Spring Security Dependencies

To enable Spring Security, the project needs to have a few additional dependencies. Given that this manual is based on Spring Boot, we suggest adding the dependency:

Dependency for Spring Boot Starter Security that needs to be included in the pom.xml file:

<dependencies>
   <!-- other dependencies -->
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-security</artifactId>
   </dependency>
   <!-- other dependencies -->
</dependencies>

Log-Out Capability

In web applications, a log-out button is typically used to handle logging out. Here is a simple example of how a log-out control would be implemented, as seen on the main layout's header:

MainLayout.java

Public class MainLayout extends AppLayout {


   private SecurityService securityService;


   public MainLayout(@Autowired SecurityService securityService) {
       this.securityService = securityService;
	

       H1 logo = new H1("Vdn CRM");
       logo.addClassName("lg");
       HorizontalLayout header;
       if (securityService.getAuthenticatedUser() != null) {
           Button logout = new Button("Lgt", click ->
                   securityService.logout());
           header = new HorizontalLayout(logo, logout);
       } else {
           header = new HorizontalLayout(logo);
       }


       // Other page components omitted.


       addToNavbar(header);
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Authenticating a user and logging them out may be done differently depending on the application. Here is a straightforward example showing how to do this using the Spring Security API:

SecurityService.java

@Component
public class SecurityService {


   private static final String LOGOUT_SUCCESS_URL = "/";


   public UserDetails getAuthenticatedUser() {
       SecurityContext cntxt = SecurityContextHolder.getContext();
       Object prncpl = context.getAuthentication().getPrincipal();
       if (prncpl instanceof UsrDtls) {
           return (UsrDtls) context.getAuthentication().getPrincipal();
       }
       // Anonymous or incomplete authentication
       return NULL;
   }
public void logout() {
       UI.getCurrent().getPage().setLocation(LOGOUT_SUCCESS_URL);
       SecurityContextLogoutHandler lgtHndlr = new SecurityContextLogoutHandler();
       lgtHndlr.logout(
               VaadinServletRequest.getCurrent().getHttpServletRequest(), null,
               null);
   }
}
You can also try this code with Online Java Compiler
Run Code

Security Configuration Class

The following step is to develop an extension of VaadinWebSecurityConfigurerAdapter for the Spring Security Configuration class. Since there is no established naming pattern for this class, it is referred to as SecurityConfiguration in this article. But be cautious when using Spring Security annotations. Here is a simple example of how to implement such a class:

SecurityConfiguration.java

@EnableWebSecurity
@Configuration
public class SecurityConfiguration
               extends VaadinWebSecurityConfigurerAdapter {


   @Override
   protected void configure(HttpSecurity HTTP) throws Exception {
       // giving the superclass responsibility for general HTTP 
       //security configurations. The following configurations are being 
       //made: Vaadin's CSRF protection by disabling the default request 
       //cache, disabling internal requests from the framework, disabling 
       //public views annotated with @AnonymousAllowed, and disabling 
       //access to other views and endpoints.
       // ViewAccessChecker permission. Here, you are free to add 
       //any additional configurations you may have (the examples below 
       //are merely examples):


       super.configure(http);


       // To register your log-in view with the view access 
       //checker mechanism, please do the following:
       setLoginView(http, LoginView.class);
   }


   /**
    * bypasses the Security of Spring and permits access to static resources.
    */
   @Override
   public void configure(WebSecurity web) throws Exception {
       // Set up public access for your static resources here:
       web.ignoring().antMatchers(
               "/images/**"
       );


       // Giving the superclass control over the ignoring 
       //configuration for Vaadin's / associated static resources:
       super.configure(web);
   }


   /**
    * Demo UserDetailService only provides two 
    *hardcoded user roles in memory. NOTICE: This shouldn't be applied in 
    *practical situations.
    */
   @Bean
   @Override
   public UserDetailsService userDetailsService() {
       UserDetails user =
               User.withUsername("user")
                       .password("{noop}user")
                       .roles("USER")
                       .build();
       UserDetails admin =
               User.withUsername("admin")
                       .password("{noop}admin")
                       .roles("ADMIN")
                       .build();
       return new InMemoryUserDetailsManager(user, admin);
   }
}
You can also try this code with Online Java Compiler
Run Code

 

  1. Take note of the @Configuration and @EnableWebSecurity annotations present on top of the above class. They instruct Spring to enable its security features, as their names suggest.
     
  2. A helper class called VaadinWebSecurityConfigurerAdapter extends Spring's WebSecurityConfigurerAdapter to configure the standard Vaadin-specific Spring security settings. The view-based access control mechanism is automatically enabled by extending it; no additional configuration is required. The following other benefits are covered.
     
  3. The configure methods' default implementation handles all Vaadin-related configuration, such as ignoring static resources, enabling CSRF checking, and ignoring pointless checking for internal Vaadin requests.
     
  4. With the help of the provided setLoginView() method, the log-in view can be easily configured.

 

Never Use Hard-coded Credentials in Production

For brevity in this article, the userDetailsService() method implementation is just an in-memory implementation. You can modify the Spring Security configuration in a real-world application to use an authentication provider for LDAPJAAS, and other real-world sources.

In the example above, the most crucial configuration is the call to setLoginView(HTTP, LoginView.class) inside the first configure method. When users try to navigate to a protected view, the view-based access control mechanism uses this information to determine where to reroute them.

It is time to proceed and observe how the security annotations on the views function now that the LoginView is prepared and has been designated as the log-in view in the security configuration.

Shows limitations

Annotating the View Classes

Before we give some usage examples of access annotations, it would be beneficial to take a closer look at the annotations and their meaning when they are applied to a view:

  • Anyone may access the view thanks to @AnonymousAllowed without requiring any authorization or authentication.
  • Any authenticated user may access the view thanks to @PermitAll.
  • The annotation value @RolesAllowed grants access to users who have the roles listed there.
  • Everyone is forbidden from traveling to the view by using @DenyAll. Since this is the default, the @DenyAll logic is used if a picture is not annotated.

 

It should be noted that Vaadin's SpringSecurityAutoConfiguration enters the picture and activates the view-based access control mechanism when the security configuration class extends from VaadinWebSecurityConfigurerAdapter. As a result, all of the views (aside from @DenyAll) are inaccessible until one of these annotations is applied to them.

Some instances:

An example of @Anonymous usage Permitted allows all users to access this view

@Route(value = "", layout = MainView.class)
@PageTitle("Public View")
@AnonymousAllowed
public class PublicView extends VerticalLayout {
   // ...
}
You can also try this code with Online Java Compiler
Run Code

 

An illustration of using @PermitAll to restrict access to this view to only authenticated users (regardless of role)

	@Route(value = "private", layout = MainView.class)
	@PageTitle("Private View")
	@PermitAll
public class PrivateView extends VerticalLayout {
   // ...
}
You can also try this code with Online Java Compiler
Run Code

 

An example of using @RolesAllowed to restrict access to this view to only those with the ADMIN role

	@Route(value = "admin", layout = MainView.class)
	@PageTitle("Admin View")
	@RolesAllowed("ADMIN") // <- should correspond to a user's role (case-sensitive)
public class AdminView extends VerticalLayout {
   // ...
}
You can also try this code with Online Java Compiler
Run Code

 

Example of inheriting security annotations from the parent class

@RolesAllowed("ADMIN")
	public abstract class AbstractAdminView extends VerticalLayout {
  		// ...
	}

	@Route(value = "user-listing", layout = MainView.class)
	@PageTitle("User Listing")
	public class UserListingView extends AbstractAdminView {
  		// ...
	}

 

The security annotations are inherited from the nearest parent class, as demonstrated in the previous example. Any inherited annotations are overridden when a child class is annotated. Only types are examined for annotations; interfaces are not. Because doing so would make deciding which security level to use needlessly difficult, the annotations are not by design read from parent layouts or "parent views." The following guidelines are followed if more than one annotation is specified for a single view class:

  • The annotation DenyAll overrides all others.
  • Allowed supersedes RolesAllowed and Permit.
  • RolesAllowed prevails over PermitAll.

 

However, it is not advised to specify more than one of the access above annotations on a view class because it is confusing, and there is probably no logical justification for doing so.

An error message appears when a user who has already authenticated attempts to access a view for which they do not have permission.Depending on the application mode, the message

  • Vaadin displays an Access denied message and a list of accessible routes in development mode.
  • In production mode, Vaadin displays the RouteNotFoundError view, which by default displays the message Could not navigate to "RequestedRouteName." The statement doesn't specify whether the navigation target is real for security reasons.

 

Frequently Asked Questions

Was enable application security?

Select Security> Global Security from the Integrated Solutions Console navigation pane. Select Enable application security on the Global Security page. Tap Apply. Press Save.

What is global Security in the WebSphere application server?

Global security settings are configuration options for Security that apply to all administrative tasks and offer the default configuration for user applications. The ability to add extra security domains to protect user applications and their resources is a brand-new feature in WebSphere Application Server V7.

What happens when I enable security defaults?

All authentication requests made using an older protocol will be blocked after security defaults have been enabled in your tenant. Security defaults prohibit basic authentication for Exchange Active Sync. Ensure your administrators aren't using outdated authentication protocols before allowing security defaults.

In the event that global Security is enabled during installation, what is the default user registry?

The console can be found at http://your host.your domain:9060/ibm/console by default. A user ID is requested if Security is disabled. Use any user ID to log in. However, you are prompted for a user ID and a password if Security is enabled.

What is Dynatrace application security?

You can identify, visualize, analyze, monitor, and fix open-source and third-party vulnerabilities in production and pre-production environments using Dynatrace Application Security. Davis, the Dynatrace AI causation engine, powers automatic and continuous protection.

Conclusion

So that's the end of the article. Enabling Security

After reading about the Enabling Security, Are you interested in reading/exploring more themes on Security?

Don't worry; Coding Ninjas has you covered. Check out Overloading and Overriding static Methods in javaUnderstanding Association, Aggregation, and Composition in Javajava interview questionsMultiple Inheritance in JavaMultilevel Inheritance in Java.

However, if you want to give your work an edge over the competition, you might choose to enroll in one of our premium courses.

With our Coding Ninjas Studio Guided Path, you may learn about Data Structures & Algorithms, Competitive Programming, JavaScript, System Design, and more! If you want to put your coding skills to the test, check out the mock test series on Coding Ninjas Studio and participate in the contests! But if you've only recently started your schooling and are looking for answers to issues presented by digital titans like Amazon, Microsoft, Uber, and others. In this situation, you must consider the obstaclesinterview experiences, and interview package as part of your placement preparations. If you find our blogs valuable and fascinating, please vote them up!

Good luck with your studies!

Live masterclass