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

No comments:

Post a Comment

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...