部分引自 www.javaboy.org
手动配置用户名密码有两种方式
1.配置文件的方式
在application.properties
中
spring.security.user.name=yzn
spring.security.user.password=123
spring.security.user.roles=admin
启动测试
2.采取java代码配置
将application.properties
中配置注释掉,新建config目录,新建配置类
package org.javaboy.security.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("yzn").password("123").roles("admin")
.and()
.withUser("test").password("123").roles("user");
}
}
这种方式本来是没有问题的,但是Spring5以后需要对密码进行加密,否则无法正确登录
为了演示方便,我先不加密,但需要使用一个过期方法
package org.javaboy.security.config;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("yzn").password("123").roles("admin")
.and()
.withUser("test").password("123").roles("user");
}
@Bean
PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
}
但两种方式都是写死的,项目中应该结合数据库动态管理
网友评论