当前位置: 首页 > 面试题库 >

如何禁用特定URL的Spring Security

颜啸
2023-03-14
问题内容

我正在使用无状态Spring Security,但是如果要注册,我想禁用Spring Security。我禁用了

antMatchers("/api/v1/signup").permitAll().

但它不起作用,我在下面收到错误消息:

 message=An Authentication object was not found in the SecurityContext, type=org.springframework.security.authentication.AuthenticationCredentialsNotFoundException

我认为这意味着弹簧安全过滤器正在工作

我的网址顺序始终为“ / api / v1”

我的spring配置是

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

         http.
         csrf().disable().
         sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
         and().
         authorizeRequests().
         antMatchers("/api/v1/signup").permitAll().
         anyRequest().authenticated().
         and().
         anonymous().disable();
        http.addFilterBefore(new AuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class);
    }

我的身份验证过滤器是

@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = asHttp(request);
        HttpServletResponse httpResponse = asHttp(response);

        String username = httpRequest.getHeader("X-Auth-Username");
        String password = httpRequest.getHeader("X-Auth-Password");
        String token = httpRequest.getHeader("X-Auth-Token");

        String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest);

        try {

            if (postToAuthenticate(httpRequest, resourcePath)) {            
                processUsernamePasswordAuthentication(httpResponse, username, password);
                return;
            }

            if(token != null){
                processTokenAuthentication(token);
            }
            chain.doFilter(request, response);
        } catch (InternalAuthenticationServiceException internalAuthenticationServiceException) {
            SecurityContextHolder.clearContext();
            logger.error("Internal authentication service exception", internalAuthenticationServiceException);
            httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (AuthenticationException authenticationException) {
            SecurityContextHolder.clearContext();
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());
        } finally {
        }
    }

     private HttpServletRequest asHttp(ServletRequest request) {
            return (HttpServletRequest) request;
        }

        private HttpServletResponse asHttp(ServletResponse response) {
            return (HttpServletResponse) response;
        }

        private boolean postToAuthenticate(HttpServletRequest httpRequest, String resourcePath) {
            return Constant.AUTHENTICATE_URL.equalsIgnoreCase(resourcePath) && httpRequest.getMethod().equals("POST");
        }

        private void processUsernamePasswordAuthentication(HttpServletResponse httpResponse,String username, String password) throws IOException {
            Authentication resultOfAuthentication = tryToAuthenticateWithUsernameAndPassword(username, password);
            SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication);
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            httpResponse.addHeader("Content-Type", "application/json");
            httpResponse.addHeader("X-Auth-Token", resultOfAuthentication.getDetails().toString());
        }

        private Authentication tryToAuthenticateWithUsernameAndPassword(String username,String password) {
            UsernamePasswordAuthenticationToken requestAuthentication = new UsernamePasswordAuthenticationToken(username, password);
            return tryToAuthenticate(requestAuthentication);
        }

        private void processTokenAuthentication(String token) {
            Authentication resultOfAuthentication = tryToAuthenticateWithToken(token);
            SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication);
        }

        private Authentication tryToAuthenticateWithToken(String token) {
            PreAuthenticatedAuthenticationToken requestAuthentication = new PreAuthenticatedAuthenticationToken(token, null);
            return tryToAuthenticate(requestAuthentication);
        }

        private Authentication tryToAuthenticate(Authentication requestAuthentication) {
            Authentication responseAuthentication = authenticationManager.authenticate(requestAuthentication);
            if (responseAuthentication == null || !responseAuthentication.isAuthenticated()) {
                throw new InternalAuthenticationServiceException("Unable to authenticate Domain User for provided credentials");
            }
            logger.debug("User successfully authenticated");
            return responseAuthentication;
        }

我的控制器是

@RestController
public class UserController {

    @Autowired
    UserService userService;

    /**
     * to pass user info to service
     */
    @RequestMapping(value = "api/v1/signup",method = RequestMethod.POST)
    public String saveUser(@RequestBody User user) {
        userService.saveUser(user);
        return "User registerted successfully";
    }
}

我怎么做?


问题答案:

使用permitAll它意味着每个经过身份验证的用户,但是你禁用了匿名访问,因此将无法使用。

你想要的是忽略某些URL,从而覆盖configure采用WebSecurity对象和ignore模式的方法。

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

然后从HttpSecurity零件中删除该线。这将告诉Spring Security忽略该URL,并且不对其应用任何过滤器。



 类似资料:
  • 我的控制器是 我对Spring完全陌生,请帮帮我怎么做?

  • Csrf筛选器验证从“验证”提交的Csrf令牌,当我从HTTP向https提交请求时,抛出无效令牌异常(403)。如何在这种情况下禁用csrf令牌身份验证?

  • 问题内容: 我在项目中配置了一个checkstyle验证规则,该规则禁止使用超过3个输入参数来定义类方法。该规则适用于我的类,但有时我必须扩展第三方类,而第三方类则不遵守此特定规则。 是否有可能指示“ checkstyle”某种方法应以静默方式忽略? 问题答案: 在http://checkstyle.sourceforge.net/config_filters.html#SuppressionCo

  • 我将Spring security用于包含一组Restful服务的Spring启动应用程序。我已经通过基本身份验证启用了网络安全。我希望启用基本的身份验证,除了以特定模式结尾的特定API URL。(例如,healthcheck API,如:/application/_healthcheck) 代码如下所示: 然而,每当我调用/应用程序/_HealthCheckURL,浏览器总是提示我输入凭据。 或

  • 我有一个微服务,它主要使用与其他微服务对话。使用Eureka的服务发现机制,这项工作非常出色。 现在我迫切需要使用连接到外部系统,并且仍然使用如下所示的配置执行负载平衡。 : : 从我看过的许多文档中,建议禁用eureka以允许从可用的服务器列表中获取负载平衡。我做了跟进,并使用以下配置禁用它。 : 这使我能够为针对外部系统的外部客户端执行负载平衡,但需要使用服务发现的所有其他外部客户端都已中断。

  • 我想你可以想象家务控制器中有什么,但为了完整起见,这里有相关的部分: 下面是测试在输出中打印的请求: 那么,为什么我的测试会得到401的返回代码,我如何修复它?