当我未使用Spring Security登录时,我的身份验证的currentPrincipalName为anonymousUser
,其方法.authenticated()
返回true
。
但是,我的配置要求对某些请求进行身份验证,并且匿名用户被拒绝。
以下是配置代码:
@Override
protected void configure(HttpSecurity http) throws Exception {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
http.addFilterBefore(characterEncodingFilter, CsrfFilter.class);
http
.formLogin()//support form login
.loginPage("/login")
.and()
.authorizeRequests()
.antMatchers("/spitter/me").authenticated()
.antMatchers(HttpMethod.POST, "/spittles").authenticated()
.anyRequest().permitAll();
}
两名antMatchers都阻止匿名用户访问。有原因吗?
编辑:为什么这是重复的?我问的是一个完全不同的问题。这个问题是"为什么它被认证?"我的是#34;它经过验证,但为什么不像一个人一样对待?"。那个问题的答案没有回答我的问题。
完整安全配置源代码:
package spittr.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.web.filter.CharacterEncodingFilter;
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
static{
System.out.println("SecurityConfig loaded");
}
@Autowired
DataSource dataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery("select username, password, enabled "
+ " from spitter where username = ?")
.authoritiesByUsernameQuery("select username, role "
+ " from spitter where username =?")
.passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
http.addFilterBefore(characterEncodingFilter, CsrfFilter.class);
http
.formLogin()//support form login
.loginPage("/login")
.and()
.authorizeRequests()
.antMatchers("/spitters/me").authenticated()
.antMatchers(HttpMethod.POST, "/spittles").authenticated()
.anyRequest().permitAll();
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}