Showing posts with label Spring Boot. Show all posts
Showing posts with label Spring Boot. Show all posts

Monday, May 4, 2020

Spring Boot Handler Interceptor --- Authorization Checking


Create the following class by using HandlerInterceptor

package com.nagaraju;

import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class AuthorizationInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if (request.getRequestURI().contains("/projects/")) {
String xHeader = request.getHeader("AUTHORIZATION");
if (Objects.isNull(xHeader)) {
String responseToClient = "Permission Denied";

response.getWriter().write(responseToClient);
response.getWriter().flush();
response.getWriter().close();
return false;
}
boolean permission = getPermission(xHeader);
if (permission) {
return true;
} else {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
String responseToClient = "Permission Denied";

response.getWriter().write(responseToClient);
response.getWriter().flush();
response.getWriter().close();
return false;
}

} else {
return true;
}
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {

}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {

}

public boolean getPermission(String authorizationKey) {
if (authorizationKey.equalsIgnoreCase("SECRETKEY")) {
return true;
}
return false;
}
}

Create the following class by using WebMvcConfigurerAdapter

package com.nagaraju;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {

@Bean
AuthorizationInterceptor getSessionManager() {
return new AuthorizationInterceptor();
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getSessionManager());
}

}


Note this configuration work for Spring Rest API .. 

if you want  to enable for Sparing MVC then add the following to WebConfiguration.

@EnableWebMvc

Wednesday, April 22, 2020

Spring Boot SSL (HTTPS) Configuration

To enable SSL or HTTPS for Spring Boot web application, puts the certificate file .p12 or .jks in the resources folder, and declares the server.ssl.* values in the application.properties

Self-signed Certificate

For this example, we will use the JDK’s keytool to generate a self-sign certificate in PKCS12 format. The below command will create a PKCS12 cert, name nagaraju.p12, puts this file into the resources folder.

Terminal

$ keytool -genkeypair -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore nagaraju.p12 -validity 365

Enter keystore password:  
Re-enter new password:


application.properties
# SSL
server.port=8443
server.ssl.key-store=classpath:nagaraju.p12
server.ssl.key-store-password=123456

# JKS or PKCS12
server.ssl.keyStoreType=PKCS12

# Spring Security
# security.require-ssl=true

Done, starts the Spring Boot, and access https://localhost:8443

Redirect all traffic from port 8080 to 8443.

StartApplication.java

package com.muthyatechnology.config
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class StartApplication {
    public static void main(String[] args) {
        SpringApplication.run(StartApplication.class, args);
    }

    // spring boot 2.x
    @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.setSecure(false);
        connector.setRedirectPort(8443);
        return connector;
    }

}


Recent Post

Databricks Delta table merge Example

here's some sample code that demonstrates a merge operation on a Delta table using PySpark:   from pyspark.sql import SparkSession # cre...