Wednesday, 31 July 2019

Basic Authentication using the Spring boot

Spring Security
Spring Security provides comprehensive security services for J2EE-based enterprise software applications. 

Terms to get familiar in spring security.

Principal:means a user, device or some other system which can perform an action in your application.

Authentication:It is the process of establishing a principal is who they claim to be.

Authorization:It refers to the process of deciding whether a principal is allowed to perform an action within your application.

UserRoles: User Roles are created to make sure the services which are created are not accessed by all the users. It is like we provide the restriction to the user, so he / she cannot access the particular service.

class WebSecurityConfigurerAdapter:Provides a convenient base class for creating a WebSecurityConfigurer instance. The implementation allows customization by overriding methods.

Now we can jump in to creating the basic authentication using the Spring boot.

Create a project from spring initializer, add the dependencies like web and security.

Here is My 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 http://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>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.searchendeca</groupId>
<artifactId>securehttp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>securehttp</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</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-web</artifactId>
</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>

Here is my Security Configuration.

package com.searchendeca.securehttp.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user1").password("user1").roles("USER");
        auth.inMemoryAuthentication().withUser("user2").password("user2").roles("USER", "ADMIN");
        auth.inMemoryAuthentication().withUser("user3").password("user3").roles("USER");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().
                realmName("spring-app").
                and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
                and().csrf().disable().
                authorizeRequests().antMatchers("/user/**").permitAll().anyRequest().authenticated();

    }

    @Bean
    public NoOpPasswordEncoder passwordEncoder()
    {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }
}

Controller Class.

@RestController
public class RestApiController {

 @RolesAllowed({"ROLE_USER", "ROLE_ADMIN"})
 @GetMapping(value = "/user/message")
    public String greetUser() {
        return "Welcome User ";
    }
}
The Above main class can be accessed by both user and admin respectively.
Main Class.
package com.searchendeca.securehttp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = "com.searchendeca.*")
public class SecurehttpApplication {

public static void main(String[] args) {
SpringApplication.run(SecurehttpApplication.class, args);
}

}

Deploy the application in Tomcat

Execute and access the below Url:http://localhost:8080/user/message It asks for the user name and password, once if you enter username and password then you will be able to see the service working else you will not see this .

you can also encrypt the password in the following format(username:password) with base64 and pass as header Authorization.

eg: Authorization:Basic c3llZDp0ZXN0MTIz

Still it will work in the same way. Once you include the spring security module you can see while server startup. Using generated security password: 6a1abb58-cfd9-4e7a-bb1f-ae9f0950c8b6

If you are not defining the configure method then you can access the resources by giving the username as user and password as encrypted that was updated during the server startup.

Happy Learning!!!

No comments:
Write comments