如何为Spring RESTful Web服务创建Spring拦截器

时间:2016-07-13 19:31:34

标签: spring-mvc spring-restcontroller spring-rest

我有一些没有web.xml的Spring RESTful(RestControllers)Web服务,我使用Spring启动来启动服务。

我想为Web服务添加授权层,并希望在实际调用Web服务本身之前将所有http请求路由到一个前端控制器。 (我有一个代码来模拟autherisation层的会话行为,根据我从客户端发送的每个httpRequest生成的密钥来验证用户)。

是否有任何标准Spring解决方案将所有请求路由到过滤器/前端控制器?

提前致谢, Praneeth

编辑: 添加我的代码

控制器: `

@RestController
public class UserService {
    UserDAO userDAO = new UserDAO();

    @RequestMapping(value="/login", method = RequestMethod.POST)
    @LoginRequired
    public String login(@RequestParam(value="user_name") String userName, @RequestParam(value="password") String password, HttpServletRequest request){
        return userDAO.login(userName, password);
    }
}`

拦截器:

`

public class AuthenticationInterceptor implements HandlerInterceptor  {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        System.out.println("In Interceptor");
        //return super.preHandle(request, response, handler);
        return true;
    }
    @Override
    public void postHandle( HttpServletRequest request, HttpServletResponse response,
            Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("---method executed---");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
            Object handler, Exception ex) throws Exception {
        System.out.println("---Request Completed---");
    }
}

`

接口。 `

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
}

`

5 个答案:

答案 0 :(得分:15)

可以采取以下步骤来实现Spring的拦截器:

  • 实现一个扩展HandlerInterceptorAdapter类的拦截器类。以下是代码的外观:

    public class LoginInterceptor extends HandlerInterceptorAdapter {
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception)
        throws Exception {
        // TODO Auto-generated method stub
    
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
        throws Exception {
        // TODO Auto-generated method stub
    
        }
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
            HandlerMethod handlerMethod = (HandlerMethod) handler;
    
            String emailAddress = request.getParameter("emailaddress");
            String password = request.getParameter("password");
    
            if(StringUtils.isEmpty(emailAddress) || StringUtils.containsWhitespace(emailAddress) ||
            StringUtils.isEmpty(password) || StringUtils.containsWhitespace(password)) {
                throw new Exception("Invalid User Id or Password. Please try again.");
            }
    
            return true;
        }
    
    
    }
    
  • 实现AppConfig类或在现有Configuration类之一中添加addInterceptors。请注意使用LoginInterceptor实例

    指定的路径模式
    @Configuration  
    public class AppConfig extends WebMvcConfigurerAdapter  {  
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
           registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/account/login");
        }
    } 
    
  • 实施控制器方法,如下所示:

    @Controller
    @RequestMapping("/account/login")
    public class LoginController {
    
        @RequestMapping(method = RequestMethod.GET)
        public String login() {
            return "login";
        }
    }
    

答案 1 :(得分:7)

这里是拦截器的一个例子:

public class AuthenticationInterceptor implements HandlerInterceptor  {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
         HandlerMethod handlerMethod = (HandlerMethod) handler;
        LoginRequired loginRequired = handlerMethod.getMethod().getAnnotation(LoginRequired.class);
        if (loginRequired == null) {
            return true;
        }

        String token = httpServletRequest.getParameter("token");

        if (StringUtils.isBlank(token)) {
            throw new MissingParameterException();
        }

        authenticationService.checkToken(token);

        return super.preHandle(httpServletRequest, httpServletResponse, handler);
    }
    @Override
    public void postHandle( HttpServletRequest request, HttpServletResponse response,
            Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("---method executed---");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
            Object handler, Exception ex) throws Exception {
        System.out.println("---Request Completed---");
    }

我们可以创建一个注释:

 @Target({ElementType.METHOD, ElementType.TYPE})
        @Retention(RetentionPolicy.RUNTIME)
        public @interface LoginRequired {
        }

然后在控制器上,我们有了这个注释:

@RequestMapping(value = "/protected/controller")
@LoginRequired
public ResponseEntity<BaseResponse> controller() {
   ...
}

这只是一个模板/示例,可以给你一个想法。 我希望这会对你有所帮助。

答案 2 :(得分:3)

这种事情有一个默认的解决方案。 春天安全。你只需实现类似的东西:

@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error")
                .usernameParameter("email")
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/")
                .permitAll();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(new BCryptPasswordEncoder());
    }
}

它的依赖是:

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

答案 3 :(得分:1)

您应该将此添加到注册拦截器

enemyHealth.currentHealth > 0

答案 4 :(得分:0)

5号春季之后: 实现应该是这样的:我们应该有一个实现

的类
HandlerInterceptor 

    public class CustomInterceptor implements HandlerInterceptorr{
}

然后我们可以通过实现WebMvcConfigurer的类来注册此拦截器 并覆盖方法addInterceptors

public class ServiceInterceptorAppConfig implements WebMvcConfigurer {
  @Autowired
  CustomInterceptor customInterceptor;

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