/** WebMvcConfig.class */
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new WebSecurityConfig())
.addPathPatterns("/**")
.excludePathPatterns("/login","/loginPost");
super.addInterceptors(registry);
}
/** WebSecurityConfig.class */
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
boolean flag =true;
User user=(User)request.getSession().getAttribute("user");
if(null==user){
response.sendRedirect("/login");
flag = false;
}
return flag;
}
I added an interceptor that jumps to the login page when the user is not logged in. The interceptor works when I enter 'http://localhost:8011/git/vision'. But when I type this URL, 'http://localhost:8011/git/vision/index.html', the interceptor doesn't work. It means that I can access this resource without logging in. Can you help me solve this problem?
Related
In older Java versions you could extend a class with WebSocketServlet, and because WebSocketServlet itself extended HttpServlet it was possible to add CRUD method, such as doGet(...), doPost(...) etc in the class.
However, now WebSocketServlet is deprecated and and using #ServerEndpoint with #OnOpen, #OnMessage, etc does not provide any "listen to doGet, doPost" messages. How can I migrate something like this?
public class Test extends WebSocketServlet
{
String something = "";
#Override
protected StreamInBound createWebSocketInbound(String string, HttpServletRequest hsr)
{
// DO STUFF
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException
{
this.something = "get";
}
}
Where do put doGet(...) and doPost(...)?
#ServerEndpoint(value = "/test")
public class Test {
#OnOpen
public void onOpen(Session session) {
// DO STUFF
}
#OnMessage
public String onMessage(String message, Session session) {
// DO STUFF
}
#OnClose
public void onClose(Session session, CloseReason closeReason) {
// DO STUFF
}
}
Also notice that I need to change a variable from the doGet(...) method that exist in the Test class.
Thanks!
I am trying to create a jar file to inject into any of my spring boot project for logging the request details.
I am able to do this in one of my project. You can see the code below.
How to create the jar out of it and how to inject into other projects?
#Component
public class Interceptor extends HandlerInterceptorAdapter {
private static Logger log = LoggerFactory.getLogger(Interceptor.class);
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// log.info("Inside prehandle");
return true;
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// log.info("Inside postHandle");
}
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("Inside afterCompletion");
sendToLoggerApi(request, response);
}
}
#Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
#Autowired
Interceptor interceptor;
#Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(interceptor);
}
}
I have several folders in /static/img/** and I need to add interceptors to some of them to check user permissions. I've used interceptors earlier and added them this way:
#SpringBootApplication
#EnableTransactionManagement
public class Application extends WebMvcConfigurerAdapter {
...
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
#Bean
public AuthHeaderInterceptor authHeaderInterceptor() {
return new AuthHeaderInterceptor();
}
#Bean
public AuthCookieInterceptor authCookieInterceptor() {
return new AuthCookieInterceptor();
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry
.addInterceptor(authHeaderInterceptor())
.addPathPatterns(REST_URL)
.excludePathPatterns(
new String[] {
REST_SECURITY_URL,
REST_SETTINGS_URL,
REST_REPORTS_URL
}
);
registry
.addInterceptor(authCookieInterceptor())
.addPathPatterns(REST_REPORTS_URL);
}
}
All works fine for rest controllers and their URLs, but now I need to secure some static resources and I added this:
#SpringBootApplication
#EnableTransactionManagement
public class Application extends WebMvcConfigurerAdapter {
...
#Bean
public RoleAdminInterceptor roleAdminInterceptor() {
return new RoleAdminInterceptor();
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry
.addInterceptor(authHeaderInterceptor())
.addPathPatterns(REST_URL)
.excludePathPatterns(
new String[] {
REST_SECURITY_URL,
REST_SETTINGS_URL,
REST_REPORTS_URL
}
);
//THIS NOT WORK
registry
.addInterceptor(roleAdminInterceptor())
.addPathPatterns("/static/img/admin/**");
registry
.addInterceptor(authCookieInterceptor())
.addPathPatterns(REST_REPORTS_URL);
}
}
Commented line doesn't work. When I send request to /static/img/admin/test.png RoleAdminInterceptor is never called.
What I'm doing wrong?
I know this is an old question, but since it's unanswered it might help others searching for it.
This is what worked for me:
1- Declare an interceptor class:
class RoleBasedAccessInterceptor implements HandlerInterceptor {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
AntPathMatcher matcher = new AntPathMatcher();
String pattern = "/static/img/admin/**";
String requestURI = request.getRequestURI();
if (matcher.match(pattern, requestURI)) {
//Do whatever you need
return validateYourLogic();
}
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 {
}
}
2- Configure WebMvcConfigurer
public class WebMvcConfiguration implements WebMvcConfigurer {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RoleBasedAccessInterceptor());
}
}
I think in this case you could use Filters with Spring Security instead of Interceptors as you could Validate the access earlier on the process even before hitting the Interceptor, unless there is a specific use case that you need to use the interceptor here.
Some topic about the difference between these two:
filters-vs-interceptor
I have configured spring boot for rest controller.
I created many api but i need to validate my token information in every api at begging, Is user is authorized or not base on provided token.
During the signin i am generating token that token required in every api for accessing information. if token is not valid then i need to return message Sorry, your provided token information has been expired or not exists.
below is the my api.
#RequestMapping(value="/delete", method= RequestMethod.DELETE)
public Map<String, Object> delete(#RequestBody String reqData,HttpServletRequest request) {
Map<String, Object> m1 = new HashMap<String,Object>();
JSONObject jsonData = new JSONObject(reqData);
Token token= tokenDao.getByTokenCode(jsonData.getString("token"));
if(token==null){
m1.put("status", "error");
m1.put("message", "Sorry, your provided token information expired or not exists.");
return m1;
}
//here my logic to remove user from database.
}
Is there any way to check token functionality in service method or using annotation, so i need to remove that same code in every api and need to use one common functionality.
you can use HandlerInterceptor to handle you token.
HandlerInterceptor.preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) will execute before any RequestMapping.
validate you token in preHandle.if token is valid continue,else throw exception,controller advice will handler the rest.
expose bean class of MappedInterceptor,spring will auto load HandlerInterceptor bean contains.
ControllerAdvice and ExceptionHandler can catch exception and return error message
full example
#RestController
#EnableAutoConfiguration
public class App {
#RequestMapping("/")
public String index() {
return "hello world";
}
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
public static class MyException extends RuntimeException {
}
#Bean
#Autowired
public MappedInterceptor getMappedInterceptor(MyHandlerInterceptor myHandlerInterceptor) {
return new MappedInterceptor(new String[] { "/" }, myHandlerInterceptor);
}
#Component
public static class TestBean {
public boolean judgeToken(HttpServletRequest request) {
String token = request.getParameter("token");
if (token == null) {
throw new MyException();
}
return true;
}
}
#Component
public static class MyHandlerInterceptor implements HandlerInterceptor {
#Autowired
TestBean testBean;
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
return testBean.judgeToken(request);
}
#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 {
}
}
#ControllerAdvice
public static class MyExceptionHandler {
#ExceptionHandler(MyException.class)
#ResponseBody
public Map<String, Object> handelr() {
Map<String, Object> m1 = new HashMap<String, Object>();
m1.put("status", "error");
m1.put("message", "Sorry, your provided token information expired or not exists.");
return m1;
}
}
}
public class TokenVallidation
{
public static boolean tokenValidation(user id, String token){
Token token= tokenDao.getByTokenCode(id,jsonData.getString("token"));
if(token==null){
m1.put("status", "error");
m1.put("message", "Sorry, your provided token information expired or not exists.");
return false;
}
else{
return true;
}
}
}
for controller pass user id and token and check the token. you need to update dao method as per user id parameter.
Instead of getting token from database and matching with current token you can use cache. create your own cache object like Map or a static string, which will have the latest token. and you can direct compare incoming token with this token from cache. no need to hit database for every time.
I would like to know how am I able to redirect the request inside the controller constructor if I need to do it?
For example: Inside the constructor I need to check some condition and if doesn't met I want to redirect to some other place. At the same way the rest of the constructor will not be executed neither the "original following action". I want the code like this.
#Controller
class SampleController{
public SampleController(){
if(![some condition]){
...redirecting code...
}
...rest code...
}
...rest code...
}
EDIT
If constructor is not a good option or approach then is there any option like before filter that will execute always before every action of a constructor and will redirect on the failure of some conditions?
You could use an interceptor:
public class CheckInterceptor implements HandlerInterceptor {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
if (handler instanceof TheController) {
// or for any controller: if (handler.getClass().isAnnotationPresent(Controller.class))
if (!check()) {
redirect("/check-failure.html");
return false;
}
}
return true;
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
}
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
private void redirect(HttpServletRequest request, HttpServletResponse response, String path) throws ServletException {
try {
response.sendRedirect(request.getContextPath() + path);
} catch (IOException e) {
throw new ServletException(e);
}
}
private boolean check() {
return ...
}
}
Then register it within the applicationContext.xml:
<mvc:interceptors>
<bean class="your.package.CheckInterceptor" />
</mvc:interceptors>