当前位置: 首页 > 知识库问答 >
问题:

如何在speingsecurity4xml配置中禁用特定url的安全性以检索访问令牌

齐振
2023-03-14

我开发了一些Rest应用程序,但Spring安全配置存在问题。

在我的Rest应用程序中,帮我处理一下Spring Security 4的xml配置。

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:sec="http://www.springframework.org/schema/security"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
      http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">

<import resource="classpath*:securityServicesContext.xml"/>
<import resource="classpath*:businessServicesContext.xml"/>

<sec:http pattern="/rest/**" create-session="stateless" auto-config="false" entry-point-ref="unauthorizedEntryPoint">
    <sec:expression-handler ref="webSecurityExpressionHandler"/>
    <sec:custom-filter ref="customTokenAuthenticationFilter" position="FORM_LOGIN_FILTER"/>
    <sec:intercept-url pattern="/rest/login" access="permitAll"/>
    <sec:intercept-url pattern="/**" access="hasRole('USER')"/>
    <sec:csrf disabled="true"/>
</sec:http>

<sec:authentication-manager id="authenticationManager">
    <sec:authentication-provider ref="daoAuthenticationProvider"/>
</sec:authentication-manager>

<bean id="unauthorizedEntryPoint" class="com.itechart.security.web.security.UnauthorizedEntryPoint"/>

<bean id="customTokenAuthenticationFilter"
      class="com.itechart.security.web.security.CustomTokenAuthenticationFilter">
    <constructor-arg name="defaultFilterProcessesUrl" value="/rest/**"/>
    <constructor-arg name="authenticationManager" ref="authenticationManager"/>
    <constructor-arg name="authenticationSuccessHandler">
        <bean class="com.itechart.security.web.security.TokenSimpleUrlAuthenticationSuccessHandler"/>
    </constructor-arg>
</bean>

当我发送用户名时

这是我的网络.xml:

<?xml version="1.0" encoding="UTF-8"?>

http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

<display-name>Security Web Application</display-name>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcherServlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/rest/*</url-pattern>
</filter-mapping>

<resource-ref>
    <res-ref-name>jdbc/SecuritySampleDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

<welcome-file-list>
    <welcome-file>/app/index.html</welcome-file>
</welcome-file-list>

更新 1:

public class CustomTokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

private static final Logger logger = LoggerFactory.getLogger(CustomTokenAuthenticationFilter.class);
private String excludedUrl;

public CustomTokenAuthenticationFilter(String excludedUrl, String defaultFilterProcessesUrl, AuthenticationManager authenticationManager, AuthenticationSuccessHandler authenticationSuccessHandler) {
    super(defaultFilterProcessesUrl);
    this.excludedUrl = excludedUrl;
    super.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher(defaultFilterProcessesUrl));
    setAuthenticationManager(authenticationManager);
    setAuthenticationSuccessHandler(authenticationSuccessHandler);
}

public final String HEADER_SECURITY_TOKEN = "X-CustomToken";


/**
 * Attempt to authenticate request - basically just pass over to another method to authenticate request headers
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    String token = request.getHeader(HEADER_SECURITY_TOKEN);
    logger.info("token found:" + token);
    AbstractAuthenticationToken userAuthenticationToken = authUserByToken(token);
    if (userAuthenticationToken == null)
        throw new AuthenticationServiceException(MessageFormat.format("Error | {0}", "Bad Token"));


    return userAuthenticationToken;
}


/**
 * authenticate the user based on token
 *
 * @return
 */
private AbstractAuthenticationToken authUserByToken(String token) {
    if (token == null) {
        return null;
    }
    AbstractAuthenticationToken authToken = null;//todo
    try {
        return authToken;
    } catch (Exception e) {
        logger.error("Authenticate user by token error: ", e);
    }
    return authToken;
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    if (((HttpServletRequest) req).getRequestURI().endsWith(excludedUrl)) {
        chain.doFilter(req, res);
    } else {
        super.doFilter(req, res, chain);
    }
}
}

这是我发送请求时的日志:

21:14:00.805 [http-nio-8080-exec-1] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/rest/test'; against '/rest/**'
21:14:00.808 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy - /rest/test at position 1 of 8 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
21:14:00.818 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy - /rest/test at position 2 of 8 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
21:14:00.826 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy - /rest/test at position 3 of 8 in additional filter chain; firing Filter: 'HeaderWriterFilter'
21:14:00.826 [http-nio-8080-exec-1] DEBUG o.s.s.w.h.writers.HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@1fd019da
21:14:00.827 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy - /rest/test at position 4 of 8 in additional filter chain; firing Filter: 'CustomTokenAuthenticationFilter'
21:14:00.827 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy - /rest/test at position 5 of 8 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
21:14:00.836 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy - /rest/test at position 6 of 8 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
21:14:00.838 [http-nio-8080-exec-1] DEBUG o.s.s.w.a.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
21:14:00.839 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy - /rest/test at position 7 of 8 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
21:14:00.839 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy - /rest/test at position 8 of 8 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
21:14:00.840 [http-nio-8080-exec-1] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/rest/test'; against '/rest/login'
21:14:00.842 [http-nio-8080-exec-1] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/rest/test'; against '/rest/test'
21:14:00.842 [http-nio-8080-exec-1] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /rest/test; Attributes: [permitAll]
21:14:00.843 [http-nio-8080-exec-1] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
21:14:00.862 [http-nio-8080-exec-1] DEBUG o.s.s.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@66e0e4e6, returned: 1
21:14:00.862 [http-nio-8080-exec-1] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Authorization successful
21:14:00.862 [http-nio-8080-exec-1] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - RunAsManager did not change Authentication object
21:14:00.863 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy - /rest/test reached end of additional filter chain; proceeding with original chain
21:14:00.925 [http-nio-8080-exec-1] WARN  o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/rest/test] in DispatcherServlet with name 'dispatcherServlet'
21:14:00.933 [http-nio-8080-exec-1] DEBUG o.s.s.w.a.ExceptionTranslationFilter - Chain processed normally
21:14:00.933 [http-nio-8080-exec-1] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed

共有1个答案

阚允晨
2023-03-14

您可以在CustTokenAuthenticationFilter中添加对url的检查,并绕过过滤规则,以防目标是/rest/login。考虑这个例子:

    @Override
    protected final void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException,
                    IOException {
        if (!request.getRequestURL().toString().endsWith("rest/login")) { 
            ... apply filtering logic...
        }
        filterChain.doFilter(request, response);
    }
 类似资料:
  • 我将Spring security用于包含一组Restful服务的Spring启动应用程序。我已经通过基本身份验证启用了网络安全。我希望启用基本的身份验证,除了以特定模式结尾的特定API URL。(例如,healthcheck API,如:/application/_healthcheck) 代码如下所示: 然而,每当我调用/应用程序/_HealthCheckURL,浏览器总是提示我输入凭据。 或

  • 我有一个Angular4应用程序托管在Azure Web应用程序和一个应用程序中。NET核心Web API托管在Azure API应用程序中。 该API由Azure Active Directory保护。目前,我使用ng2 adal获取一个访问令牌,并将其注入头中以执行API调用。 现在,我尝试删除ng2 adal模块,并使用相同的ClientId(如API)使用身份验证/授权功能保护我的Web应

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

  • 本任务将演示如何通过使用Istio认证提供的服务账户,来安全地对服务做访问控制。 当Istio双向TLS认证打开时,服务器就会根据其证书来认证客户端,并从证书获取客户端的服务账户。服务账户在source.user的属性中。请参考Istio auth identity了解Istio中服务账户的格式。 开始之前 根据quick start的说明在开启认证的Kubernetes中安装Istio。注意,应

  • 问题内容: 我正在使用无状态Spring Security,但是如果要注册,我想禁用Spring Security。我禁用了 但它不起作用,我在下面收到错误消息: 我认为这意味着弹簧安全过滤器正在工作 我的网址顺序始终为“ / api / v1” 我的spring配置是 我的身份验证过滤器是 我的控制器是 我怎么做? 问题答案: 使用它意味着每个经过身份验证的用户,但是你禁用了匿名访问,因此将无法

  • 我已经在使用Java 8,它是Nashorn javascript引擎。在我的应用程序中,我出于各种目的从Java classess访问javaScript脚本文件。然而,也可以从javaScript代码访问Java类。但由于我的应用程序中的Javascript也可以由第三方编写,所以我想限制它们(JS脚本)访问Java模块。(特别禁止某些Java类) 我不想限制对Java类的所有访问,只是想寻找