SrpingSecurity项目学习 1

标签: Security  java  mybatis  数据库  spring boot  mysql

基于spring Security的后台管理系统

简介

一个很普通的后台管理项目,后台使用了一些较大众的框架:springboot,mybatis,springSecurity等。前台用的是vue+element ui。前后端分离。有需要看源码的同学可以到github中取:
链接: spring Security.
后续还会持续更新活完善这个项目的。

项目结构

项目中的pom配置和properties、config配置详解:

  1. 创建出一个maven项目 ,导入基本的springboot依赖、mysql驱动包、druid连接池、security安全认证;
  2. 具体pom文件如下:
 <dependencies>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
       </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-data-redis</artifactId>
       </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-aop</artifactId>
       </dependency>
       <dependency>
           <groupId>org.projectlombok</groupId>
           <artifactId>lombok</artifactId>
           <scope>provided</scope>
       </dependency>
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <scope>runtime</scope>
       </dependency>
       <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>druid</artifactId>
           <version>1.1.10</version>
       </dependency>
       <dependency>
           <groupId>tk.mybatis</groupId>
           <artifactId>mapper-spring-boot-starter</artifactId>
           <version>2.0.3-beta1</version>
       </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-security</artifactId>
       </dependency>
       <!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
       <dependency>
           <groupId>io.jsonwebtoken</groupId>
           <artifactId>jjwt</artifactId>
           <version>0.9.1</version>
       </dependency>
       <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>fastjson</artifactId>
       </dependency>
   </dependencies>
  1. application.yml 中加入数据库和mybatis的配置,已及redis的配置(redis作为登陆用户数据缓存)
server:
  port: 32001

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://127.0.0.1:3306/server?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
    username: root
    password: 123456
  redis:
#sentinel:
    ##      nodes: 127.0.0.1:26379,127.0.0.1:26389,127.0.0.1:26399
    ##      master: mymaster
    database: 0
    password:
    timeout: 10000ms
    jedis:
      pool:
        max-wait: 10000ms
        max-active: 50
        max-idle: 50
        min-idle: 1
    host: 127.0.0.1

mybatis:
  type-aliases-package: package com.mot.mapper
  mapper-locations: classpath:mapper/*.xml
  #配置驼峰下划线
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  1. SpringSecurity 配置
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  AuthDetailsUserService authDetailsUserService;

  @Autowired
  JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

  @Autowired
  GlobalSettingConfig globalSettingConfig;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
      http
              //开启跨站攻击防御,首次XSRF-TOKEN放在cookie中,并允许访问cookie,后面每次请求需要在请求头中加入X-XSRF-TOKEN
              .csrf()
              .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
              .ignoringAntMatchers(getWhiteList())
              //跨域访问
              .and().cors()
              //判断是否登录拦截器
              .and().addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
              //权限判断方法
              .authorizeRequests()
              .antMatchers(getWhiteList()).permitAll()
              .anyRequest().access("@userPermissionService.hasPermission(request,authentication)")
              //设置无session状态
              .and().sessionManagement()
              .sessionCreationPolicy(SessionCreationPolicy.STATELESS);;
  }

  private String[] getWhiteList() {
      return new String[]{"/"+URLConstant.LOGIN_URL_01};
  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
      auth.userDetailsService(authDetailsUserService).passwordEncoder(passwordEncoder());
  }

  @Bean
  PasswordEncoder passwordEncoder(){
      return new BCryptPasswordEncoder();
  }

  @Bean
  AuthenticationManager getAuthenticationManager() throws Exception {
      return super.authenticationManagerBean();
  }

  @Bean
  CorsConfigurationSource corsConfigurationSource(){
      CorsConfiguration configuration = new CorsConfiguration();
      configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080"));
      configuration.setAllowedMethods(Arrays.asList("GET","POST"));
      configuration.setAllowedHeaders(Arrays.asList("X-XSRF-TOKEN","Content-Type",globalSettingConfig.jwtEncryptHeader));
      configuration.setAllowCredentials(true);
      configuration.applyPermitDefaultValues();
      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      source.registerCorsConfiguration("/**", configuration);
      return source;
  }
}

上述配置中:
authDetailsUserService 是从数据库中加载用户数据。该类需要实现UserDetailsService,重写里面的loadUserByUsername(String UserName)方法。返回值UserDetails为一个用户的基本信息类,可以重写子类继承为更丰富的用户信息。
jwtAuthenticationTokenFilter 是一个拦截器。再所有请求进入后台时。由该拦截器判断是否登陆或登陆是否有效
userPermissionService.hasPermission(request,authentication) 为权限判断的方法。

  1. 然后就是一些用户表、权限表 和 资源表的增删改查。

前端

前端代码由于本人不会写。所以基本是按照element 官方文档写的。所以就不贴代码了,需要的话可直接去github上下载。大家可以看一下效果图

图片1:
登陆界面

登陆界面
图片2:
在这里插入图片描述
在这里插入图片描述

版权声明:本文为tfx19931128原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/tfx19931128/article/details/108597254