引入SpringSecurity的依赖:
org.springframework.boot spring-boot-starter-security
然后启动项目,会发现项目已被SpringSecurity接管,进入任何页面之前都要登录,下面是SpringSecurity的默认登录页:
在后端会有一个随机密码生成,使用user用户登录就可以进入其他页面。
为了实现自定义用户名密码的认证,可以通过在application.properties中添加属性spring.security.user.name和spring.security.user.password来实现,也可以通过代码实现。代码的实现方式是继承WebSecurityConfigurerAdapter类(注意不要忘了@Configuration注解),覆写其中的configure(AuthenticationManagerBuilder auth)方法:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
String encode = new BCryptPasswordEncoder().encode("123456");
auth.inMemoryAuthentication().withUser("root").password(encode).roles("root");
}
@Bean
public PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
密码一般都要加密,加密方式必须使用@Bean注解,否则会报错There is no PasswordEncoder mapped for the id "null"。
正常业务的用户名和密码需要查询数据库,这是需要使用UserDetailsService接口。编写一个类实现该接口,然后返回UserDetails类型的对象:
@Service("myUserDetailsService")
public class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
List list = AuthorityUtils.commaSeparatedStringToAuthorityList("root");
return new User("root", new BCryptPasswordEncoder().encode("123456"), list);
}
}
这里为了简便,没有查询数据库,而是将用户名密码以及权限在程序中写死,后期会链接数据库。而刚才的configure(AuthenticationManagerBuilder auth)方法中的内容为:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(getPasswordEncoder());
}
其中的userDetailsService为Spring自动注入的私有属性。以上就是实现权限认证的三种方式。



