Saturday, May 1, 2021

Securing Spring Applications against Common Security Threats

 Description:

1)Spring Security protects your application from many common security threats right out of the box. You don't have to re-invent the wheel for the same but the problem is usually developer tends to ignore it but spring security framework provides protection against those threats right out the of the box it just matters how you tend to implement it.

 2)In fact the increased adoption of such frameworks has resulted in significant declines in occurrences of many of the threats.

 3)In Spring Framework: Securing Spring Applications against Common Security Threat like Man of the Middle Attack, Cross-site scripting, and many more. you should learn how to configure Spring Security with Spring Boot to get security up and running from the very get-go of your project. So here I am basically telling you how to deal with these common threats without much effort and you just need to configure your spring app correctly you just need the skills and knowledge of Spring Security needed to effectively secure your application against common security threats.

 I am mentioning a few of the security risks and threats to any spring boot-based application effectively. These are very common threats but very effective So before disabling anything in spring, make sure you are confident and are aware of the risks to your users before going ahead.

1)HTTP Headers: The First Line of Defense
2)The Cache-Control Header
3)MIME Type Sniffing and Browser XSS Protection
4)Understanding Spring Security Cross-Site Request Forgery
5)Default Clickjacking Protection
6)Additional Optional Security Headers
7)Spring Securities HTTP Firewall

The main takeaway from this is just don't try to reinvent the wheel.
Increased adoption of frameworks like Spring Security has resulted in many of the common security threats like cross‑site scripting, cross‑site request forgery, dropping out of the OWASP top 10 as you're getting a lot of protection right out of the box, often threats you don't even know about. 
Spring Security is very configurable, and it's easy to unintentionally disable some of the default security protection. Hence, before disabling anything, make sure you are confident and are aware of the risks to your users before going ahead.

This will give you the foundational knowledge required to customize the framework in the spring boot app.
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.mvcMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.and()
.logout();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("abhinaw").password("{noop}password").roles("USER");
auth.inMemoryAuthentication().withUser("tripathi").password("{noop}password").roles("ADMIN");
}

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/css/**", "/webjars/**");
}

}

@Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(redirectConnector());
return tomcat;
}

private Connector redirectConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setRedirectPort(8443);
return connector;
}

@Controller
public class LoginController {

@GetMapping("/login")
public String login() {
return "login";
}

}

public class AuthenticationUtil {

public static String getUsername() {
UserDetails user = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return user.getUsername();
}
}

Below is my YAML file:

server:
port: 8443
ssl:
key-store-password: ENC(8e+G1W2rkvi1EglUn6uTheBzZ4IY2hhl)
key-store: classpath:keystore.p12
key-store-type: PKCS12
key-alias: tomcat

logging:
level:
root: INFO
com.memorynotfound: INFO
org.springframework.web: INFO
org.springframework.security: INFO

jasypt:
encryptor:
password: password
iv-generator-classname: org.jasypt.iv.NoIvGenerator
algorithm: PBEWithMD5AndTripleDES

For detailed implementation you can check out my GitHub code for better understanding:

Git Hub URL: https://github.com/Abhinaw/SpringSecirityAgainstCommonThreats

Just visit and check out the code and you will understand correctly. 



Monday, March 29, 2021

Part-3 Ktor Kotlin MySQL Integration tutorial - Best Practices Code

 Here you will learn how to integrate MYSQL with Ktor using Kotlin Need to create Database Screen-shots attached for reference.

Below is my Github URL:
https://github.com/Abhinaw/MySqlKtorTutorial




Get All Todos response coming from database:

http://localhost:8081/todos

[ { "id": 2, "title": "Test todo #2", "done": true }, { "id": 3, "title": "Record Video #6", "done": true }, { "id": 4, "title": "Todo Test #4", "done": true } ]

Part-2 Middle-Tier Implementation with #Ktor #kotlindeveloper

Working demo with best practices with proper handling GET, POST, PUT, DELETE operation. You can request JSON and get a response as JSON.

Below is the Github URL:

https://github.com/Abhinaw/KtorEnhancedTutorialRequestResponseDemo

Here you can see live request and response that you are making through the postman . you can perform add,delete,update in the code below is the working example that i performed:

GET:

http://localhost:8081/todos [ { "id": 2, "title": "Record Video", "done": true }, { "id": 3, "title": "Record Video #4", "done": true }, { "id": 4, "title": "Record Video", "done": true }, { "id": 5, "title": "Record Video", "done": true }, { "id": 6, "title": "Record Video", "done": true }, { "id": 7, "title": "Record Video", "done": true }, { "id": 8, "title": "Record Video", "done": true } ]

POST: http://localhost:8081/todos request: { "title": "Record Video", "done": true } response: { "id": 8, "title": "Record Video", "done": true }

PUT: http://localhost:8081/todos/3

request: { "title": "Record Video #4", "done": true }

response: 200OK

DELETE:

http://localhost:8081/todos/1

request: { "title": "Record Video", "done": true } response: 200OK



Part-1 Building Middle-Tier in Kotlin Using Ktor #kotlin #Ktor

 Very Simple Working Code Example. Below is my GitHub URL

https://github.com/Abhinaw/Kotlin_Ktor_Demo_App

Many web applications and services are built using the Spring Framework. While Spring is incredibly powerful and Kotlin is useful nobody can accuse it of being lightweight because of the benefits it has such as support of immutable data and null detection, as well as having less of the bloat of Java. Bring these two together, a lightweight HTTP framework and a nice programming language and you get Ktor. It is heavily based on Kotlin coroutines and so supports a high degree of asynchrony. I have tried to write as much as possible easy code for all so that everyone can understand it.


Saturday, October 31, 2020

What are some skills possessed by software engineers at big companies like Google, Samsung, Amazon Facebook etc that software engineers at no-name companies usually don’t have?


This blog is not technical and I was having a fever so can't open a laptop but thanks to the phone they also do their work wisely.

I have worked and interviewed several times with this big, small, mid damn every size of companies and there is a difference and it is a very thin line. Let me explain.

I am working in software engineering for the last 10 years. I come from a no-name college in India, and my grades weren’t stellar. SO, getting into top tier companies was hard for me. Over 10 years, I’ve worked my way up, and I was in Samsung , IndiGo and after that got opportunity to work for (Amazon, Google) Big Companies etc.

 On the way, I have worked in all kinds of companies: startups, mid sized companies, large multi nationals; and in all kinds of industries: consumer goods, healthcare, finance, education

First of all, Companies are tiered in terms of the skill levels of their engineers. They pretend not to be. Everyone claims that they hire the smartest engineers. WHat they mean is that they hire the smartest engineers that they can get. There is a definite differrence in Engineers working in FAANG companies (Facebook, Amazon, Apple, Netflix, Google), I’ve seen all kinds of engineers beleive me and I was the only one worked in between the IIT'ns with respect.

Here’s the kicker. The biggest difference isn’t in the quality of the code that they write. FAANG engineers, on the whole, write as buggy code as engineers in decent companies.

The biggest differentiator is Communication. When I was in mid-tier companies, I was constantly finding myself explaining and re-explaining things in great detail. In fact, I would say that at most companies at mid-tier level, your success as an engineer depends on being able to drive people in the right direction by communicating to them.

There are 3 kind of people in tech. 

There are

 a) arguers:- people who will fight every point of view that isn’t their own, 

b) receivers: people who will try their best to understand what you are saying

 c) analyzers: people who start thinking critically while you are talking to them.

 Arguers are toxic. Receivers are good but slow. Analyzers are good and fast.

In mid tier companies, you are more likely to find Arguers and Receivers, whereas in top-tier companies, you are more likely to find Receivers and Analyzers.

To be a successful tech company, you need to get in as many Analyzers as you can. Because these are the people who generate ideas. These are the people you give 2 and 2 and they figure out how to make 8. Not only that, with ANalyzers, you have to spend less time getting the team on the same page. 

Less miscommunication = Less rework = shorter turnaround = lower time to market = win.

Just to be clear, I’m not saying communication is bad. Communication is good. You need to make sure everyone understands what needs to be done. Communication is essential. All I’m saying is that in top tier companies, communication is lot more efficient.

And that is the biggest difference. I have seen and also was a part of it as a analyzer.

Sunday, October 18, 2020

Analysis of Algorithm - Java

 

I was getting comments on it to explain the concept. I have tried to capture my concept on paper but it could have better on video and will upload the video ASAP.

Analysis of the algorithm:

In this article, I will try to give you brief in the easiest way possible and also write 3 functions/methods that return the sum of first n natural numbers and using these functions I will explain the concept of it. It is very basic but very important to understand others you will be confused like what is the difference between Big O of N and Theta of  N. Most people fail to explain it. here I will stick to my topic and will try not to go beyond.

and analyze these different functions in detail and compare them with each other on the basis of the time taken by them individually.

Let's understand the analysis with this example.

Given a number n, write a function/method to find the sum of first n natural numbers. very simple right?

I/P= n= 3

O/P = 6

I/P= n= 5

O/P = 15

So it is like if n =3 then 1+2+3 = 5 sum of first natural numbers right?

And if n =5 then it is like 1+2+3+4+5 =15

So now I am gone a write 3 different solutions for this program and try to analyze it.

Soution 1 :

int fun(int n)

{

  return n*(n+1)/2 ;

}

What it does?:

it simply uses the formula of first n natural numbers So like the first 3 natural numbers you will do like 3*(3+1)/2 = 6

Solution 2:

int fun2(int n)

{

  int sum = 0;

  for(int i=0;i<=n ; i++)

  {

    sum = sum + i ;

  }

  return sum;

}

What it does?

is like simply runs a loop to sum numbers from 1 to n. 

Solution 3:

int fun3(int n)

{

  int sum =0;

  for(int  i=1 ; i<=n ; i++)

      for(int j=1 ; j<=i; j++)

  sum ++;

 return sum;   

}

what it does?

it goes from i to 1 to n and for every i it increments the sum by i times.

1 + (1+1) + (1+1+1) for n =3 

Now how would you decide which one is better among all these functions?

The analysis which handles all these 3 functions is called Asymptotic analysis and basically, we measure the order of growth of a program or an algorithm in terms of input size.

So here I am writing an expression for the time taken by these 3 different functions

fun1() - > c1

fun2() - > c2n + c3

fun3() - > c4n^2 + c5n + c6

where c1,c2,c5,c6 all are constants 

n = input size for the program.

Now I am going to tell you how to get these expressions. So the first function does the constant work however how? like if you pass n = 10000 then also it will compute like

10000*(10000 + 1)/2 right? and even if you pass 100 it will do the same way right? So no matter what you pass as input size the number of operations you are doing is constant and it is not dependent upon the value of its input size And what operations you are doing So what are the operations here you are doing is like one initiation, one multiplication, and one division right?

these 3 operations are not dependent upon anything it will be the same for 10, 100, 1000, 1000000, etc right? and that is why I have written constant C1 on the above expression for that function .

Now let see function2 and think why we do get c2n + c3 SO in this function we do some constant amount of work here like 

int fun2(int n)

{

  int sum = 0;                  // 1) this is a constant work right?

  for(int i=0;i<=n ; i++)       //2) the initialization of i is also constant work

  {

    sum = sum + i ;             // 3)Similarly it is also a constant work 

  }

  return sum;

}

So why I am always saying constant work because it will always happen exactly once whether you pass n = 10, n= 1000, n =1000000000, etc. it will not depend on input size right? but there is some work which depends upon the input size n. 

sum = sum + i  // this will execute the 100 times if n=100 and ten thousands time if n = 10,000 right?

 Similarly this for(int i=0;i<=n ; i++) // this i++ will  also depend upon the input size of the n . it will also increment based on the input size right?

 Similarly, the condition checks i<=n will also depend on the input size right?

 So there is some work which happens constant times So if I write it C2 time and the rest of the work is constant time So we can write  it as C2n + C3

Now analyze the function 3 what happens in this case is 

int fun3(int n)

 {

  int sum =0;

  for(int  i=1 ; i<=n ; i++)

      for(int j=1 ; j<=i; j++)

  sum ++;    

  return sum;   

 }

this sum ++ is going to happen how many times? It will happen n * (n+1)/2 times right? If you notice the program the inner loop will run for  i=1 for 1 time and i=2 for 2 times and so on right? So it is going to run 1 + (1+1) + (1+ 1+ 1) So ultimately you have an expression which runs 

 n *(n + 1)/2 and you have more expression like you constant works also right So we can write it as 

 n*(n+1)/2 + Constant

 So now whenever you think of analysis of algorithm always think of the size of input which is larger than or equal to zero because your input size can never be negative.

 And also the time taken by the function be should greater than or equal to zero because your algorithm or program can never take a negative time.

 So now see the static analysis all those above programs may work faster for small input size may be the function 2 or function 3 works faster for the small input size but when you increment the input size like 10000000 than you will notice actually the function 2 and function 3 is taking more than function 1.So one more thing the function 1 will always give you the linear time taken to execute the program as it does not depend on the input size like I explained above.

 There are mathematical ways of analysis also for comparing which algorithms are better and we measure it in terms of the order of growth.

So this is how you compare which algorithm is better and which is not? keep in mind that it also depends upon the programming language and the machine that you use to compare the algorithms.

And one more point the Big O of N gives you the probable complexity whereas Theta of N will give you the exact complexity and information of the algorithm.I can discuss more on this but in the next blog will tell what is the difference when I say Big O of N and Theta of N of an Algorithm.

 

 

 






























Saturday, September 19, 2020

Microservice Spring Java Interview Question - Is it the best approach to implement the REST for inter-microservices communication? or any other alternatives

Question :

Are there other alternatives for inter-microservices communication? Is it the best approach to implement the REST for inter-microservices communication?

Ans:

the microservices we have developed are based on REST. We have used REST for both internal (inter-microservice, where one microservice communicates with another microservice in the same system) and external (through the public API) communication. At present, REST fits best for the public API. 

You can build microservices that are purely asynchronous. You can build microservice-based systems that would communicate based on events. There is a tradeoff between REST and event-based microservices. 

REST provides synchronous communication, whereas reactive microservices are based on asynchronous communication (asynchronous message passing). We can use asynchronous communication for inter-microservice communication. Based on the requirement and functionality, we can choose REST or asynchronous message passing.

 Consider the example case of a user placing an order, which makes a very good case for implementing reactive microservices. On successful order placement, the inventory service would recalculate the available items; the account service would maintain the transaction, correspondence service would send the messages (SMS, emails, and so on) to all involved users such as a customer and a supplier. 

In this case, more than one microservice may perform distinct operations (inventory, accounts, messaging, and so on) based on an operation (order placement) performed in one microservice. Now, just think if all these communications were synchronous. Instead, reactive communication, with asynchronous message passing, provides efficient use of hardware resources, non-blocking, low latency, and high throughput operations. 

We can primarily divide the microservice implementations into two groups—REST-based microservices and event-based/message-driven microservices. Reactive microservices are event-based.

So now what is reactive microservice?

A reactive microservice is based on the reactive manifesto and it has four principles.

for reference please go through it

https://www.reactivemanifesto.org/




1)Responsive
2)Resilient
3)Elastic
4)Message Driven

Reactive microservice performs operations in response to events like a single event, a microservice can have multiple producers or consumer events. Also, a microservice can have both producer and consumer events. like in the Booking microservice that creates the new booking (POST /v1/booking). This will be our event source and would make use of Apache Kafka for sending this event. Other microservices can consume this event by listening to the event. On a successful booking call, the Booking microservice will produce the event bookingOrdered.

So that why we should be focusing on the Reactive Microservice Architecture.



 

Friday, August 14, 2020

Microservices build pipeline (Peeling Concept) - Java Example

 Microservices could be built and tested using CI/CD tools such as Jenkins, TeamCity, and so on. In microservices, each microservice is like a small application.

For example, once you commit the code in the repository(SCM), CI/CD tools trigger the build process:

- Cleaning Code

- Code Compilation

- Unit Test Execution

- Contract/Acceptance Test Execution

- Building the application container images/archives

- Publishing the archives

- Deployment in various environments such as Dev, QA, STAGE, and PROD, etc.

- Integration and Functional test execution

So after this release-build triggers that change the SNAPSHOT version in pom.xml build the artifacts. Publish the artifacts to the repository. Tag this version in the repository.If you are using the container image then build the container image as a part of the build.

Deployment using Docker

Previously, VMs(Virtual Machines) were used to create software images that could be deployed wherever needed. As of now, Container such as Docker becomes very popular as it is compatible with old vs new(cloud) build environments.

Containers

So containers provide a lightweight runtime environment that consists of the core features of VMs and isolated service of operating systems. So a container basically runs as an application(microservice) within the OS. The OS is basically on top of the hardware and each OS could have multiple containers, with a container running the application.

A container uses kernel interfaces such as cnames and namespaces that allow multiple containers to share the same kernel while running in complete isolation to one another.





Docker

Docker is open-source and it makes use of the Linux Kernel features such as groups and namespaces because to ensure resource isolation and packaging of the application you can with its dependencies.

you can also run as expected across different Linux OS/distributions.SO you can develop an application in any language and then easily deploy it.

Containers are made of just the application and its dependencies including the basic OS. In docker container, everything executes natively on the host and uses the host kernel directly.That's why each container has its own user namespace.

Docker uses a client-server architecture. the docker client is a user interface that is used by an end-user and it communicates back and forth with a Docker daemon. Docker daemon actually does the building, running, and distributing of your docker containers.at the same time docker client and docker daemon can run on the same system or different machines.

The Docker client and daemon communicate via sockets or through a RESTful API.

Docker Architecture

Main components of Docker :

1)Docker Image: This is basically a read-only template like an image that could contain an Ubuntu OS with an apache web server and your web application installed. So it is a build component of Docker and images are used to create docker containers.

2)Docker container: A docker container is created from a Docker image. The docker container can only see its own process and its own filesystem layered onto a host filesystem and a networking stack that pipes to the host-networking stack. Docker containers can be run started stopped moved or deleted.


Microservices deployment with docker deals with 3 parts:

- Application packaging like JAR

- Building Docker Image with a JAR and dependencies using a Docker instruction file, the Dockerfile and command docker build. 

- Docker container execution from this newly build image using command docker run.

So ultimately Containerization is an efficient way to simplify microservices deployment.


The detail concept will cover in the next blog. Thanks.