2017-03-13 32 views
-1

我正在使用Spring Security 4基於XML的配置。如何將REST基本認證添加到現有的XML Spring Security配置中?

這是我的配置(security.xml):

<!--?xml version="1.0" encoding="UTF-8"?--> 
<beans:beans xmlns="http://www.springframework.org/schema/security" 
      xmlns:beans="http://www.springframework.org/schema/beans" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
      http://www.springframework.org/schema/security 
      http://www.springframework.org/schema/security/spring-security.xsd"> 

    <http create-session="always" 
     use-expressions="true" 
     authentication-manager-ref="authenticationManager" 
     entry-point-ref="authenticationEntryPoint"> 
     <csrf disabled="true" /> 
     <intercept-url pattern="/**" access="hasRole('USER')" /> 
     <form-login authentication-success-handler-ref="customAuthenticationSuccessHandler" /> 
     <logout /> 
    </http> 

    <authentication-manager alias="authenticationManager"> 
     <authentication-provider user-service-ref="userDao"></authentication-provider> 
    </authentication-manager> 

</beans:beans> 

這裏是我的CustomEntryPoint

@Component 
public class CustomEntryPoint implements AuthenticationEntryPoint { 

    @Override 
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { 
     System.out.println("Entering commence due to failed Authentication"); 
     response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized Access!"); 
    } 

} 

和我UserDao(以備將來讀從文件的憑據):

public class UserDao implements UserDetailsService { 

    @Override 
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 

     String password = readPasswordFromFileOrDatabase(username); 

     if (password == null) throw new UsernameNotFoundException("failure"); 
     return User.withUsername("user").password(password).authorities("ROLE_USER").build(); 
    } 

    private String readPasswordFromFileOrDatabase(String username) { 
     if (username.equals("user")) return "q"; 
     return null; 
    } 


} 

它看起來像REST feauture不起作用,w母雞我送POST通過郵遞員http://localhost:8080/login與用戶名/密碼:用戶/ Q,它說

認證錯誤

但是當我通過形式瀏覽器做同樣的事情,它工作正常。

那麼,有什麼方法可以使REST功能發揮作用嗎?

回答

1

以下代碼將爲您提供用戶名和密碼的base64編碼值。用它來HTTP報頭添加如下:

String plainClientCredentials="myusername:mypassword"; 
String base64ClientCredentials = new String(Base64.encodeBase64(plainClientCredentials.getBytes())); 
System.out.println(base64ClientCredentials);` 

在設置該標頭:

密鑰 - 授權,價值Basicbase64ClientCredentials

假設代碼打印123&78# 然後值將是Basic123&78#

+0

不知道它是否工作,因爲添加標題後,我得到了相同的行爲 –

相關問題