我正在使用基于Spring Security 4 XML的配置。
这是我的配置(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;
}
}
当我使用用户/密码通过邮递员POST
向http://localhost:8080/login
发送Metascore
时,看起来REST功能不起作用:user / q it that
凭据错误
但是当我在浏览器中通过表单执行同样的操作时,它可以正常工作。
那么,有什么方法可以使REST功能起作用吗?
答案 0 :(得分:1)
以下代码将为您提供用户名和密码的base64编码值。使用它来添加HTTP标头如下:
String plainClientCredentials="myusername:mypassword";
String base64ClientCredentials = new String(Base64.encodeBase64(plainClientCredentials.getBytes()));
System.out.println(base64ClientCredentials);`
在标题中设置:
密钥授权,Value-Basicbase64ClientCredentials
假设代码打印123&78#
那么价值就是Basic123&78#
。