2017-02-21 92 views
1

以下是我的春季安全配置示例。如何在Spring Security中爲401 REST API調用返回401?

我希望所有/api都返回HTTP 401代碼,而不是將302重定向到登錄頁面。

另外我想保留舊網頁的重定向功能。

<security:http auto-config='true' use-expressions="true" > 
    <security:intercept-url pattern="/api*" access="hasRole('USER')" /> 
    <security:intercept-url pattern="/oldweb*" access="hasRole('USER')" /> 

    <security:form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1" default-target-url="/home"/>  
</security:http> 

回答

1

您需要有一個自定義身份驗證入口點。

public class CustomEntryPoint extends LoginUrlAuthenticationEntryPoint { 

    private static final String XML_HTTP_REQUEST = "XMLHttpRequest"; 
    private static final String X_REQUESTED_WITH = "X-Requested-With"; 

    public CustomEntryPoint(String loginFormUrl) { 
     super(loginFormUrl); 
    } 

    @Override 
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) 
      throws IOException, ServletException { 
     if (XML_HTTP_REQUEST.equals(request.getHeader(X_REQUESTED_WITH))) { 
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED); 
     } else { 
      super.commence(request, response, exception); 
     } 
    }  
} 

你的配置最後改成這樣:

<security:http auto-config='true' use-expressions="true" entry-point-ref="customEntryPoint"> 
    <security:intercept-url pattern="/api*" access="hasRole('USER')" /> 
    <security:intercept-url pattern="/oldweb*" access="hasRole('USER')" /> 

    <security:form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1" default-target-url="/home"/> 

    <beans:bean id="customEntryPoint" class="CustomEntryPoint"> 
     <beans:constructor-arg value="/login"/> 
    </beans:bean>  
</security:http> 
1

我來更簡單的解決方案。 在Spring Boot和Java配置中,除了缺省值之外,您只需註冊其他入口點。而且因爲所有的休息服務都駐留在「/ api」名稱空間中,所以您可以使用AntPathRequestMatcher("/api/**")來匹配必要的請求。

所以,最終的解決方案是:

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
    http.exceptionHandling() 
        //Actually Spring already configures default AuthenticationEntryPoint - LoginUrlAuthenticationEntryPoint 
        //This one is REST-specific addition to default one, that is based on PathRequest 
        .defaultAuthenticationEntryPointFor(getRestAuthenticationEntryPoint(), new AntPathRequestMatcher("/api/**")); 
    } 

    private AuthenticationEntryPoint getRestAuthenticationEntryPoint() { 
     return new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED); 
    } 
} 
相關問題