网站后台模块,网站建设 问答,网站首页被k 做跳转,网站开发工程师获奖WebSecurityConfigurerAdapter配置文件在
configure(AuthenticationManagerBuilder auth)
方法中完成身份认证。前面的demo都只有一个用户#xff0c;security中使用UserDetailsService做为用户数据源 #xff0c;所以可以实现UserDetailsService 接口来自定义用户。实现方…WebSecurityConfigurerAdapter配置文件在
configure(AuthenticationManagerBuilder auth)
方法中完成身份认证。前面的demo都只有一个用户security中使用UserDetailsService做为用户数据源 所以可以实现UserDetailsService 接口来自定义用户。实现方法可以有几下几种
1内容用户
2JDBC读取
3自定义UserDetailsService
4自定义AuthenticationProvider
一、使用内存用户验证InMemoryUserDetailsManager
1、代码改动
package com.security.demo.config;import org.springframework.security.crypto.password.PasswordEncoder;public class MyPasswordEncoder implements PasswordEncoder {Overridepublic String encode(CharSequence charSequence) {return charSequence.toString();}Overridepublic boolean matches(CharSequence charSequence, String s) {return s.equals(charSequence.toString());}
}配置类中configure(AuthenticationManagerBuilder auth)方法覆盖身份认证
//身份认证
Overridepublic void configure(AuthenticationManagerBuilder auth) throws Exception {//可以设置内存指定的登录的账号密码,指定角色不加.passwordEncoder(new MyPasswordEncoder())就不是以明文的方式进行匹配会报错:java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id nullauth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser(admin).password(123).roles(xtgly);auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser(zs).password(123).roles(userAdmin,roleAdmin);auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser(ls).password(123).roles(schoolAdmin);//加上.passwordEncoder(new MyPasswordEncoder())。页面提交时候密码以明文的方式进行匹配。}
2、测试重启项目控制台不再输出随机的默认密码
输入正常的账号密码跳转到目标接口输入错误的账号密码跳转到登陆错误页面。
二、JDBC方式
1、代码
Autowired
DataSource dataSource;Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.jdbcAuthentication().dataSource(dataSource)// 下面的方法会运行数据表初始化脚本前提是你的数据库支持varchar_ignorecase字段类型// .withDefaultSchema()//使用自定义sql查询用户信息.usersByUsernameQuery(select username,password,enabled from users where username ?).withUser(tester).password(passwordEncoder.encode(123456)).authorities(tester).and().withUser(user).password(passwordEncoder.encode(123456)).authorities(tester);
}
三、 自定义UserDetailsService
四、自定义AuthenticationProvider这是实际应用中常用的方法。