Tuesday 30 January 2018

Security with Spring Boot

Web Services Security can be provided in many ways: 

  1. SSL Configuration
  2. HTTP Basic Authentication 
  3. OAUTH Configuration
  4. HTTP Digest Authentication.



SSL Configuration

Step 1 : Create a Spring boot application by using http://start.spring.io

Step 2 : Generate a SSL Certificate by using keystore commands like below

keytool -genkey -alias selfsigned_localhost_sslserver -keyalg RSA -keysize 2048 - validity 700  - keypass changeit -storepass changeit -keystore ssl-server.jks.

It will generate the ssl.server.jks file which will have self signed certificate.

Step 3 : Create Controller class and write one get method.

Step 4 : Copy the keystore file (ssl-server.jks) into the resource folder.

Step 5 : Copy the below properties into the application.properties file.

server.port=8443
server.ssl.key-alias=selfsigned_localhost_sslserver
server.ssl.key-password=changeit
server.ssl.key-store=classpath:ssl-server.jks
server.ssl.key-store-provider=SUN

server.ssl.key-store-type=JKS

Step 6 : Do maven build and call the get method through web browser. You will get warning like not trusted certificate authorities. Just give continue it will redirect to HTTPS.

HTTP Basic Authentication : 

Step 1 : Create a spring boot project by using spring boot security jar.

Step 2 : Write one simple Controller with @GetMapping method which will returns some message.

Step 3 : Run the spring boot main application.

Step 4 : Hit the service (http://localhost:8080/security/hellosecurity/)in browser, then pop up will ask username and pwd to access the API.

Step 5 : Default username : user, Password : it will generate in Console.

Custom Configuration:

Step 6 : Write a @Configuration Class which extends WebSecurityConfigurerAdaptor
Override the configure methods in the class and give the custom roles and credentials like below

Step 7 : Hit the service will ask the username and password. Use the above custom credentials to access the API's. From custom class we can hit the Database and validate the roles and credentials also.

OAUTH Configuration in Spring Boot:

Will be add soon

SpringBoot

SpringBoot SpringBoot Application :  Pros & Cons :  SpringBoot Application creation using spring.io :  SpringBoot Application Annotation...