title: How to return 401 for REST API call in Spring Security?
body: <p>Following is my sample Spring Security configuration. </p>
  
  <p>I want all <code>/api</code> to return HTTP 401 code instead of redirecting 302 to login page.</p>
  
  <p>Also I want to keep the redirect feature for old web pages.</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;security:http auto-config='true' use-expressions="true" &gt;
      &lt;security:intercept-url pattern="/api*" access="hasRole('USER')" /&gt;
      &lt;security:intercept-url pattern="/oldweb*" access="hasRole('USER')" /&gt;
  
      &lt;security:form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1" default-target-url="/home"/&gt;    
  &lt;/security:http&gt;
  </code></pre>