Spring Security – Authentication Provider ”; Previous Next Spring Security allows us to customize our authentication process as much as we want. Starting from a custom login page to our very own customized authentication providers and authentication filters, we can pretty much customize every aspect of the authentication process. We can define our own authentication process which can range from basic authentication using a username and a password to a complex one such as two-factor authentication using tokens and OTP’s. Also, we can use various databases – both relational and non-relational, use various password encoders, lock malicious users out of their accounts, and so on. Spring Security Architecture The basic components of Spring Security, as we can see in the above diagram are given below. We shall discuss them briefly as we go along. We shall also discuss their roles in the authentication and authorization process. AuthenticationFilter This is the filter that intercepts requests and attempts to authenticate it. In Spring Security, it converts the request to an Authentication Object and delegates the authentication to the AuthenticationManager. AuthenticationManager It is the main strategy interface for authentication. It uses the lone method authenticate() to authenticate the request. The authenticate() method performs the authentication and returns an Authentication Object on successful authentication or throw an AuthenticationException in case of authentication failure. If the method can’t decide, it will return null. The process of authentication in this process is delegated to the AuthenticationProvider which we will discuss next. AuthenticationProvider The AuthenticationManager is implemented by the ProviderManager which delegates the process to one or more AuthenticationProvider instances. Any class implementing the AuthenticationProvider interface must implement the two methods – authenticate() and supports(). First, let us talk about the supports() method. It is used to check if the particular authentication type is supported by our AuthenticationProvider implementation class. If it is supported it returns true or else false. Next, the authenticate() method. Here is where the authentication occurs. If the authentication type is supported, the process of authentication is started. Here is this class can use the loadUserByUsername() method of the UserDetailsService implementation. If the user is not found, it can throw a UsernameNotFoundException. On the other hand, if the user is found, then the authentication details of the user are used to authenticate the user. For example, in the basic authentication scenario, the password provided by the user may be checked with the password in the database. If they are found to match with each other, it is a success scenario. Then we can return an Authentication object from this method which will be stored in the Security Context, which we will discuss later. Spring Security provides following major implementations of AuthenticationProvider. DaoAuthenticationProvider − This provider is used to provide database based authentication. LdapAuthenticationProvider − This provider is specialized for LDAP(Lightweight Directory Access Protocol) based authentication. OpenIDAuthenticationProvider − This provider is used for OpenID based authentication and can be used with OpenID authentication providers like Google/Facebook etc. JwtAuthenticationProvider − For JWT(Java Web Token) based authentication, we can use JwtAuthenticationProvider class. RememberMeAuthenticationProvider − This class is used for user authentication based on remember me token of user. We”ll be creating our own AuthenticationProvider in coming section. UserDetailsService It is one of the core interfaces of Spring Security. The authentication of any request mostly depends on the implementation of the UserDetailsService interface. It is most commonly used in database backed authentication to retrieve user data. The data is retrieved with the implementation of the lone loadUserByUsername() method where we can provide our logic to fetch the user details for a user. The method will throw a UsernameNotFoundException if the user is not found. PasswordEncoder Until Spring Security 4, the use of PasswordEncoder was optional. The user could store plain text passwords using in-memory authentication. But Spring Security 5 has mandated the use of PasswordEncoder to store passwords. This encodes the user’s password using one its many implementations. The most common of its implementations is the BCryptPasswordEncoder. Also, we can use an instance of the NoOpPasswordEncoder for our development purposes. It will allow passwords to be stored in plain text. But it is not supposed to be used for production or real-world applications. Spring Security Context This is where the details of the currently authenticated user are stored on successful authentication. The authentication object is then available throughout the application for the session. So, if we need the username or any other user details, we need to get the SecurityContext first. This is done with the SecurityContextHolder, a helper class, which provides access to the security context. We can use the setAuthentication() and getAuthentication() methods for storing and retrieving the user details respectively. Custom Authenticator We can create a custom Authenticator by implementing AuthenticationProvider interface. AuthenticatorProvider interface has two methods authenticate() and supports(). authenticate() method @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = authentication.getCredentials().toString(); UserDetails user = userDetailsService.loadUserByUsername(username); if (user == null || !password.equals(user.getPassword())) { throw new BadCredentialsException(“Invalid username or password”); } List<GrantedAuthority> authorities = new ArrayList(); authorities.add(new SimpleGrantedAuthority(“ROLE_USER”)); return new UsernamePasswordAuthenticationToken(username, password, authorities); } Here in authenticate() method, we”re getting username and password using authentication object and we”re comparing username/password with the user credentials. In case user details are invalid, we”re throwing an exception as BadCredentialsException. Otherwise, a new role is prepared and UsernamePasswordAuthenticationToken is returned with required role. supports() method @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } Spring Security Configuration Use the AuthenticationProvider created in the AuthenticationManager and mark it as managed bean. @Bean public AuthenticationManager authManager(HttpSecurity http) throws Exception { AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class); WebAuthenticationProvider authProvider = new WebAuthenticationProvider(userDetailsService()); authenticationManagerBuilder.authenticationProvider(authProvider); return authenticationManagerBuilder.build(); } That”s all we need. Now let”s see the complete code in action. Before you start writing your first example using Spring framework, you have to make sure that you have set up your Spring environment properly as explained in Spring Security – Environment Setup Chapter. We also assume that you have a bit of working knowledge on Spring
Category: spring Security
Spring Security – Discussion
Discuss Spring Security ”; Previous Next In this tutorial, we will learn about Spring Security Frameworks. We will start with the basics and go through the configuration of various frameworks to work with Spring Security. We will also do some handson coding to perform CRUD operation using Spring Security Frameworks. Print Page Previous Next Advertisements ”;
Spring Security – Remember Me ”; Previous Next Remember Me is an important function of Spring Security, so that a user can remain logged in the application even when session is expired. We”ll demonstrate the use of Remember Me functionality provided by Spring security in following sections. A Remember Me functionality performs following important functions. Firstly, it will add a “Remember Me” checkbox to default login form that we generated using formLogin(). In case of custom login form, we need to add a checkbox named “remember-me” to the form. In case of different name to be used, we need to configure the new name during Spring Security configuration as shown below: .rememberMe().rememberMeParameter(“remember”) And, secondly, ticking the checkbox generates the remember-me cookie. The cookie stores the identity of the user and the browser stores it. Spring Security detects the cookie in future sessions to automate the login. As a result, the user can access the application again without logging in again. A remember-me can be explicitly configured as given below − protected void configure(HttpSecurity http) throws Exception { http // … // key should be unique .rememberMe(config -> config.key(“123456″) .tokenValiditySeconds(3600)) .build(); } Important Methods Following are important methods that we can configure in logout() method. rememberMe () − This will be used to implement remember me functionality. The key passed to remember-me function should be unique and secret. This key is application specific and is used to generate remember me token content. tokenValiditySeconds () − This will be used to set the expiry of the remember me cookie. By default it has validity of 2 weeks. We can customize it any time as in above code snippet, we”ve set it as 1 hour using 3600 seconds. rememberMeParameter () − This is used to mark an input check box to be remember-me checkbox. By default, its value is remember-me. Let us start actual programming with Spring Security. Before you start writing your example using Spring framework, you have to make sure that you have set up your Spring environment properly as explained in Spring Security – Environment Setup Chapter. We also assume that you have a bit of working knowledge on Spring Tool Suite IDE. Now let us proceed to write a Spring MVC based Application managed by Maven, which will ask user to login, authenticate user and then provide option to logout using Spring Security Form Login Feature. Create Project using Spring Initializr Spring Initializr is great way to start with Spring Boot project. It provides a easy to use User Interface to create a project, add dependencies, select java runtime etc. It generates a skeleton project structure which once downloaded can be imported in spring tool suite and we can proceed with our readymade project structure. We”re choosing a maven project, naming the project as formlogin, with java version as 21. Following dependencies are added: Spring Web Spring Security Thymeleaf Spring Boot DevTools Thymeleaf is a templating engine for Java. It allows us to quickly develop static or dynamic web pages for rendering in the browser. It is extremely extensible and allows us to define and customize the processing of our templates in fine detail. In addition to this, we can learn more about Thymeleaf by clicking this link. Let”s move on to generate our project and download it. We then extract it to a folder of our choice and use any IDE to open it. I shall be using Spring Tools Suite 4. It is available for free downloading from the https://spring.io/tools website and is optimized for spring applications. pom.xml with all relevant dependencies Let”s take a look at our pom.xml file. It should look something similar to this − pom.xml <?xml version=”1.0″ encoding=”UTF-8″?> <project xmlns=”http://maven.apache.org/POM/4.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.3.1</version> <relativePath/> <!– lookup parent from repository –> </parent> <groupId>com.tutorialspoint.security</groupId> <artifactId>formlogin</artifactId> <version>0.0.1-SNAPSHOT</version> <name>formlogin</name> <description>Demo project for Spring Boot</description> <url/> <licenses> <license/> </licenses> <developers> <developer/> </developers> <scm> <connection/> <developerConnection/> <tag/> <url/> </scm> <properties> <java.version>21</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity6</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Spring Security Configuration Class Inside of our config package, we have created the WebSecurityConfig class. We shall be using this class for our security configurations, so let”s annotate it with an @Configuration annotation and @EnableWebSecurity. As a result, Spring Security knows to treat this class a configuration class. As we can see, configuring applications have been made very easy by Spring. WebSecurityConfig package com.tutorialspoint.security.formlogin.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class WebSecurityConfig { @Bean protected UserDetailsService userDetailsService() { UserDetails user = User.builder() .username(“user”) .password(passwordEncoder().encode(“user123”)) .roles(“USER”) .build(); UserDetails admin = User.builder() .username(“admin”) .password(passwordEncoder().encode(“admin123”)) .roles(“USER”, “ADMIN”) .build(); return new InMemoryUserDetailsManager(user, admin); } @Bean protected PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests( request -> request.requestMatchers(“/login”).permitAll() .requestMatchers(“/**”).authenticated() ) .formLogin(form -> form.loginPage(“/login”) .defaultSuccessUrl(“/”) .failureUrl(“/login?error=true”) .permitAll()) .rememberMe(config -> config.key(“123456”) .tokenValiditySeconds(3600)) .logout(config -> config .logoutUrl(“/logout”) .logoutSuccessUrl(“/login”) .invalidateHttpSession(true) .deleteCookies(“JSESSIONID”)) .build(); } } Here we”ve mentioned the rememberMe() with a secure key for spring security. Controller Class In this class, we”ve created a mapping for “/” endpoint and for “/login” for the index page and login page of this application. AuthController.java package com.tutorialspoint.security.formlogin.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class AuthController { @GetMapping(“/”) public String home() { return “index”; } @GetMapping(“/login”) public String login() { return “login”; } } Views Let”s create index.html in /src/main/resources/templates folder with following content to act as a home page and to display logged in user name. index.html <!DOCTYPE html> <html xmlns=”http://www.w3.org/1999/xhtml” xmlns:th=”https://www.thymeleaf.org” xmlns:sec=”https://www.thymeleaf.org/thymeleaf-extras-springsecurity3″> <head> <title> Hello World! </title> </head> <body> <h1 th:inline=”text”>Hello <span sec:authentication=”name”></span>!</h1> <form th:action=”@{/logout}” method=”post”> <input type=”submit” value=”Sign Out”/> </form> </body> <html> login.html Let”s create the login.html in /src/main/resources/templates folder with following content
Spring Security – Redirection ”; Previous Next In web application, we”re often required to land to different pages based on user profile. For example, a normal user may land on user home page whereas an admin may land on Admin console. We can achieve this requirement very easily using spring security which provides supports to handle login success and based on user role, we can decide which page to be shown to the user or simply redirect the user to the required page. In order to achieve redirection, we need to handle successHandler of formLogin in Spring Security Configuration as shown below: protected void configure(HttpSecurity http) throws Exception { http // … // key should be unique .formLogin(form -> form.loginPage(“/login”) .defaultSuccessUrl(“/”) .failureUrl(“/login?error=true”) .successHandler(authenticationSuccessHandler()) .permitAll()) // .build(); } Here authenticationSuccessHandler() method is another bean to handle login success and redirect user to the required page. @Bean public AuthenticationSuccessHandler authenticationSuccessHandler() { return new AuthenticationHandler(); } AuthenticationSuccessHandler In order to achieve redirection, we first need to create a class by implementing AuthenticationSuccessHandler as shown below. In this class, we”ve to implement onAuthenticationSuccess() method. onAuthenticationSuccess() method is called once user is logged in successfully. Now using Authentication object, we can check the role of the logged in user and then determine the redirection url. Using HttpServletResponse.sendRedirect() method, we can then redirect user to the required page. public class AuthenticationHandler implements AuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { String redirect = request.getContextPath(); if (authentication.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals(“ROLE_ADMIN”))) { redirect = “/admin”; } else if (authentication.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals(“ROLE_USER”))) { redirect = “/user”; } response.sendRedirect(redirect); } } Let us start actual programming with Spring Security. Before you start writing your first example using Spring framework, you have to make sure that you have set up your Spring environment properly as explained in Spring Security – Environment Setup Chapter. We also assume that you have a bit of working knowledge on Spring Tool Suite IDE. Now let us proceed to write a Spring MVC based Application managed by Maven, which will ask user to login, authenticate user and then provide option to logout using Spring Security Form Login Feature. Create Project using Spring Initializr Spring Initializr is great way to start with Spring Boot project. It provides a easy to use User Interface to create a project, add dependencies, select java runtime etc. It generates a skeleton project structure which once downloaded can be imported in spring tool suite and we can proceed with our readymade project structure. We”re choosing a maven project, naming the project as formlogin, with java version as 21. Following dependencies are added: Spring Web Spring Security Thymeleaf Spring Boot DevTools Thymeleaf is a templating engine for Java. It allows us to quickly develop static or dynamic web pages for rendering in the browser. It is extremely extensible and allows us to define and customize the processing of our templates in fine detail. In addition to this, we can learn more about Thymeleaf by clicking this link. Let”s move on to generate our project and download it. We then extract it to a folder of our choice and use any IDE to open it. I shall be using Spring Tools Suite 4. It is available for free downloading from the https://spring.io/tools website and is optimized for spring applications. pom.xml with all relevant dependencies Let”s take a look at our pom.xml file. It should look something similar to this − pom.xml <?xml version=”1.0″ encoding=”UTF-8″?> <project xmlns=”http://maven.apache.org/POM/4.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.3.1</version> <relativePath/> <!– lookup parent from repository –> </parent> <groupId>com.tutorialspoint.security</groupId> <artifactId>formlogin</artifactId> <version>0.0.1-SNAPSHOT</version> <name>formlogin</name> <description>Demo project for Spring Boot</description> <url/> <licenses> <license/> </licenses> <developers> <developer/> </developers> <scm> <connection/> <developerConnection/> <tag/> <url/> </scm> <properties> <java.version>21</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity6</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Spring Security Configuration Class Inside of our config package, we have created the WebSecurityConfig class. We shall be using this class for our security configurations, so let”s annotate it with an @Configuration annotation and @EnableWebSecurity. As a result, Spring Security knows to treat this class a configuration class. As we can see, configuring applications have been made very easy by Spring. WebSecurityConfig package com.tutorialspoint.security.formlogin.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; @Configuration @EnableWebSecurity public class WebSecurityConfig { @Bean protected UserDetailsService userDetailsService() { UserDetails user = User.builder() .username(“user”) .password(passwordEncoder().encode(“user123”)) .roles(“USER”) .build(); UserDetails admin = User.builder() .username(“admin”) .password(passwordEncoder().encode(“admin123”)) .roles(“USER”, “ADMIN”) .build(); return new InMemoryUserDetailsManager(user, admin); } @Bean protected PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests( request -> request.requestMatchers(“/login”).permitAll() .requestMatchers(“/**”).authenticated() ) .formLogin(form -> form.loginPage(“/login”) .defaultSuccessUrl(“/”) .failureUrl(“/login?error=true”) .successHandler(authenticationSuccessHandler()) .permitAll()) .rememberMe(config -> config.key(“123456”) .tokenValiditySeconds(3600)) .logout(config -> config .logoutUrl(“/logout”) .logoutSuccessUrl(“/login”) .invalidateHttpSession(true) .deleteCookies(“JSESSIONID”)) .build(); } @Bean public AuthenticationSuccessHandler authenticationSuccessHandler() { return new AuthenticationHandler(); } } Here we”ve used the authenticationSuccessHandler() in successHandler() method to do the required redirection. The AuthenticationHandler class should be in same package. AuthenticationHandler class Following class implements AuthenticationSuccessHandler as shown below. In this class, we”ve implemented onAuthenticationSuccess() method. onAuthenticationSuccess() method is called once user is logged in successfully. AuthenticationHandler package com.tutorialspoint.security.formlogin.config; import java.io.IOException; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; public class AuthenticationHandler implements AuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { String redirect = request.getContextPath(); if (authentication.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals(“ROLE_ADMIN”))) { redirect = “/admin”; } else if (authentication.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals(“ROLE_USER”))) { redirect = “/user”; } response.sendRedirect(redirect); } } Controller Class In this class, we”ve created a mapping for “/” endpoint and for “/login” for the index page and login page of this application. For user.html and admin.html we”ve two methods user() and admin() added. AuthController.java package com.tutorialspoint.security.formlogin.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class AuthController {
Spring Security – Introduction ”; Previous Next What is Spring Security? Spring Security is one of Spring Project or Module to secure a Spring based application. Spring security provides us many in-built features to implement authentication and authorization in our application. We can use these features with our changes to secure an application very quickly. In addition to this, Spring Security also allows plenty of customizations to the features mentioned before to implement our own complex authentications and authorizations. In addition to providing various inbuilt authentication and authorization options, Spring Security allows us to customize our authentication process as much as we want. Starting from a custom login page to our very own customized authentication providers and authentication filters, we can pretty much customize every aspect of the authentication process. We can define our own authentication process which can range from basic authentication using a username and a password to a complex one such as two-factor authentication using tokens and OTP’s. Also, we can use various databases – both relational and non-relational, use various password encoders, lock malicious users out of their accounts, and so on. Authentication and Authorization Authentication and Authorization are two main components of Spring Security. Authentication − Authentication is to ensure that the user or the client is who they claim to be. There are many ways in which Spring Security enables us to perform authentication. Spring Security supports Basic Authentication, LDAP authentication, JDBC authentication, etc. Authorization − Authorization ensures whether the user has permission for the action or not. If our application is a complex one, with different kinds of users such as admins, regular users, other less privileged users, we need to maintain access control in our application. For example, a guest user should not be able to access admin content. So, to control access to various resources within our application, we need to check if a user has permission to access that resource. Spring Security supports roles, claims etc. to provide user level authorization. Spring Security supports a large set of authentication models. Most of these authentication models are developed by third parties or by Internet Engineering Task Force, IETF as a standard body. Being able to integrate with wide set of third parties autentication models, spring security becomes very popular among developers to integrate in their projects. Spring provides its own authentication features as well. Following list shows the various authentication methods supported by Spring security. HTTP BASIC authentication headers HTTP Digest authentication headers HTTP X.509 client certificate exchange LDAP Form-based authentication OpenID authentication Authentication based on pre-established request headers JA-SIG Central Authentication Service, a open source single sign on system Transparent authentication context propagation for Remote Method Invocation (RMI) and HttpInvoker Remember Me Anonymous authentication Run-as authentication Java Authentication and Authorization Service (JAAS) JEE container autentication Kerberos Java Open Source Single Sign On (JOSSO) OpenNMS Network Management Platform AppFuse AndroMDA Mule ESB Direct Web Request (DWR) Grails Tapestry JTrac Jasypt Roller Elastic Path Atlassian Crowd We can integrate own custom authentication mechanism as well with Spring Security. History of Spring Security Spring Security started in late 2003 as The Acegi Security System for Spring as a simple Spring based security implementation. Later as spring community members enquired for an existing framework, it was assigned to one of the community member to work and by Jan 2004, a team of 20+ people started working in this project which was later established as a SourceForge project in Mar 2004. Initially spring security had not its authentication module and it was relying completely on Container managed security and Acegi security system was focusing only on authorization modules. In following year, 2005, Acegi Security specific Authentication services were introduced and Acegi Security System became an official Spring sub-project. In May 2006, after being used in numerous production softwares, community improvements and bug fixes, 1.0.0 was released. By the end of 2007, Acegi Security System was rebranded as Spring Security and it became an Official Spring Portfolio Project. Print Page Previous Next Advertisements ”;
Sprint Security – Home
Spring Security Tutorial PDF Version Quick Guide Resources Job Search Discussion In this tutorial, we will learn about Spring Security Frameworks. We will start with the basics and go through the configuration of various frameworks to work with Spring Security. We will also do some handson coding to perform CRUD operation using Spring Security Frameworks. Audience This tutorial will be useful for graduates, post graduates, and research students who either have an interest in this subject or have this subject as a part of their curriculum. The reader can be a beginner or an advanced learner. Prerequisites Though there is NO mandatory requirement to have for this tutorial. However, if you have any or all (supercool) prior knowledge on any below mentioned technologies that will be an added advantage − About 30 minutes Basic Spring Security knowledge A Basic understanding of the Apache Solr Database. A java based IDE (Eclipse, STS or IntelliJ IDEA) JDK 1.8 or later Gradle 4+ or Maven 3.2+ Apache Solr installed Print Page Previous Next Advertisements ”;
Spring Security – Taglibs
Spring Security – Taglibs ”; Previous Next In Spring MVC applications using JSP, we can use the Spring Security tags for applying security constraints as well as for accessing security information. Spring Security Tag library provides basic support for such operations. Using such tags, we can control the information displayed to the user based on his roles or permissions. Also, we can include CSRF protection features in our forms. To use Spring security tags, we must have the security taglib declared in our JSP file. <%@ taglib prefix=”sec” uri=”http://www.springframework.org/security/tags” %> Now, we can use Spring Security tags with the sec prefix. Let”s now see the usage of the tags. The authorize Tag The first tag we will be discussing is the authorize tag. Let’s check out some usage examples. <sec:authorize access=”!isAuthenticated()”> Login </sec:authorize> <sec:authorize access=”isAuthenticated()”> Logout </sec:authorize> <sec:authorize access=”hasRole(”ADMIN”)”> Hello Admin. </sec:authorize> As we can see, we can use this tag to hide or show sections of information based on access or roles. hasRole(ADMIN) − evaluates to true if the current user has the admin role. hasAnyRole(‘ADMIN’,’USER’) − evaluates to true if the current user has any of the listed roles isAnonymous() − evaluates to true if the current user is an anonymous user isRememberMe() − evaluates to true if the current user is a remember-me user isFullyAuthenticated() − evaluates to true if the user is authenticated and is neither anonymous nor a remember-me user As we can see, the access attribute is where the web-security expression is specified. Then, Spring Security evaluates the expression. The evaluation is generally delegated to SecurityExpressionHandler<FilterInvocation>, which is defined in the application context. If it returns true, then the user can get access to the information given in that section. If we use the authorize tag with Spring Security ‘s Permission Evaluator, we can also check user permissions as given below − <p sec:authorize=”hasPermission(#domain,”read”) or hasPermission(#domain,”write”)”> This content is visible to users who have read or write permission. </p> We can also allow or restrict the user from clicking on certain links within our content. <a sec:authorize href=”/admin”> This content will only be visible to users who are authorized to send requests to the “/admin” URL. </agt; The authentication tag When we want access to the current Authentication object stored in the Spring Security Context, we can use the authentication tag. Then we can use it to render properties of the object directly in our JSP page. For example, if we want to render the principal property of the Authentication object in our page, we can do it as follows − <p sec:authentication=”name” /> The csrfInput Tag We can use the csrfInput tag to insert a hidden form field with the correct values for the CSRF protection token when CSRF protection is enabled. If CSRF protection is not enabled, this tag outputs nothing. We can place the tag within the HTML <form></form> block along with other input fields. However, we must not place the tag within the <form:form></form:form> block as Spring Security automatically inserts a CSRF form field within those tags and also takes care of Spring forms automatically. <form method=”post” action=”/do/something”> <sec:csrfInput /> Username:<br /> <input type=”text” username=”username” /> … </form> The csrfMetaTags Tag We can use this tag to insert meta tags which contain the CSRF protection token form field and header names and CSRF protection token value. These meta tags can be useful for employing CSRF protection within Javascript in our application. However, this tag only works when we have enabled CSRF protection in our application, otherwise, this tag outputs nothing. <html> <head> <title>CSRF Protection in Javascript</title> <sec:csrfMetaTags /> <script type=”text/javascript” language=”javascript”> var csrfParam = $(“meta[name=”_csrf_param”]”).attr(“content”); var csrfToken = $(“meta[name=”_csrf”]”).attr(“content”); </script> </head> <body> … </body> </html> Let us start actual programming with Spring Security. Before you start writing your example using Spring framework, you have to make sure that you have set up your Spring environment properly as explained in Spring Security – Environment Setup Chapter. We also assume that you have a bit of working knowledge on Spring Tool Suite IDE. Now let us proceed to write a Spring MVC based Application managed by Maven, which will ask user to login, authenticate user and then provide option to logout using Spring Security Form Login Feature. Create Project using Spring Initializr Spring Initializr is great way to start with Spring Boot project. It provides a easy to use User Interface to create a project, add dependencies, select java runtime etc. It generates a skeleton project structure which once downloaded can be imported in spring tool suite and we can proceed with our readymade project structure. We”re choosing a maven project, naming the project as formlogin, with java version as 21. Following dependencies are added: Spring Web Spring Security Thymeleaf Spring Boot DevTools Thymeleaf is a templating engine for Java. It allows us to quickly develop static or dynamic web pages for rendering in the browser. It is extremely extensible and allows us to define and customize the processing of our templates in fine detail. In addition to this, we can learn more about Thymeleaf by clicking this link. Let”s move on to generate our project and download it. We then extract it to a folder of our choice and use any IDE to open it. I shall be using Spring Tools Suite 4. It is available for free downloading from the https://spring.io/tools website and is optimized for spring applications. pom.xml with all relevant dependencies Let”s take a look at our pom.xml file. It should look something similar to this − pom.xml <?xml version=”1.0″ encoding=”UTF-8″?> <project xmlns=”http://maven.apache.org/POM/4.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.3.1</version> <relativePath/> <!– lookup parent from repository –> </parent> <groupId>com.tutorialspoint.security</groupId> <artifactId>formlogin</artifactId> <version>0.0.1-SNAPSHOT</version> <name>formlogin</name> <description>Demo project for Spring Boot</description> <url/> <licenses> <license/> </licenses> <developers> <developer/> </developers> <scm> <connection/> <developerConnection/> <tag/> <url/> </scm> <properties> <java.version>21</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity6</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId>
Spring Security – Logout
Spring Security – Logout ”; Previous Next Logout is an important function, so that a user is required to login to access any secured resource once user has logged out or signed out or its current session is invalidated for any reason. Spring security provides a default logout functionality as we”ve seen in Spring Security – Form Login chapter. A logout functionality performs following important functions. Invalidates the Http session, and unbinds objects bound to the session. It clears the remember-me cookie. Removes the authentication from Spring’s Security context. A logout can be explicitly configured as given below − protected void configure(HttpSecurity http) throws Exception { http // … .logout(config -> config .logoutUrl(“/logout”) .logoutSuccessUrl(“/login”)) .build(); } Important Methods Following are important methods that we can configure in logout() method. logoutUrl (“/logout”) − This will be used to logout from our application. It has default value as logout and can be changed to any other custom value. logoutSuccessUrl (“/login”) − This will be used to load login page once user is successfully logged out. invalidateHttpSession (“true”) − This is used to invalidate the session. By default, it is true so that when user it logged out, its session is invalidated. We can mark it false to keep the session alive even after logout. deleteCookies (“JSESSIONID”) − This is used to clear remember-me cookie. logoutSuccessHandler(logoutSuccessHandler()); − This method is used when we need to perform some action at the time user logs out from the application. Let us start actual programming with Spring Security. Before you start writing your first example using Spring framework, you have to make sure that you have set up your Spring environment properly as explained in Spring Security – Environment Setup Chapter. We also assume that you have a bit of working knowledge on Spring Tool Suite IDE. Now let us proceed to write a Spring MVC based Application managed by Maven, which will ask user to login, authenticate user and then provide option to logout using Spring Security Form Login Feature. Create Project using Spring Initializr Spring Initializr is great way to start with Spring Boot project. It provides a easy to use User Interface to create a project, add dependencies, select java runtime etc. It generates a skeleton project structure which once downloaded can be imported in spring tool suite and we can proceed with our readymade project structure. We”re choosing a maven project, naming the project as formlogin, with java version as 21. Following dependencies are added: Spring Web Spring Security Thymeleaf Spring Boot DevTools Thymeleaf is a templating engine for Java. It allows us to quickly develop static or dynamic web pages for rendering in the browser. It is extremely extensible and allows us to define and customize the processing of our templates in fine detail. In addition to this, we can learn more about Thymeleaf by clicking this link. Let”s move on to generate our project and download it. We then extract it to a folder of our choice and use any IDE to open it. I shall be using Spring Tools Suite 4. It is available for free downloading from the https://spring.io/tools website and is optimized for spring applications. pom.xml with all relevant dependencies Let”s take a look at our pom.xml file. It should look something similar to this − pom.xml <?xml version=”1.0″ encoding=”UTF-8″?> <project xmlns=”http://maven.apache.org/POM/4.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.3.1</version> <relativePath/> <!– lookup parent from repository –> </parent> <groupId>com.tutorialspoint.security</groupId> <artifactId>formlogin</artifactId> <version>0.0.1-SNAPSHOT</version> <name>formlogin</name> <description>Demo project for Spring Boot</description> <url/> <licenses> <license/> </licenses> <developers> <developer/> </developers> <scm> <connection/> <developerConnection/> <tag/> <url/> </scm> <properties> <java.version>21</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity6</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Spring Security Configuration Class Inside of our config package, we have created the WebSecurityConfig class. We shall be using this class for our security configurations, so let”s annotate it with an @Configuration annotation and @EnableWebSecurity. As a result, Spring Security knows to treat this class a configuration class. As we can see, configuring applications have been made very easy by Spring. WebSecurityConfig package com.tutorialspoint.security.formlogin.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class WebSecurityConfig { @Bean protected UserDetailsService userDetailsService() { UserDetails user = User.builder() .username(“user”) .password(passwordEncoder().encode(“user123”)) .roles(“USER”) .build(); UserDetails admin = User.builder() .username(“admin”) .password(passwordEncoder().encode(“admin123”)) .roles(“USER”, “ADMIN”) .build(); return new InMemoryUserDetailsManager(user, admin); } @Bean protected PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests( request -> request.requestMatchers(“/login”).permitAll() .requestMatchers(“/**”).authenticated() ) .formLogin(form -> form.loginPage(“/login”) .defaultSuccessUrl(“/”) .failureUrl(“/login?error=true”) .permitAll()) .logout(config -> config .logoutUrl(“/logout”) .logoutSuccessUrl(“/login”) .invalidateHttpSession(true) .deleteCookies(“JSESSIONID”)) .build(); } } Here we”ve mentioned the logout url to be used logout which is a default url provided by spring security. We are not required to create a special logout page for it. Similarly once user is logged out, user will be shown the login page which is standard practice. Controller Class In this class, we”ve created a mapping for “/” endpoint and for “/login” for the index page and login page of this application. AuthController.java package com.tutorialspoint.security.formlogin.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class AuthController { @GetMapping(“/”) public String home() { return “index”; } @GetMapping(“/login”) public String login() { return “login”; } } Views Let”s create index.html in /src/main/resources/templates folder with following content to act as a home page and to display logged in user name. index.html <!DOCTYPE html> <html xmlns=”http://www.w3.org/1999/xhtml” xmlns:th=”https://www.thymeleaf.org” xmlns:sec=”https://www.thymeleaf.org/thymeleaf-extras-springsecurity3″> <head> <title> Hello World! </title> </head> <body> <h1 th:inline=”text”>Hello <span sec:authentication=”name”></span>!</h1> <form th:action=”@{/logout}” method=”post”> <input type=”submit” value=”Sign Out”/> </form> </body> <html> Here we”ve used a form with a submit button to logout the user. <form th:action=”@{/logout}” method=”post”> <input type=”submit” value=”Sign Out”/> </form> We can use a link as well as well as shown below: <a href=”/logout” alt=”logout”>Sign Out</a> login.html Let”s create the
Spring Security – Basic Authentication ”; Previous Next We”ve seen form based login so far where an html based form is used for Username/password authentication. We can either create our own custom login form or use spring security provided default login form. There is another way to ask username/password where we can ask user to pass username/password in the url itself using basic authentication. In case of Web browse, whenever a user requests a protected resource, Spring Security checks for the authentication of the request. If the request is not authenticated/authorized, the user will be asked for username/password using default dialog as shown below: Spring Security provides following configuration to achieve basic authentication − protected void configure(HttpSecurity http) throws Exception { http // … .authorizeHttpRequests(request -> request.anyRequest().authenticated()) .httpBasic(Customizer.withDefaults()) .build(); } Here we”re configuring spring security for every request to be authenticated using basic authentication mechanism. Let us start actual programming with Spring Security. Before you start writing your first example using Spring framework, you have to make sure that you have set up your Spring environment properly as explained in Spring Security – Environment Setup Chapter. We also assume that you have a bit of working knowledge on Spring Tool Suite IDE. Now let us proceed to write a Spring MVC based Application managed by Maven, which will ask user to login, authenticate user and then provide option to logout using Spring Security Form Login Feature. Create Project using Spring Initializr Spring Initializr is great way to start with Spring Boot project. It provides a easy to use User Interface to create a project, add dependencies, select java runtime etc. It generates a skeleton project structure which once downloaded can be imported in spring tool suite and we can proceed with our readymade project structure. We”re choosing a maven project, naming the project as formlogin, with java version as 21. Following dependencies are added: Spring Web Spring Security Thymeleaf Spring Boot DevTools Thymeleaf is a templating engine for Java. It allows us to quickly develop static or dynamic web pages for rendering in the browser. It is extremely extensible and allows us to define and customize the processing of our templates in fine detail. In addition to this, we can learn more about Thymeleaf by clicking this link. Let”s move on to generate our project and download it. We then extract it to a folder of our choice and use any IDE to open it. I shall be using Spring Tools Suite 4. It is available for free downloading from the https://spring.io/tools website and is optimized for spring applications. pom.xml with all relevant dependencies Let”s take a look at our pom.xml file. It should look something similar to this − pom.xml <?xml version=”1.0″ encoding=”UTF-8″?> <project xmlns=”http://maven.apache.org/POM/4.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.3.1</version> <relativePath/> <!– lookup parent from repository –> </parent> <groupId>com.tutorialspoint.security</groupId> <artifactId>formlogin</artifactId> <version>0.0.1-SNAPSHOT</version> <name>formlogin</name> <description>Demo project for Spring Boot</description> <url/> <licenses> <license/> </licenses> <developers> <developer/> </developers> <scm> <connection/> <developerConnection/> <tag/> <url/> </scm> <properties> <java.version>21</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity6</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Spring Security Configuration Class Inside of our config package, we have created the WebSecurityConfig class. We shall be using this class for our security configurations, so let”s annotate it with an @Configuration annotation and @EnableWebSecurity. As a result, Spring Security knows to treat this class a configuration class. As we can see, configuring applications have been made very easy by Spring. WebSecurityConfig package com.tutorialspoint.security.formlogin.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class WebSecurityConfig { @Bean protected UserDetailsService userDetailsService() { UserDetails user = User.builder() .username(“user”) .password(passwordEncoder().encode(“user123”)) .roles(“USER”) .build(); UserDetails admin = User.builder() .username(“admin”) .password(passwordEncoder().encode(“admin123”)) .roles(“USER”, “ADMIN”) .build(); return new InMemoryUserDetailsManager(user, admin); } @Bean protected PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(request -> request.anyRequest().authenticated()) .httpBasic(Customizer.withDefaults()) .build(); } } Configuration Class Details Let”s take a look at our configuration class. First, we shall create a bean of our UserDetailsService class by using the userDetailsService() method. We shall be using this bean for managing our users for this application. Here, to keep things simple, we shall use an InMemoryUserDetailsManager instance to create users. These users, along with our given username and password, are mapped to User and Admin roles respectively. Password Encoder Now, let”s look at our PasswordEncoder. We shall be using a BCryptPasswordEncoder instance for this example. Hence, while creating the user, we used the passwordEncoder to encode our plaintext password like this: .password(passwordEncoder().encode(“user123″)) Http Security Configuration After the above steps, we move on to our next configuration. Here, we”ve defined the filterChain method. This method takes HttpSecurity as a parameter. We shall be configuring this to use our form login and logout function. We can observe that all these functionalities are available in Spring Security. Let’s study the below section in detail − http .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(request -> request.anyRequest().authenticated()) .httpBasic(Customizer.withDefaults()) .build(); There are a few points to note here − We have disabled csrf or Cross-Site Request Forgery protection As this is a simple application only for demonstration purposes, we can safely disable this for now. Then we add configuration which requires all requests to be authenticated. After that, we”re using httpBasic() functionality of Spring Security as mentioned above. This makes browser to ask for username/password. In case of rest API, we”can set authetication as Basic Auth as we shall see later in this section. Controller Class In this class, we”ve created a mapping for single “/” endpoint for the index page of this application, for simplicity. This will redirect to index.html. AuthController package com.tutorialspoint.security.formlogin.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class AuthController { @GetMapping(“/”) public String home() { return “index”; } } Views Create
Spring Security – Useful Resources ”; Previous Next The following resources contain additional information on Spring Security. Please use them to get more in-depth knowledge on this. Useful Links on Spring Security Spring Security Wiki − Wikipedia Reference for Spring Security. Spring Security − Official website of Spring Security. Useful Books on Spring Security To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;