1.spring Boot Intro Configuration Security Latest-1111
1.spring Boot Intro Configuration Security Latest-1111
Configuration
Why Spring Boot?
• Relieves Programmer from multiple manual configurations – spring
boot provides auto configurations
• Lets programmer easily develop production ready applications,
• It makes it easier to integrate the Spring Boot Application with the
Spring that majorly includes Spring ORM, Spring JDBC, Spring
Security, Spring Data and many other things.
• Provides Dev tools(spring-boot-devtools), helpful in remote
debugging
• It tests the web applications easily with the help of different
Embedded HTTP servers that includes Tomcat, Jetty and many
others.
@Bean is used to explicitly declare a single bean, rather than letting Spring do it
automatically as above. It decouples the declaration of the bean from the class
definition, and lets you create and configure beans exactly how you choose.
The @Bean annotation returns an object that spring should register as bean in
application context. The body of the method bears the logic responsible for
creating the instance.
@Component, @Repository, @Service and
@Controller
@Component annotation marks a java class as a bean so the component-scanning
mechanism of spring can pick it up and pull it into the application context.
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:resources mapping="/webjars/**" location="/webjars/"/>
Manual Configurations in
Traditional Spring F/W
And when Hibernate is used, below configurations need to be provided
Spring Boot has relieved us from this Brutal effort, by providing Auto
Configurations
Spring Boot Auto Configuration
Therefore, you can annotate your component classes with @Component, but by
annotating them with @Repository, @Service, or @Controller instead, your classes
are more properly suited for processing by tools or associating with aspects. For
example, these stereotype annotations make ideal targets for pointcuts.
Thus, if you are choosing between using @Component or @Service for your service
layer, @Service is clearly the better choice.
Spring Boot External Configuration
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. Let us see
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.
-Dspring.config.location="C:\\spring_boot_training\\abcd.properties"
Spring Boot
Environment Variables
External Configuration
set SPRING_CONFIG_NAME=application,myapp
Set SPRING_CONFIG_LOCATION=classpath:/data/myapp/config,classpath:/data/myapp/external/config
@EnableConfigurationProperties
Spring Boot Property Configuration order
Spring Boot Profiles
A profile is a set of settings that can be configured to override settings
from application.properties.
http://start.spring.io/
Packaging Spring Boot Application
Spring Boot has simplified the deployment of Java-based web/API
applications drastically. It has eliminated the process of deploying a
WAR file into the web container provided by Tomcat or any other
application servers.
It has brought in a new paradigm shift where the container libraries (like
Tomcat/Ubuntu/Jetty) are themselves embedded along with application
classes/JAR within the fat Spring Boot JAR — thus making it a truly
standalone application and a candidate for microservice development.
This saves Server setup time, into production, you just have only jar file
which need to be deployed.
But, there are few minor challenges, which a spring boot developer
would face, when deploying the Spring boot application.
Packaging Spring Boot Application
How do we ship the external configuration files like
application.properties, configuration XML files, etc. along with the
Spring Boot JAR?
How can we copy the start-up script with VMs and other parameters to
start the application to deployment environments?
On the downside, you will not be able to run the application from
Eclipse, just by running “Application.java” because the configuration
files will not be copied to the target/classesdirectory. However,
exclusion of files can be ignored.
Spring Boot Security
Spring security is the highly customizable authentication and access-
control framework. Spring Security is a framework that focuses on
providing both authentication and authorization to Java applications.
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER")
.and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
}
Above configuration sets up a basic in-memory authentication config.
Pom.xml snippet
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
</dependency>
OAuth2 Authentication
OAuth2.0 is an open authorization protocol, which allows accessing the
resources of the resource owner by enabling the client applications on
HTTP services such as Facebook, GitHub, etc. It allows sharing of
resources stored on one site to another site without using their
credentials. It uses username and password tokens instead.
@Autowired
private DataSource dataSource;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.withDefaultSchema()
.withUser("user").password("password").roles("USER")
.and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
Filter Chains
Spring Security offers support for applying access rules to Java method
executions. The first step is to enable method security, for example in
the top level configuration for our app:
This sample is a service with a secure method. If Spring creates a @Bean of this type then it
will be proxied and callers will have to go through a security interceptor before the method
is actually executed. If the access is denied the caller will get
an AccessDeniedException instead of the actual method result.
There are other annotations that can be used on methods to enforce security constraints,
notably @PreAuthorize and @PostAuthorize, which allow you to write expressions
containing references to method parameters and return values respectively.
CORS
Lets configure some simple authorization on each URL using roles:
Exceptions
How to disable Security?
Add below lines to application.properties :
security.basic.enabled=false
management.security.enabled=false
Spring JMS
JMS (Java Message Service) is a Java Message Oriented Middleware
used to send messages between clients and works by sending messages
to a message queue which are then taken when possible to execute a
transaction. This post will focus on implementing JMS with Spring Boot,
which doesn’t take long at all to setup.
JMS and message queues, in general, bring some certain advantages
over using RESTful services such as:
Loose coupling: The services do not interact directly and only know
where the message queue is, where one service sends
messages(Publisher) and the other(Subscribers) receives them.
Subscribers/Publishers can be added/removed dynamically.
Spring JMS
Asynchronous messaging: As the process time of the message cannot be
guaranteed, the client that sent the message can carry on
asynchronously to the completion of the transaction. Due to this, the
queue should be used to write data (POST if you're thinking in a RESTful
mindset).
Publisher
//Get JMS template bean reference
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class);
// Send a message
System.out.println("Sending a message.");
jmsTemplate.convertAndSend("jms.message.endpoint", new Message(1001L, "test body", new Date()));
Spring JMS
Subscriber: JMS Message Receiver with @JmsListener
Message receiver class ispretty much simple class with single method
with annotation @JmsListener. @JmsListener allows you to expose a
method of a managed bean as a JMS listener endpoint.
So whenever any message is available on configured queue (in this
example queue name is “jms.message.endpoint”), annotated method
(i.e. receiveMessage) will be invoked.
Spring JMS
application.properties file
jsa.activemq.broker.url=tcp://localhost:61616
jsa.activemq.borker.username=admin
jsa.activemq.borker.password=admin
jsa.activemq.topic=jsa-topic
Spring Boot JMS
ActiveMq provides the Publish-Subscribe pattern (pub-sub) for building
Jms message distributed systems.
How it work? -> When you publish a messages, all active subscribers
will receive a copy of the message.
Home page of ActiveMQ - http://activemq.apache.org/
Any Language/Platform
Any Language/Platform
Spring Boot JMS
Download and install ActiveMQ from URL
http://activemq.apache.org/activemq-5130-release.html
http://activemq.apache.org/cross-language-
clients.html
Characteristics of Topic
A JMS topic is the type of destination in a 1-to-many model of
distribution.
The same published message is received by all consuming
subscribers.
You can also call this the 'broadcast' model.
You can think of a topic as the equivalent of a Subject in an
Observer design pattern for distributed computing.
Some JMS providers efficiently choose to implement this as UDP
instead of TCP.
For topic's the message delivery is 'fire-and-forget' - if no one
listens, the message just disappears.
If that's not what you want, you can use 'durable subscriptions'.
Characteristics of Queue
A JMS queue is a 1-to-1 destination of messages.
The message is received by only one of the consuming receivers
(please note: consistently using subscribers for 'topic client's and
receivers for queue client's avoids confusion).
Messages sent to a queue are stored on disk or memory until
someone picks it up or it expires.
So queues (and durable subscriptions) need some active storage
management, you need to think about slow consumers.
In most environments, topics are the better choice because you can
always add additional components without having to change the
architecture. Added components could be monitoring, logging,
analytics, etc.
Messaging Solutions
RabbitMQ, Kafka, and ActiveMQ are all messaging technologies used to
provide asynchronous communication and decouple processes
(detaching the sender and receiver of a message). They are called
message queues, message brokers, or messaging tools. RabbitMQ,
Kafka, and ActiveMQ all serve the same basic purpose, but can go about
their jobs differently. Kafka is a high-throughput distributed messaging
system. RabbitMQ is an AMQP based reliable message broker.
ActiveMQ and Kafka are both Apache products, and both written in
Java; RabbitMQ is written in Erlang.