Spring REST API -Part 3: Spring Security (Basic Authentication) | by Zia khalid | Medium

Basic Authentication Demo

For demo purposes, we can write a simple REST API given below.

1. REST API

@RestController
@RequestMapping(path = "/employees")
public class EmployeeController
{
    @Autowired
    private EmployeeDAO employeeDao;

    @GetMapping(path="/", produces = "application/json")
    public Employees getEmployees()
    {
        return employeeDao.getAllEmployees();
    }
}

Authentication vs authorization

Authentication is the process of verifying who you are, while authorization is the process of verifying what you have access to.

Basicauthsecurityconfig.java

@Profile annotation indicates that a component is eligible for registration when one or more specified profiles are active. Here, Basic authentication will be enabled only when the application is run with “BasicAuth” profile.

Create product

Click on the Create Product endpoint and click on “Try it out” and then execute

Environment setup

1. JDK 8
2. Spring Boot
3. Intellij Idea/ eclipse
4. Maven

Get an api token

Basic auth requires API tokens. You generate an API token for your Atlassian account and use
it to authenticate anywhere where you would have used a password. This enhances security because:

  • you’re not saving your primary account password outside of where you authenticate
  • you can quickly revoke individual API tokens on a per-use basis
  • API tokens will allow you to authenticate even if your Atlassian Cloud organization has two-factor
    authentication or SAML enabled.

See the Atlassian Cloud Support API tokens@Beanpublic WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Overridepublic void addCorsMappings(CorsRegistry registry) {
registry.addMapping(“/**”).allowedMethods(“GET”, “POST”, “PUT”, “DELETE”).allowedOrigins(“*”)
.allowedHeaders(“*”);
}
};
}

MethodSecurityConfig.java
By using @EnableGlobalMethodSecurity we can easily secure our methods with Java configuration. It provides AOP security on methods, some of the annotations it will enable are PreAuthorize and PostAuthorize.
Next Article
Part 4.1: Spring Controllers (RestController — GET)
Overview
The Jira REST API is protected by the same restrictions that apply in the standard Jira web interface.
These restrictions mean that if you don’t log in, you access Jira anonymously. If you log in and don’t
have permission to view something in Jira, you won’t be able to view it using the Jira REST API either.
Part 3: Spring Security (Basic Authentication)
Note — Codes in the story is in continuation to the previous parts, so if you feel uncomfortable or disconnected please check the previous parts or navigate through git commit to have a better understanding. In this part we will secure REST API using Basic Authentication. What is Basic Authentication?
Profiles.java
This class is used to define various Spring profiles. For now, let us create a constant for basicauth profile
Rest Template with Basic Authentication Example
Initially, we used POSTMAN as a client to call our REST APIs. But in a real scenario, we won’t be using POSTMAN, you will have to call these APIs programmatically. We will create a class RestClient and that will call our APIs while building Basic Authentication.
Role.java
@Getter and @Setter annotations are used to generate getter and setter methods respectively. @Data annotation should not be used here since we have implemented hashCode and equals methods.
Run Application
1. Run Application.java as a java application 2. Launch postman
Secure method with Preauthorize annotation
@PreAuthorize annotation is used to specify a method access-control expression which will be evaluated to decide whether a method invocation is allowed or not Annotate the updateProduct method in ProductController with @PreAuthorize annotation
Source Code
As always, you can get the source code from the Github below
Spring Bean Configuration
SpringBootServletInitializer enables process used in Servlet 3.0 using web.xml @SpringBootApplication: This is a convenience annotation that is equivalent to declaring @Configuration @EnableAutoConfiguration and @ComponentScan. Application.java
Spring Boot 2 Basic Authentication
There are certain changes required to run this app with spring boot 2. With spring boot 2, you need to Bcrypt the password.To make use of Bcrypt, first we need to define
a Bean of BCryptPasswordEncoder as follow or else it throws error as PasswordEncoder mapped for the id “null”
@Bean
public BCryptPasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
Next, we require to Bcrypt our plain-text password in configureGlobal() method. You can use this online Bcrypt tool to generate Bcrypt password.Else,
you will be getting this error Encoded password does not look like BCrypt
SwaggerConfig.java
In order to enable Basic Authentication in Swagger-UI, we need to configure the Security Schemes and Security Contexts for Swagger as highlighted below package com.javachinna.config;

Похожее:  Потребителям | Пятигорсктеплосервис

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.BasicAuth;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
private static final String BASIC_AUTH = “basicAuth”;

@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage(“com.javachinna”)).paths(PathSelectors.any()).build().apiInfo(apiInfo())
.securitySchemes(securitySchemes()).securityContexts(List.of(securityContext()));
}

private ApiInfo apiInfo() {
return new ApiInfo(“Product REST API”, “Product API to perform CRUD opertations”, “1.0”, “Terms of service”,
new Contact(“Java Chinna”, “www.vhod-v-lichnyj-kabinet.ru”, “[email protected]”), “License of API”, “API license URL”, Collections.emptyList());
}

private List<SecurityScheme> securitySchemes() {
return List.of(new BasicAuth(BASIC_AUTH));
}

private SecurityContext securityContext() {
return SecurityContext.builder().securityReferences(Arrays.asList(basicAuthReference())).forPaths(PathSelectors.any()).build();
}

private SecurityReference basicAuthReference() {
return new SecurityReference(BASIC_AUTH, new AuthorizationScope[0]);
}
}

Conclusion
That’s all folks! In this article, you’ve learned how to implement basic authentication for Spring Boot RESTful services. I hope you enjoyed this article. Thank you for reading. Read Next:9 Steps to Secure Spring Boot 2 REST API with Spring Security 5 JWT Authentication, Role based Authorization and MySQL Database
Maven Dependencies
spring-boot-starter-parent: provides useful Maven defaults. It also provides a dependency-management section so that you can omit version tags for existing dependencies. spring-boot-starter-web: includes all the dependencies required to create a web app. This will avoid lining up different spring common project versions. spring-boot-starter-tomcat: enable an embedded Apache Tomcat 7 instance, by default. We have overriden this by defining our version. This can be also marked as provided if you wish to deploy the war to any other standalone tomcat. spring-boot-starter-security: take care of all the required dependencies related to spring security. pom.xml
1. Maven Dependency
The simplest way to add all required jars is to add the latest version of spring-boot-starter-security dependency.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *