【发布时间】:2018-07-17 18:25:20
【问题描述】:
我用 Spring-boot 和 spring security 制作了一个简单的 restAPI,实现了基本身份验证。我想使用 inMemoryAuthentication 和 bcryptPasswordEncoder,但由于某种原因,我的编译器在错误的位置寻找 passwordEncoder,请参阅标题与 security.crypto.password.PasswordEncoder。
我的基本身份验证如下所示:
import org.springframework.context.annotation.Bean;
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;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
Configuration
@EnableWebSecurity
public class BasicAuthConfig extends WebSecurityConfigurerAdapter {
// Authentication : User --> Roles
// NoOpPasswordEncoder has been deprecated in Spring security so {noop} is being used to avoid errors
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication()
.passwordEncoder(passwordEncoder())
.withUser("user1")
.password("{noop}secret1")
.roles("USER")
.and().withUser("admin1")
.password("{noop}secret1")
.roles("USER", "ADMIN");
}
// Authorization : Role -> Access
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.and().authorizeRequests()
.antMatchers("/tokenservice/**")
.hasRole("USER")
.antMatchers("/**")
.hasRole("ADMIN")
.and().csrf()
.disable()
.headers()
.frameOptions()
.and().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
尝试编译时出现此错误:
Error:(21, 7) java: cannot access org.springframework.security.authentication.encoding.PasswordEncoder org.springframework.security.authentication.encoding.PasswordEncoder 的类文件未找到
忽略密码前面的 {noop}。没有密码编码器可以测试吗?
我对 Spring 和 gradle 以及 java 非常陌生。我可以使用错误版本的 Spring 吗?如果是这样,我该如何解决?
【问题讨论】:
-
您好!您能在 gradle 设置中向我们展示您的依赖关系吗?
-
依赖{ compile('org.springframework.boot:spring-boot-starter') compile('org.springframework.boot:spring-boot-starter-web') compile('org.springframework :spring-oxm:4.1.5.RELEASE') 编译('org.codehaus.castor:castor-xml:1.3.3') 编译('org.springframework.security:spring-security-web:4.2.3.RELEASE ') 编译('org.springframework.security:spring-security-config:4.2.3.RELEASE') 编译('org.apache.commons:commons-collections4:4.1') testCompile('org.springframework.boot:spring -boot-starter-test')
-
您的版本似乎不错。检查我的回答,看看它是否能解决您的问题。
标签: spring spring-boot encoding spring-security basic-authentication