Friday 18 January 2019

java spring boot tutorial


Explanation on how Spring boot will be used:

Spring Boot aims to make it easy to create Spring-powered, production-grade applications and services with minimum fuss. It takes an opinionated view of the Spring platform so that new and existing users can quickly get to the bits they need. You can use it to create stand-alone Java applications that can be started using ‘java -jar’ or more traditional WAR deployments. We also provide a command line tool that runs ‘spring scripts’.
The diagram below shows Spring Boot as a point of focus on the larger Spring ecosystem. It presents a small surface area for users to approach and extract value from the rest of Spring
How to run spring boot without a web container?
Simply start your spring boot app in a non-web environment:
new SpringApplicationBuilder()
.sources(SpringBootApp.class)
.web(false)
.run(args);
Also, you obviously should not add the spring-boot-starter-web dependency.
By default, spring boot launches a web container if it finds one in the classpath. Using web(false)ensures that it does not happen. Tomcat could be included by another dependency without your knowledge, so it's better to disable the web environment if that is your goal.

What is Spring?
Simply put, the Spring framework provides comprehensive infrastructure support for developing Java applications.
It’s packed with some nice features like Dependency Injection and out of the box modules like:
  • Spring JDBC
  • Spring MVC
  • Spring Security
  • Spring AOP
  • Spring ORM
  • Spring Test
These modules can drastically reduce the development time of an application.
For example, in the early days of Java web development, we needed to write a lot of boilerplate code to insert a record into a data source. But by using the JDBCTemplate of the Spring JDBC module we can reduce it to a few lines of code with only a few configurations.
What is Spring Boot?
Spring Boot is basically an extension of the Spring framework which eliminated the boilerplate configurations required for setting up a Spring application.
It takes an opinionated view of the Spring platform which paved the way for a faster and more efficient development eco-system.
Here are just a few of the features in Spring Boot:
  • Opinionated ‘starter’ dependencies to simplify build and application configuration
  • Embedded server to avoid complexity in application deployment
  • Metrics, Helth check, and externalized configuration
  • Automatic config for Spring functionality – whenever possible

Maven Dependencies

First of all, let’s look at the minimum dependencies required to create a web application using Spring:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.1.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.0.RELEASE</version>
</dependency>

Unlike Spring, Spring Boot requires only one dependency to get a web application up and running:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.0.5.RELEASE</version>
</dependency>

Spring Boot provides a number of starter dependencies for different Spring modules.Some of the most commonly used ones are:
  • spring-boot-starter-data-jpa
  • spring-boot-starter-security
  • spring-boot-starter-test
  • spring-boot-starter-web
  • spring-boot-starter-thymeleaf

Application Configuration with Spring Boot:
Configuration for applications vary from one environment to another
·        You would want to connect to a different database or queues
·        You would want to connect with different services
·        You would want to configure less logging in production
·        You might want to have different custom configuration
Application Configuration with Spring Boot application.properties
Spring Boot allows you to configure your application configuration using a file named application.properties
application.properties can reside anywhere in the classpath of the application.
In application.properties, we can use the “logging.level” prefix to set logging levels.
logging.level.some.package.path=DEBUG
logging.level.some.other.package.path=ERROR
You can configure a log file by using logging.file property in application.properties. The logging here would be in addition to the logging in console.
logging.file=\path_to\logfile.log
You can also configure the port to run the server on using server.port
server.port = 9080
How application configuration will point common location:
Spring Boot looks at Frameworks available on the CLASSPATH b) Existing configuration for the application. Based on these, Spring Boot provides basic configuration needed to configure the application with these frameworks. This is called Auto Configuration.
For external configuration follow the below link:
How to load external property files into Spring Boot application?
It is a standard practice that during our production deployments, our application loads property files from external locations. This helps us to change our configurations without changing our code. In this page, we will come to know how to load external property files into Spring Boot application.
By default, Spring Boot look for externalized default property file application.properties into given below predetermined locations:
In the classpath root.
In the package "/config" in classpath.
In the current directory.
In the "/config" directory of current folder.

Now lets say, your application requires externalized properties like application.properties and another property file myapp.properties. The both properties can be in the same folder or they can be in different folder. There are 3 ways of doing it.
Command line arguments
In the first approach, all you need to do is pass folder names and property names as part of command line arguments as shown below:
Terminal:
java -jar myapp.jar --spring.config.name=application,myapp --spring.config.location=classpath:/data/myapp/config,classpath:/data/myapp/external/config
In the above command, we are passing property file name as part of "--spring.config.name" variable and folder location as part of "--spring.config.location" variable.
Environment variables
In the second approach, you can configure your externalized configuration details into environment variables and your Spring Boot application will read it from your environment as shown below:
Terminal:
set SPRING_CONFIG_NAME=application,myapp
set SPRING_CONFIG_LOCATION=classpath:/data/myapp/config,classpath:/data/myapp/external/config
java -jar myapp.jar
Programatically loding configurations:
ort org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

@SpringBootApplication
public class SpringBootWebApplication {

    private static Logger logger = LoggerFactory.getLogger(SpringBootWebApplication.class);
public static void main(String[] args) throws Exception {

ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(SpringBootWebApplication.class).properties("spring.config.name:application,myapp",          spring.config.location:classpath:/data/myapp/config,classpath:/data/myapp/external/config").build().run(args);
 ConfigurableEnvironment environment = applicationContext.getEnvironment();
     logger.info(environment.getProperty("cmdb.resource-url"));
    }
}



Thursday 17 January 2019

what is micro services authentication strategy in spring

micro services authentication strategy

All about building secure micro-services
Why need security in microservices?
Microservices talk to each-other. So all the communication links between micro services need to have a way to make security decisions whether or not they are allowed to communicate and if at all, what are the authorization levels.

What protocol does your microservice speak?
·        HTTP (REST, SOAP)
·        AMQP (Messaging)
·        Apache Thrift (Remote Procedure Call Framework)
·        gRPC (google’s RPC)
·        custom TCP protocol and likewise…

What we just got to know is, it’s not just a HTTP protocol which is in picture, and therefore decision on making a choice on the security standard must take into account the protocol flexibility.
Solution:
Every request to a microservice must include a security token that the microservice can easily authenticate and use for making authorization decision.

Self-Learn : Look back on what is Authentication and Authorization???

Problems to solve
  1. 1   What format should security token use?
  2. 2    How are tokens supposed to be obtained?
  3. 3    What libraries should be used for authentication and authorization when         implementing micro services?
  4. 4 What information should be in the token?

 n  Use a “STANDARD” token format, as simple as that.
Token Standard
Format
Protocol Specific
Year of standardization
Kerberos Ticket
Binary
Yes, Kerberos
1993
SAML Token
XML
Yes, SAML
2002
JWT Token
JSON
No
2015

To get a SAML token you need a SAML Server.
To get a Kerberos ticket you need a Kerberos server.
To get a JWT you need something that can give it to you.

Decision point #1) Evaluation criteria
            Is the token format standardized?
            Can the token be used with any protocol?
            Is the token easy to parse?
            Can the token be included in URL parameter?
            Are there lots of libraries in lots of programming languages for working with the token?
Is the token format considered “easy” to work with?

A ToolBox of Standards
Name
Title
OAuth1
The Oauth 1.0 Protocol
OAuth2
The Oauth 2.0 Authorization Framework
Bearer Token
The Oauth 2.0 Authorization Framework : Bearer token usage
JWE
JSON Web encryption
JWK
JSON Web key
JWA
JSON Web algorithms
JWT
JSON Web tokens
JOSE
JSON object signing and encryption
JWS
JSON Web signature unencoded payload option
JWT:
JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.
JWT.IO allows you to decode, verify and generate JWT.
OAuth:
OAuth (Open Authorization) is an open standard for access delegation, commonly used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords.[1] This mechanism is used by companies such as Google, Facebook, Microsoft and Twitter to permit the users to share information about their accounts with third party applications or websites.
JWT, OAuth, OpenID Connect and CSRF protection : An understanding
JWT (JSON Web Tokens)- It is just a token format. JWT tokens are JSON encoded data structures contains information about issuer, subject (claims), expiration time etc. It is signed for tamper proof and authenticity and it can be encrypted to protect the token information using symmetric or asymmetric approach. JWT is simpler than SAML 1.1/2.0 and supported by all devices and it is more powerful than SWT(Simple Web Token).
OAuth2 - OAuth2 solve a problem that user wants to access the data using client software like browse based web apps, native mobile apps or desktop apps. OAuth2 is just for authorization, client software can be authorized to access the resources on-behalf of end user using access token.
OpenID Connect - OpenID Connect builds on top of OAuth2 and add authentication. OpenID Connect add some constraint to OAuth2 like UserInfo Endpoint, ID Token, discovery and dynamic registration of OpenID Connect providers and session management. JWT is the mandatory format for the token.
CSRF protection - You don't need implement the CSRF protection if you do not store token in the browser's cookie.
You can read more details here http://proficientblog.com/microservices-security/


If we have to differentiate JWT and OAuth. Basically, JWT is a token format. OAuth is an authorization protocol that can use JWT as a token. OAuth uses server-side and client-side storage. If you want to do real logout you must go with OAuth2. Authentication with JWT token cannot logout actually. Because you don't have an Authentication Server that keeps track of tokens. If you want to provide an API to 3rd party clients, you must use OAuth2 also. OAuth2 is very flexible. JWT implementation is very easy and does not take long to implement. If your application needs this sort of flexibility, you should go with OAuth2. But if you don't need this use-case scenario, implementing OAuth2 is a waste of time.
XSRF token is always sent to the client in every response header. It does not matter if a CSRF token is sent in a JWT token or not, because the CSRF token is secured with itself. Therefore sending CSRF token in JWT is unnecessary.

Decision on whether to go for OAuth or Simple JWT based access to applications:
The key point here is access delegation. Why would anyone create OAUTH when there is an id/pwd based authentication, backed by multifactored auth like OTPs and further can be secured by JWTs which are used to secure the access to the paths (like scopes in OAUTH) and set the expiry of the access
There's no point of using OAUTH if consumers access their resources(your end points) only through their trusted websites(or apps) which are your again hosted on your end points
You can go OAUTH authentication only if you are an OAUTH provider in the cases where the resource owners (users) want to access their(your) resources (end-points) via a third-party client(external app). And it is exactly created for the same purpose though you can abuse it in general
Another important note:
You're freely using the word authentication for JWT and OAUTH but neither provide the authentication mechanism. Yes one is a token mechanism and the other is protocol but once authenticated they are only used for authorization (access management). You've to back OAUTH either with OPENID type authentication or your own client credentials



Sample code to generate JWT:
Sample Code to decode tokens:


for reference go through the below links