Thursday, April 13, 2023

How to create key cloak authentication server and spring boot

To create a Keycloak authentication server, you need to follow these steps: 

 1. Download and Install Keycloak: You can download Keycloak from the official website     

 Follow the installation instructions provided in the documentation. 

 2. Configure Keycloak: Once installed, you need to configure Keycloak by creating a new realm. 
     A realm is a container for all the users, roles, and groups in your application.

    To create a new realm, log in to the Keycloak admin console using the default credentials
      (admin/admin), then follow these steps:

      Click on the "Add Realm" button and provide a name for your realm. 

      Configure your realm settings, including themes, email settings, and login settings. 

      Create users and groups within your realm and assign roles to them. 

 3. Set Up Your Spring Boot Application: You can use the Keycloak Spring Boot Starter dependency to
      add Keycloak authentication to your Spring Boot application.

      Add the following dependency to your Maven or Gradle build file:

<dependency>
  <groupId>org.keycloak</groupId>
  <artifactId>keycloak-spring-boot-starter</artifactId>
</dependency>


4. Configure Your Spring Boot Application: You need to configure your Spring Boot application to
     connect to the Keycloak server. 

     You can do this by adding the following properties to your application.properties or application.yml file:
keycloak.auth-server-url=<keycloak-server-url>
keycloak.realm=<keycloak-realm>
keycloak.resource=<keycloak-client-id>
keycloak.credentials.secret=<keycloak-client-secret>


   Replace <keycloak-server-url>, <keycloak-realm>, <keycloak-client-id>, 
    and <keycloak-client-secret> with the appropriate values for your Keycloak instance.

 5.  Secure Your Spring Boot Application: You can secure your Spring Boot application by adding the
      Keycloak configuration to your Spring Security configuration. 

      You can do this by creating a new class that extends KeycloakWebSecurityConfigurerAdapter and
      override the configure method. 

Here's an example:
@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(keycloakAuthenticationProvider());
    }

    @Bean
    public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
        return new KeycloakSpringBootConfigResolver();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.authorizeRequests().antMatchers("/admin/**").hasRole("admin")
          .antMatchers("/user/**").hasAnyRole("user", "admin")
          .anyRequest().permitAll();
    }
}
    This configuration class enables Keycloak authentication and authorization for specific URLs in the
     application.

 6. Test Your Application: You can test your application by running it and accessing the protected URLs.
     When a user tries to access a protected resource, they will be redirected to the Keycloak login page.
      Once they successfully authenticate, they will be redirected back to the original resource. 

That's it! we have created a Keycloak authentication server and secured your Spring Boot application with it.

Wednesday, April 12, 2023

How to build video conference using spring boot

To build a video conference application using Spring Boot, you can follow these steps: 

 1. Choose a video conferencing API: There are several video conferencing APIs available such as Twilio, Agora, Zoom, Jitsi, etc. Choose an API that best fits your requirements. 

 2. Set up a Spring Boot project: Create a new Spring Boot project using your preferred IDE or by using Spring Initializr. 

 3. Add the video conferencing API dependencies: Add the necessary dependencies for the chosen API in your project's pom.xml file.

 4. Configure the video conferencing API: Configure the video conferencing API with the required credentials and other settings in your Spring Boot application's configuration file.

 5. Implement the video conferencing features: Use the API's SDK to implement the video conferencing features such as creating a conference room, joining a room, leaving a room, etc. 

 6. Integrate the video conferencing features with your application: Add the necessary controllers and views to your Spring Boot application to integrate the video conferencing features with your application. 

 7. Test the application: Test the application thoroughly to ensure that the video conferencing features are working as expected. 

 Here's a sample code for a video conference application using Spring Boot and the Twilio Video API:
 1. Add the Twilio Video API dependency to your pom.xml file:

 

<dependency>
    <groupId>com.twilio.sdk</groupId>
    <artifactId>twilio</artifactId>
    <version>7.54.0</version>
</dependency>



2. Add the required Twilio credentials and settings to your Spring Boot application's application.properties file
twilio.account.sid=your_account_sid
twilio.auth.token=your_auth_token
twilio.api.key=your_api_key
twilio.api.secret=your_api_secret
twilio.video.room.max-participants=4
3. Implement a controller for creating and joining a video conference room:
@RestController
public class VideoConferenceController {

    @Autowired
    private TwilioConfig twilioConfig;

    @PostMapping("/room")
    public ResponseEntity createRoom() throws Exception {
        RoomCreator roomCreator = Room.creator()
                .setUniqueName(UUID.randomUUID().toString())
                .setType(RoomType.PEER_TO_PEER)
                .setStatusCallback(twilioConfig.getStatusCallback())
                .setMaxParticipants(twilioConfig.getMaxParticipants());
        Room room = roomCreator.create();
        RoomResponse response = new RoomResponse();
        response.setRoomId(room.getSid());
        response.setRoomName(room.getUniqueName());
        response.setToken(createAccessToken(room.getSid()));
        return ResponseEntity.ok(response);
    }

    @GetMapping("/room/{roomId}/token")
    public ResponseEntity 
                        getRoomToken(@PathVariable("roomId") String roomId) {
        String accessToken = createAccessToken(roomId);
        return ResponseEntity.ok(accessToken);
    }

    private String createAccessToken(String roomId) {
        VideoGrant grant = new VideoGrant();
        grant.setRoom(roomId);
        AccessToken token = new AccessToken.Builder(
                twilioConfig.getAccountSid(),
                twilioConfig.getApiKey(),
                twilioConfig.getApiSecret()
        ).identity(UUID.randomUUID().toString())
                .grant(grant)
                .build();
        return token.toJwt();
    }

}
4.Define a configuration class for the Twilio settings:
@ConfigurationProperties(prefix = "twilio")
@Data
public class TwilioConfig {

    private String accountSid;
    private String authToken;
    private String apiKey;
    private String apiSecret;
    private String statusCallback;
    private int maxParticipants;


}


5.Configure the Twilio settings in your Spring Boot application's application.yml file:
twilio:
  account-sid: your_account_sid
  auth-token: your_auth_token
  api-key: your_api_key
  api-secret: your_api_secret
  status-callback: http://localhost:8080/callback
  max-participants: 4
  
  
6. Run your Spring Boot application and test the video conference feature by creating and joining a room using the API endpoints.

Tuesday, March 14, 2023

Oracle Cloud Infrastructure- Object storage example

This post will explain, how we can create bucket and configure notification and rules and object storage like create/update object. Login into OCI using login credentials . if you don't have a account please create the same using this link https://www.oracle.com/cloud/sign-in.html Once you create account and successful login, Now we need to create a bucket. search for bucket and create a bucket
After creating bucket now we can create a topic
Now we can create notification, after uploading file , we should get email
Create a Rule to process this
Once we create all then , once we upload file in object storage , then we should get email like below
This shows we can send email, but we can configure with different ways like queues. Here we will get the details in mail . But if we want complete object details, then we can use java code to retrieve the object details by calling the API which required namespace details ,bucket name and object name.
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Paths;
import java.util.List;

import com.oracle.bmc.objectstorage.ObjectStorage;
import com.oracle.bmc.objectstorage.ObjectStorageClient;
import com.oracle.bmc.objectstorage.model.GetObjectRequest;
import com.oracle.bmc.objectstorage.model.ObjectStream;
import com.oracle.bmc.objectstorage.model.Range;
import com.oracle.bmc.objectstorage.requests.GetObjectRequest;
import com.oracle.bmc.objectstorage.responses.GetObjectResponse;

public class LogFileRetriever {
    public static void main(String[] args) {
        String namespaceName = "mynamespace";
        String bucketName = "mybucket";
        String objectName = "mylogfile.txt";

        // Create a new Object Storage client
        ObjectStorage objectStorageClient = ObjectStorageClient.builder()
                .build(objectStorageConfig);

        GetObjectRequest request = GetObjectRequest.builder()
                .namespaceName(namespaceName)
                .bucketName(bucketName)
                .objectName(objectName)
                .build();

        GetObjectResponse response = objectStorageClient.getObject(request);

        // Get the InputStream from the response
        InputStream logFileInputStream = response.getInputStream();

        // Write the InputStream to a local file
        OutputStream logFileOutputStream = 
            new FileOutputStream(Paths.get("logfile.txt").toFile());
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = logFileInputStream.read(buffer)) != -1) {
            logFileOutputStream.write(buffer, 0, bytesRead);
        }
        logFileOutputStream.close();
    }
}

Monday, March 14, 2022

How to call REST API Using Spring Webflux WebClient set proxy with authorization while calling the external site and Generate base 64 authentication header spring boot

This post will explain us, how can we call REST API using Webclient. How to set Proxy username and password to call the external site. Step 1: Add folllowing dependency in your pom.xml
   
	 org.springframework.boot
	 spring-boot-starter-webflux
	
Step 2:
import lombok.extern.slf4j.XSlf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.reactive.ClientHttpConnector;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
import reactor.netty.transport.ProxyProvider;

import java.net.URI;
import java.util.Base64;
import java.util.function.Consumer;
import java.util.function.Function;
 public static void main(String[] args) {
  try {
  //Generate HttP client to set proxy details
  HttpClient httpClient = HttpClient.create()
            .proxy(proxy-> proxy.type(ProxyProvider.Proxy.HTTP)
            .host("javaguruonline.com").port(1328)
            .username("siva")
            .password(new Function() {
                        @Override
                        public String apply(String s) {
                            return "test@12!";
                        }
                    }));
  ClientHttpConnector clientHttpConnector = 
           new ReactorClientHttpConnector(httpClient);
  WebClient webClient = WebClient.builder().build();
  String plainCredentials = "username" + ":" + "password";
  String base64Credentials = new String(Base64.getEncoder()
                           .encode(plainCredentials.getBytes()));
  String authorizationHeader = "Basic " + base64Credentials;
  //input json
  String json = "{\n" +
                    "  \"user\": \"siva\"\n" +
                    "}";
            //set http headers
  Consumer httpHeaders = new Consumer() {
     @Override
     public void accept(HttpHeaders httpHeaders) {
       httpHeaders.add("Authorization", authorizationHeader);
       httpHeaders.add("Content-Type", "application/json");
       httpHeaders.add("Proxy-Authorization", authorizationHeader);
     }};
   //post call to external URL and get ResponseEntity as response like body 
   //and http status code etc..
    ResponseEntity result = webClient.mutate()
                    .clientConnector(clientHttpConnector)
                    .build()
                    .post()
                    .uri(new URI("https://localhost:8080/test/details"))
                    .bodyValue(json)
                    .accept(MediaType.APPLICATION_JSON)
                    .retrieve()
                    .toEntity(String.class)
                    .block();
            System.out.println(result);
        }
        catch(Exception ex){
        }
Hope this post will help some one, while working on the REST API calls

AddToAny

Contact Form

Name

Email *

Message *