SpringBoot集成Spring Security进行安全控制的时候。
package com.example.boot2security.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 WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()// 定义哪些URL需要被保护、哪些不需要被保护
.antMatchers("/", "/home").permitAll()//指定了/和/home不需要任何认证就可以访问,其他的路径都必须通过身份验证。
.anyRequest()// 任何请求,登录后可以访问
.authenticated()
.and()
.formLogin() //定义当需要用户登录时候,转到的登录页面
.successForwardUrl("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
/**
* 在内存中创建了一个用户,该用户的名称为user,密码为password,用户角色为USER。
* @param auth
* @throws Exception
*/
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("a")
.password("a")
.roles("USER");
}
}
报错:
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
后发通过查询解决,解决办法如下:
在Spring Security 5.0之前,默认值PasswordEncoder
是NoOpPasswordEncoder
需要纯文本密码。
在Spring Security 5中,默认值为DelegatingPasswordEncoder
,这需要密码存储格式。
解决方案1:添加密码存储格式,对于纯文本,添加{noop}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("a")
.password("{noop}a")
.roles("USER");
}
解决方案2 - User.withDefaultPasswordEncoder()
forUserDetailsService
@Bean
public UserDetailsService userDetailsService() {
User.UserBuilder users = User.withDefaultPasswordEncoder();
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(users.username("a").password("a").roles("USER").build());
return manager;
}