1、什么是SpringSecurity
Spring
Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring
IoC,DI(控制反转Inversion
of Control ,DI:Dependency
Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。
2、结合SpringBoot使用步骤
<!-->spring-boot 整合security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
知道HttpBasic模式与FormLogin模式的区别,代码第29行;
http.authorizeRequests().antMatchers(“/**”).fullyAuthenticated().and().httpBasic();
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAuthenticationFailureHandler failureHandler;
@Autowired
private MyAuthenticationSuccessHandler successHandler;
// 配置认证用户信息和权限
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 添加admin账号
auth.inMemoryAuthentication().withUser("admin").password("123456").
authorities("showOrder","addOrder","updateOrder","deleteOrder");
// 添加userAdd账号
auth.inMemoryAuthentication().withUser("userAdd").password("123456").authorities("showOrder","addOrder");
// 如果想实现动态账号与数据库关联 在该地方改为查询数据库
}
// 配置拦截请求资源
protected void configure(HttpSecurity http) throws Exception {
// 如何权限控制 给每一个请求路径 分配一个权限名称 让后账号只要关联该名称,就可以有访问权限
http.authorizeRequests()
// 配置查询订单权限
.antMatchers("/showOrder").hasAnyAuthority("showOrder")
.antMatchers("/addOrder").hasAnyAuthority("addOrder")
.antMatchers("/login").permitAll()
.antMatchers("/updateOrder").hasAnyAuthority("updateOrder")
.antMatchers("/deleteOrder").hasAnyAuthority("deleteOrder")
.antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login").
successHandler(successHandler).failureHandler(failureHandler)
.and().csrf().disable();
}
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
}
处理登陆是否成功的两个过滤器;再加上上边低30的代码;
//认证失败
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse res, AuthenticationException auth)
throws IOException, ServletException {
System.out.println("登陆失败!");
res.sendRedirect("http://mayikt.com");
}
}
// 认证成功
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication arg2)
throws IOException, ServletException {
System.out.println("用户认证成功");
res.sendRedirect("/");
}
}
更改403报错信息下边两个:
/**
* 自定义 WEB 服务器参数 可以配置默认错误页面
* @version 2018年11月12日
*/
@Configuration
public class WebServerAutoConfiguration {
@Bean
public ConfigurableServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400");
ErrorPage errorPage401 = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401");
ErrorPage errorPage403 = new ErrorPage(HttpStatus.FORBIDDEN, "/error/403");
ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
ErrorPage errorPage415 = new ErrorPage(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "/error/415");
ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
factory.addErrorPages(errorPage400, errorPage401, errorPage403, errorPage404, errorPage415, errorPage500);
return factory;
}
}
@Controller
public class ErrorController {
// 403权限不足页面
@RequestMapping("/error/403")
public String error() {
return "/error/403";
}
}
@Controller
public class OrderController {
// 首页
@RequestMapping("/")
public String index() {
return "index";
}
// 查询订单
@RequestMapping("/showOrder")
public String showOrder() {
return "showOrder";
}
// 添加订单
@RequestMapping("/addOrder")
public String addOrder() {
return "addOrder";
}
// 修改订单
@RequestMapping("/updateOrder")
public String updateOrder() {
return "updateOrder";
}
// 删除订单
@RequestMapping("/deleteOrder")
public String deleteOrder() {
return "deleteOrder";
}
// 自定义登陆页面
@GetMapping("/login")
public String login() {
return "login";
}
}
11.12 PPT.pptxspringboot-security.docx上课代码.zip
3、将SecurityConfig配置成动态的
先总结一个什么是RBAC权限模型
就是基于角色的权限访问控制,在五张表的基础上做扩展;用户表,角色表,权限表,用户角色关联表,角色权限关联表;
public interface UserMapper {
// 查询用户信息
@Select(" select * from sys_user where username = #{userName}")
User findByUsername(@Param("userName") String userName);
// 查询用户的权限
@Select(" select permission.* from sys_user user" + " inner join sys_user_role user_role"
+ " on user.id = user_role.user_id inner join "
+ "sys_role_permission role_permission on user_role.role_id = role_permission.role_id "
+ " inner join sys_permission permission on role_permission.perm_id = permission.id where user.username = #{userName};")
List<Permission> findPermissionByUsername(@Param("userName") String userName);
}
// 设置动态用户信息
@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 1.根据用户名称查询数据用户信息
User user = userMapper.findByUsername(username);
// 2.底层会根据数据库查询用户信息,判断密码是否正确
// 3. 给用户设置权限
List<Permission> listPermission = userMapper.findPermissionByUsername(username);
System.out.println("username:" + username + ",对应权限:" + listPermission.toString());
if (listPermission != null && listPermission.size() > 0) {
// 定义用户权限
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (Permission permission : listPermission) {
authorities.add(new SimpleGrantedAuthority(permission.getPermTag()));
}
user.setAuthorities(authorities);
}
return user;
}
}
// Security 配置
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAuthenticationFailureHandler failureHandler;
@Autowired
private MyAuthenticationSuccessHandler successHandler;
@Autowired
private MyUserDetailsService myUserDetailsService;
@Autowired
private PermissionMapper permissionMapper;
// 配置认证用户信息和权限
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// // 添加admin账号
// auth.inMemoryAuthentication().withUser("admin").password("123456").
// authorities("showOrder","addOrder","updateOrder","deleteOrder");
// // 添加userAdd账号
// auth.inMemoryAuthentication().withUser("userAdd").password("123456").authorities("showOrder","addOrder");
// 如果想实现动态账号与数据库关联 在该地方改为查询数据库
//如果需要加密则增加passwordEncoder,如果不需要则不用加;
auth.userDetailsService(myUserDetailsService).passwordEncoder(new PasswordEncoder() {
// 加密的密码与数据库密码进行比对CharSequence rawPassword 表单字段 encodedPassword
// 数据库加密字段
public boolean matches(CharSequence rawPassword, String encodedPassword) {
System.out.println("rawPassword:" + rawPassword + ",encodedPassword:" + encodedPassword);
// 返回true 表示认证成功 返回fasle 认证失败
return MD5Util.encode((String) rawPassword).equals(encodedPassword);
}
// 对表单密码进行加密
public String encode(CharSequence rawPassword) {
System.out.println("rawPassword:" + rawPassword);
return MD5Util.encode((String) rawPassword);
}
});
}
// 配置拦截请求资源
protected void configure(HttpSecurity http) throws Exception {
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests = http
.authorizeRequests();
// 1.读取数据库权限列表
List<Permission> listPermission = permissionMapper.findAllPermission();
for (Permission permission : listPermission) {
// 设置权限
authorizeRequests.antMatchers(permission.getUrl()).hasAnyAuthority(permission.getPermTag());
}
authorizeRequests.antMatchers("/login").permitAll().antMatchers("/**").fullyAuthenticated().and().formLogin()
.loginPage("/login").successHandler(successHandler).and().csrf().disable();
}
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
}
工具类学习
public class MD5Util {
// 加盐
private static final String SALT = "mayikt";
public static String encode(String password) {
password = password + SALT;
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
throw new RuntimeException(e);
}
char[] charArray = password.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
public static void main(String[] args) {
System.out.println(MD5Util.encode("123456"));
}
}
其实用户权限的信息存放在session里的,应用spring-session框架可以做一些优化处理;