春季启动:将Servlet过滤器应用于除一条

时间:2018-11-20 15:18:49

标签: java spring spring-boot jwt servlet-filters

一个关于弹簧靴大师的问题!

用例:

我希望我的应用程序的行为取决于以下路由:

  • /没有身份验证,没有授权
  • / render通过作为URL参数发送的json网络令牌(jwt)进行授权(我知道,这很奇怪)
  • 其他任何途径:通过作为URL参数发送的json网络令牌(jwt)进行授权(我知道,这很奇怪)

jwt的秘密存储为应用程序配置(application.yaml)的元素(我知道这不是最佳实践,因为它是演示应用程序,所以我不在乎)

我正在使用SpringBoot 2.0.5io.jsonwebtoken作为jwt库。

我已经使用Servlet过滤器实现了它,并且可以正常工作,但是感觉真的很丑。我找不到说“ 将此Servlet过滤器应用于除此列表以外的所有端点”的方法。我已经将逻辑包含在doFilter方法中,但是这个看起来确实很丑

这是否有“最佳实践”?

我当前的代码如下:

SecurityConfiguration

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/render").permitAll()
            .anyRequest().authenticated();
    httpSecurity.headers().frameOptions().disable();
}
}

WebConfigurer

import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Configuration;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.EnumSet;

@Configuration
public class WebConfigurer implements ServletContextInitializer {

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
        EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);
        initFilter(servletContext, disps);
}

private void initFilter(ServletContext servletContext,
                            EnumSet<DispatcherType> disps) {
FilterRegistration.Dynamic myFilter =
                servletContext.addFilter("myFilter",
                        new JWTAuthenticationFilter());

myFilter.addMappingForUrlPatterns(disps, true, "/app/*");
myFilter.setAsyncSupported(true);
}
}

JWTAuthenticationFilter

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.impl.TextCodec;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JWTAuthenticationFilter extends GenericFilterBean {

    @Value("${security.jwt.token.secret-key}")
    private String secret;

    @Override
    public void doFilter(ServletRequest req,
                         ServletResponse res,
                         FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        try {
            String path = request.getRequestURI();
            if (!path.equals("/")) {

                String jwsString = request.getParameter("jwt");
                Jws<Claims> jws;

                String base64_encoded_secret = TextCodec.BASE64.encode(secret);

                jws = Jwts.parser()
                        .setSigningKey(base64_encoded_secret)
                        .parseClaimsJws(jwsString);
            }
        } catch (Exception e) {
            System.out.println(e);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed");
            SecurityContextHolder.clearContext();
        }
        filterChain.doFilter(request, response);
    }
}

1 个答案:

答案 0 :(得分:0)

找到了解决方案!我使用了FilterRegistrationBean。无法排除URL。我的解决方案是将所有应用程序放在app /目录下,因此我不需要在根目录/上放置过滤器。

@Bean
public FilterRegistrationBean FilterRegistration() {
    FilterRegistrationBean registration = new  FilterRegistrationBean();
    registration.setFilter(filter);
    registration.setOrder(1);
    registration.addUrlPatterns("/app/*");
    return registration;
}