java—如何绕过特定域的已验证端点上的Spring Security ?

tjrkku2a  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(303)

我正在使用基于jwt令牌的Spring Security 。我有一个端点“/sample endpoint”,它需要身份验证。但是,当请求来自一个名为xyz.com的特定域时,我需要绕过该端点的安全性。
有可能吗?如果是,如何做到这一点?
这是我到目前为止所拥有的。
证券配置

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

// cant add the end point here as it would open up for everybody.
public static final String[] unauthedUrls = { "healthcheck","some-other-endpoint"}  

@Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .httpBasic()
                .disable()
                .csrf()
                .disable()
                .cors()
                .and()
                .headers().frameOptions()
                .disable()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .and()
                .addFilterAfter(jwtSecurityFilter, UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests()
                .antMatchers(unauthedUrls)
                .permitAll()
                .anyRequest()
                .authenticated();
    }

下面是jwtsecurityfilter实现。

public class JwtSecurityFilter extends OncePerRequestFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtSecurityFilter.class);

    private static final String JWT_PREFIX = "Bearer ";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        setAuthenticationContext(request);

        chain.doFilter(request, response);
    }

    private void setAuthenticationContext(HttpServletRequest request) {
        try {
            String token = getJwt(request);

            if (StringUtils.isBlank(token)) {
                throw new RuntimeException("Authorization token not provided");
            }

// some logic here...
        } catch (Exception ex) {

            if (request != null && Arrays.stream(SecurityConfig.unauthedUrls).anyMatch(url -> request.getRequestURI().contains(url))) {
                // it's a URL that isn't authenticated so an exception here is normal
                // if we couldn't get a token
                return;
            }
            LOGGER.warn("Unable to authenticate request: {} {}", ex.getMessage(), request == null ? null : request.getRequestURI());
        }
    }

    private String getJwt(HttpServletRequest request) {

        String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);

        if (StringUtils.isBlank(authHeader) || !authHeader.startsWith(JWT_PREFIX)) {
            return "";
        }

        return authHeader.replaceFirst(Pattern.quote(JWT_PREFIX), "");
    }
}
70gysomp

70gysomp1#

您要做的是忽略特定的URL,以覆盖获取websecurity对象并忽略模式的configure方法。例如,使用api:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/api/v1/signup");
}

并从httpsecurity部分中删除该行。这将告诉spring security忽略此url,并且不对其应用任何筛选器。
我有一个更好的方法:

http
    .authorizeRequests()
    .antMatchers("/api/v1/signup/**").permitAll()
    .anyRequest().authenticated()

相关问题