我正在构建Web应用程序,我想通过用户名和密码添加日志记录,我一开始就做了类似的事情,然后通过db传递来添加日志记录。
package com.webservice.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter{
@Autowired
private AuthenticationEntryPoint entrypoint;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("pass").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().httpBasic()
.authenticationEntryPoint(entrypoint);
}
身份验证入口点类如下
package com.webservice.config;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
@Component
public class AuthenticationEntryPoint extends BasicAuthenticationEntryPoint{
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.addHeader("WWW-Authenticate", "Basic realam - " + getRealmName());
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
writer.println("Http Status 401 " + authException.getMessage());
}
@Override
public void afterPropertiesSet() {
setRealmName("MyWebService");
super.afterPropertiesSet();
}
}
该应用程序正常启动,但是当我在浏览器中输入本地主机行时,它会立即从Authntication入口点抛出信息,并且无需输入用户名和密码
Http Status 401 Full authentication is required to access this resource
我该怎么办?
答案 0 :(得分:0)
Basic realm
标头中有一个错字。如下所示进行更改:
response.addHeader("WWW-Authenticate", "Basic realm = " + getRealmName());
要求对密码进行编码,而不是将其存储为纯文本。如下所示修改您的内存中身份验证配置:
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
auth.inMemoryAuthentication().withUser("user").password(encoder.encode("pass")).roles("USER");
}