1

前言

接前面的内容,我们用zuul + spring security 来完成认证授权。

认证中心

image.png
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>zuul-auth</artifactId>
        <groupId>com.babaznkj.com</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>auth-center</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.babaznkj.com</groupId>
            <artifactId>common</artifactId>
        </dependency>

        <!-- mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <!-- mybatis启动器 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis.starter.version}</version>
        </dependency>

        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${druid.starter.version}</version>
        </dependency>
    </dependencies>

</project>

yml

server:
  port: 8090

baba:
  security:
    jwt:
      secret: otherpeopledontknowit
      url: /auth
      header: Authorization
      prefix: Bearer
      expiration: 86400
      language: CN

spring:
  application:
    name: auth
  datasource:
    name: test
    url: jdbc:mysql://localhost:3306/baba_icloud_test1?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: carry0610A
    # druid 连接池
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
  main:
    allow-bean-definition-overriding: true # 这个表示允许我们覆盖OAuth2放在容器中的bean对象,一定要配置
  redis:
    host: 192.168.3.119
    port: 6379
    password: 123456

ribbon:
  ReadTimeout: 5000
  SocketTimeout: 5000

eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka/
  instance:
    prefer-ip-address: false
management:
  endpoints:
    security:
      enabled: false
    web:
      exposure:
        include: "*"
mybatis:
  mapper-locations: classpath:mapper/*.xml    # mapper映射文件位置
  type-aliases-package: shuaicj.example.security.common.entity    # 实体类所在的位置
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  • SecurityConfig.java : 这里过滤器可以返回自定义异常。

    package com.baba.security.auth.config;
    
    import com.baba.security.auth.filter.JwtUsernamePasswordAuthenticationFilter;
    import com.baba.security.auth.service.impl.MemberUserDetailsService;
    import com.baba.security.common.config.JwtProperties;
    import com.baba.security.common.exception.JWTAuthenticationEntryPoint;
    import com.baba.security.common.handler.SimpleAccessDeniedHandler;
    import com.baba.security.common.handler.SimpleAuthenticationEntryPoint;
    import com.baba.security.common.utils.MD5Util;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.http.HttpMethod;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.config.http.SessionCreationPolicy;
    import org.springframework.security.crypto.password.PasswordEncoder;
    import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * Config login authentication.
     *
     * @author shuaicj 2017/10/18
     */
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
      @Autowired
      private MemberUserDetailsService memberUserDetailsService;
    
      @Autowired
      private JwtProperties jwtProperties;
    
      @Bean
      public JwtProperties jwtConfig() {
          return new JwtProperties();
      }
    
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
          auth.userDetailsService(memberUserDetailsService).passwordEncoder(new PasswordEncoder() {
              /**
               * 对密码MD5
               * @param rawPassword
               * @return
               */
              @Override
              public String encode(CharSequence rawPassword) {
                  return MD5Util.encode((String) rawPassword);
              }
    
              /**
               * rawPassword 用户输入的密码
               * encodedPassword 数据库DB的密码
               * @param rawPassword
               * @param encodedPassword
               * @return
               */
              @Override
              public boolean matches(CharSequence rawPassword, String encodedPassword) {
                  String rawPass = MD5Util.encode((String) rawPassword);
                  boolean result = rawPass.equals(encodedPassword);
                  return result;
              }
          });
      }
    
    
      @Override
      protected void configure(HttpSecurity httpSecurity) throws Exception {
    
          httpSecurity
                  .cors().
                  and()
                  .csrf().disable()
                  .logout().disable()
    //                .formLogin().disable()
                  .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                  .and()
                  .exceptionHandling().authenticationEntryPoint(
                  (req, rsp, e) -> rsp.sendError(HttpServletResponse.SC_UNAUTHORIZED))
                  .and()
    //                .addFilterBefore(new WebSecurityCorsFilter(), ChannelProcessingFilter.class) // 保证跨域的过滤器首先触发
                  .addFilterAfter(new JwtUsernamePasswordAuthenticationFilter(jwtProperties, authenticationManager()),
                          UsernamePasswordAuthenticationFilter.class)
                  .authorizeRequests()
                  .antMatchers(HttpMethod.OPTIONS).permitAll()
                  .antMatchers(jwtProperties.getUrl()).permitAll()
                  .anyRequest().authenticated()
    //                // 加一句这个
                  .and()
                  .exceptionHandling().authenticationEntryPoint(new JWTAuthenticationEntryPoint())
                  .accessDeniedHandler(new SimpleAccessDeniedHandler()).authenticationEntryPoint(new SimpleAuthenticationEntryPoint());
    
      }
    
      @Bean
      @Override
      public AuthenticationManager authenticationManagerBean() throws Exception {
          return super.authenticationManagerBean();
      }
    
    
    }
    
    
  • PermissionMapper.java

    package com.baba.security.auth.dao;
    
    
    import com.baba.security.auth.entity.Permission;
    import com.baba.security.auth.entity.PermissionEntity;
    
    import java.util.List;
    
    public interface PermissionMapper {
      /**
       * delete by primary key
       *
       * @param id primaryKey
       * @return deleteCount
       */
      int deleteByPrimaryKey(Long id);
    
      /**
       * insert record to table
       *
       * @param record the record
       * @return insert count
       */
      int insert(Permission record);
    
      /**
       * insert record to table selective
       *
       * @param record the record
       * @return insert count
       */
      int insertSelective(Permission record);
    
      /**
       * select by primary key
       *
       * @param id primary key
       * @return object by primary key
       */
      Permission selectByPrimaryKey(Long id);
    
      /**
       * update record selective
       *
       * @param record the updated record
       * @return update count
       */
      int updateByPrimaryKeySelective(Permission record);
    
      /**
       * update record
       *
       * @param record the updated record
       * @return update count
       */
      int updateByPrimaryKey(Permission record);
    
      List<Permission> findByAll(Permission permission);
    
      List<PermissionEntity> findPermissionEntity(Permission permission);
    
      List<PermissionEntity> findPermissionByUsername(String username);
    
    }
  • RoleMapper.java

    package com.baba.security.auth.dao;
    
    
    import com.baba.security.auth.entity.Role;
    
    import java.util.List;
    
    public interface RoleMapper {
      /**
       * delete by primary key
       * @param id primaryKey
       * @return deleteCount
       */
      int deleteByPrimaryKey(Integer id);
    
      /**
       * insert record to table
       * @param record the record
       * @return insert count
       */
      int insert(Role record);
    
      /**
       * insert record to table selective
       * @param record the record
       * @return insert count
       */
      int insertSelective(Role record);
    
      /**
       * select by primary key
       * @param id primary key
       * @return object by primary key
       */
      Role selectByPrimaryKey(Integer id);
    
      /**
       * update record selective
       * @param record the updated record
       * @return update count
       */
      int updateByPrimaryKeySelective(Role record);
    
      /**
       * update record
       * @param record the updated record
       * @return update count
       */
      int updateByPrimaryKey(Role record);
    
      List<Role> findByAll(Role role);
    }
  • RolePermissionMapper.java

    package com.baba.security.auth.dao;
    
    
    import com.baba.security.auth.entity.RolePermission;
    
    import java.util.List;
    
    public interface RolePermissionMapper {
      /**
       * insert record to table
       * @param record the record
       * @return insert count
       */
      int insert(RolePermission record);
    
      /**
       * insert record to table selective
       * @param record the record
       * @return insert count
       */
      int insertSelective(RolePermission record);
    
      List<RolePermission> findByAll(RolePermission rolePermission);
    }
  • UserMapper.java

    package com.baba.security.auth.dao;
    
    
    import com.baba.security.auth.entity.User;
    
    import java.util.List;
    
    public interface UserMapper {
      /**
       * delete by primary key
       *
       * @param id primaryKey
       * @return deleteCount
       */
      int deleteByPrimaryKey(Long id);
    
      /**
       * insert record to table
       *
       * @param record the record
       * @return insert count
       */
      int insert(User record);
    
      /**
       * insert record to table selective
       *
       * @param record the record
       * @return insert count
       */
      int insertSelective(User record);
    
      /**
       * select by primary key
       *
       * @param id primary key
       * @return object by primary key
       */
      User selectByPrimaryKey(Long id);
    
      User findByUsername(String username);
    
    
      /**
       * update record selective
       *
       * @param record the updated record
       * @return update count
       */
      int updateByPrimaryKeySelective(User record);
    
      /**
       * update record
       *
       * @param record the updated record
       * @return update count
       */
      int updateByPrimaryKey(User record);
    
      List<User> findByAll(User user);
    
    }
  • Permission.java

    package com.baba.security.auth.entity;
    
    import lombok.Getter;
    import lombok.Setter;
    import lombok.ToString;
    
    import java.io.Serializable;
    import java.util.Date;
    
    @Getter
    @Setter
    @ToString
    public class Permission implements Serializable {
      /**
       * 主鍵id
       */
      private Long id;
    
      /**
       * 父级权限id
       */
      private Long pid;
    
      /**
       * 中文导航栏名称
       */
      private String name;
    
      /**
       * 英文导航栏名称
       */
      private String eName;
    
      /**
       * 权限标记
       */
      private String tag;
    
      /**
       * 权限值
       */
      private String value;
    
      /**
       * 图标
       */
      private String icon;
    
      /**
       * 权限类型:0->目录;1->菜单;2->按钮(接口绑定权限)
       */
      private Integer type;
    
      /**
       * 请求url
       */
      private String url;
    
      /**
       * 启用状态;0 正常 1删除
       */
      private Integer status;
    
      /**
       * 排序
       */
      private Integer sort;
    
      /**
       * 创建时间
       */
      private Date createTime;
    
      /**
       * 更新时间
       */
      private Date updateTime;
    
      /**
       * 创建人
       */
      private String createdBy;
    
      /**
       * 修改人
       */
      private String updatedBy;
    
      private static final long serialVersionUID = 1L;
    }
  • PermissionEntity.java

    package com.baba.security.auth.entity;
    
    import lombok.Data;
    
    @Data
    public class PermissionEntity {
      private Integer id;
      // 权限名称
      private String permName;
      // 权限标识
      private String permTag;
      // 请求url
      private String url;
    }
    
  • Role.java

    package com.baba.security.auth.entity;
    
    import lombok.Getter;
    import lombok.Setter;
    import lombok.ToString;
    
    import java.io.Serializable;
    import java.util.Date;
    
    @Getter
    @Setter
    @ToString
    public class Role implements Serializable {
      private Integer id;
    
      /**
      * 用户id
      */
      private Long userId;
    
      /**
      * 角色名称
      */
      private String roleName;
    
      /**
      * 角色描述
      */
      private String roleDesc;
    
      /**
      * 创建时间
      */
      private Date createTime;
    
      /**
      * 更新时间
      */
      private Date updateTime;
    
      /**
      * 创建人
      */
      private String createdBy;
    
      /**
      * 修改人
      */
      private String updatedBy;
    
      private static final long serialVersionUID = 1L;
    }
  • RolePermission.java

    package com.baba.security.auth.entity;
    
    import lombok.Getter;
    import lombok.Setter;
    import lombok.ToString;
    
    import java.io.Serializable;
    
    @Getter
    @Setter
    @ToString
    public class RolePermission implements Serializable {
      private Integer roleId;
    
      private Integer permId;
    
      private static final long serialVersionUID = 1L;
    }
  • User: 实现UserDetails

    package com.baba.security.auth.entity;
    
    import lombok.Getter;
    import lombok.Setter;
    import lombok.ToString;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.userdetails.UserDetails;
    
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Date;
    import java.util.List;
    
    @Getter
    @Setter
    @ToString
    public class User implements UserDetails, Serializable {
      /**
       * 主键id
       */
      private Long id;
    
      /**
       * 子用户ID
       */
      private Long pid;
    
      /**
       * 租户id
       */
      private Long tenantId;
    
      /**
       * 名称
       */
      private String username;
    
      /**
       * 密码
       */
      private String password;
    
      /**
       * 昵称
       */
      private String nick;
    
      /**
       * 性别(男/女)
       */
      private int gender;
    
      /**
       * 年龄
       */
      private Integer age;
    
      /**
       * 头像地址
       */
      private String headImg;
    
      /**
       * 电话号码
       */
      private String phone;
    
      /**
       * 0:禁用/1:启用
       */
      private Integer state;
    
      /**
       * 友盟推送认证token
       */
      private String pushToken;
    
      /**
       * app端盐值
       */
      private String appSalt;
    
      /**
       * web端盐值
       */
      private String webSalt;
    
      /**
       * 当前账户是否可用
       */
      private boolean enabled= true;
    
      /**
       * 当前账户是否过期
       */
      private boolean accountNonExpired = true;
    
      /**
       * 当前账户是否锁定
       */
      private boolean accountNonLocked= true;
    
      /**
       * 当前账户凭证是否过期
       */
      private boolean credentialsNonExpired= true;
    
      /**
       * 创建时间
       */
      private Date createTime;
    
      /**
       * 更新时间
       */
      private Date updateTime;
    
      /**
       * 创建人
       */
      private String createBy;
    
      /**
       * 修改人
       */
      private String updateBy;
    
      /**
       * 秘钥
       */
      private String secretKey;
    
      private static final long serialVersionUID = 1L;
    
      /**
       * 权限列表
       */
      private List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    
      public Collection<? extends GrantedAuthority> getAuthorities() {
          return authorities;
      }
    
    
      public void setAuthorities(List<GrantedAuthority> authorities) {
          this.authorities = authorities;
      }
    }
  • JwtUsernamePasswordAuthenticationFilter.java :这里也要放行【config.getUrl()】登录接口,成功和失败的方法调用。token的生成,动态颜值处理。

    package com.baba.security.auth.filter;
    
    import com.baba.security.auth.dao.UserMapper;
    import com.baba.security.auth.entity.User;
    import com.baba.security.common.config.JwtProperties;
    import com.baba.security.common.constant.RedisConstant;
    import com.baba.security.common.enums.ResultCode;
    import com.baba.security.common.exception.DefinitException;
    import com.baba.security.common.utils.JwtUtils;
    import com.baba.security.common.utils.RedisUtils;
    import com.baba.security.common.utils.SaltUtils;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.apache.commons.lang.StringUtils;
    import org.springframework.context.ApplicationContext;
    import org.springframework.http.MediaType;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.authentication.InternalAuthenticationServiceException;
    import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.AuthenticationException;
    import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
    import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
    import org.springframework.web.context.support.WebApplicationContextUtils;
    import org.springframework.web.servlet.HandlerExceptionResolver;
    
    import javax.servlet.FilterChain;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.concurrent.TimeUnit;
    
    /**
     * Authenticate the request to url /login by POST with json body '{ username, password }'.
     * If successful, response the client with header 'Authorization: Bearer jwt-token'.
     *
     * @author shuaicj 2017/10/18
     */
    public class JwtUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    
      //    private final JwtAuthenticationConfig config;
      private final JwtProperties config;
      private final ObjectMapper mapper;
    
      public JwtUsernamePasswordAuthenticationFilter(JwtProperties config, AuthenticationManager authManager) {
          super(new AntPathRequestMatcher(config.getUrl(), "POST"));
          setAuthenticationManager(authManager);
          this.config = config;
          this.mapper = new ObjectMapper();
    
      }
    
    
      // 接收并解析用户凭证
      @Override
      public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse rsp)
              throws AuthenticationException, IOException {
          try {
              User user = mapper.readValue(req.getInputStream(), User.class);
              return getAuthenticationManager().authenticate(
                      new UsernamePasswordAuthenticationToken(
                              user.getUsername(),
                              user.getPassword(),
                              Collections.emptyList()
                      )
              );
          } catch (InternalAuthenticationServiceException e) {
              ServletContext context = req.getServletContext();
              ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
              HandlerExceptionResolver resolver = ctx.getBean("handlerExceptionResolver", HandlerExceptionResolver.class);
              resolver.resolveException(req, rsp, null, new DefinitException(ResultCode.USER_NOT_FOUND));
              return null;
    //            throw new DefinitException(ResultCode.USER_NOT_FOUND);
          }
    
      }
    
    
      // 用户成功登录后,这个方法会被调用,我们在这个方法里生成token
      @Override
      protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse rsp, FilterChain chain,
                                              Authentication auth) throws IOException {
          User user = (User) auth.getPrincipal();
          // filter过滤器使用Autowired注入Bean为null
          ServletContext context = req.getServletContext();
          ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
          RedisUtils redisUtil = ctx.getBean(RedisUtils.class);
          UserMapper userMapper = ctx.getBean(UserMapper.class);
          User updateSalt = new User();
          updateSalt.setId(user.getId());
          //1.生成随机盐
          String salt = SaltUtils.getSalt(8);
          String userAgent = req.getHeader("user-agent").toLowerCase();
          String language = req.getHeader("language");
          if (userAgent.indexOf("micromessenger") != -1) {
              //微信
          } else if (userAgent.indexOf("android") != -1
                  || userAgent.indexOf("iphone") != -1 || userAgent.indexOf("ipad") != -1 || userAgent.indexOf("ipod") != -1) {
              //安卓 或者 苹果
              //2.将随机盐保存到Redis
              redisUtil.setEx(RedisConstant.PREFIX_APP + user.getId(), salt, 1, TimeUnit.DAYS);
              updateSalt.setAppSalt(salt);
          } else {
              //电脑
              //2.将随机盐保存到Redis
              redisUtil.setEx(RedisConstant.PREFIX_WEB + user.getId(), salt, 1, TimeUnit.DAYS);
              updateSalt.setWebSalt(salt);
          }
          //3.更新Mysql随机盐值
          userMapper.updateByPrimaryKeySelective(updateSalt);
          user.setSecretKey(salt);
          if (StringUtils.isEmpty(language)) {
              language = config.getLanguage();
          }
          String token = JwtUtils.generateJsonWebToken(auth, salt, language);
          redisUtil.setEx(token, user.getId().toString(), 2, TimeUnit.HOURS);
          rsp.addHeader(config.getHeader(), config.getPrefix() + " " + token);
          HashMap<String, Object> map = new HashMap<>(2);
          map.put("code", ResultCode.USER_AUTH_SUCCESS.getCode());
          map.put("msg", ResultCode.USER_AUTH_SUCCESS.getMessage());
          rsp.setStatus(HttpServletResponse.SC_OK);
          rsp.setCharacterEncoding("utf-8");
          rsp.setContentType(MediaType.APPLICATION_JSON_VALUE);
          rsp.getWriter().write(new ObjectMapper().writeValueAsString(map));
      }
    
      @Override
      protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
    //        response.getWriter().write("authentication failed, reason: " + failed.getMessage());
          System.out.println(failed.getMessage());
          ServletContext context = request.getServletContext();
          ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
          HandlerExceptionResolver resolver = ctx.getBean("handlerExceptionResolver", HandlerExceptionResolver.class);
          resolver.resolveException(request, response, null, new DefinitException(ResultCode.LOGIN_METHOD_WROND));
      }
    }
    
  • MemberUserDetailsService.java : 查询的tag必须拼接前缀"ROLE_",而不能在数据库中添加。

    package com.baba.security.auth.service.impl;
    
    import com.baba.security.auth.entity.PermissionEntity;
    import com.baba.security.auth.entity.User;
    import com.baba.security.auth.service.PermissionService;
    import com.baba.security.auth.service.UserService;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.authority.SimpleGrantedAuthority;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
    import org.springframework.stereotype.Component;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * @ClassName MemberUserDetailsService
     * @Author wulongbo
     * @Version V1.0
     **/
    @Component
    @Slf4j
    public class MemberUserDetailsService implements UserDetailsService {
      @Autowired
      private UserService userService;
    
      @Autowired
      private PermissionService permissionService;
    
      /**
       * loadUserByUserName
       *
       * @param username
       * @return
       * @throws UsernameNotFoundException
       */
      @Override
      public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
          // 1.根据该用户名称查询在数据库中是否存在
          User userEntity = userService.findByUsername(username);
          if (userEntity == null) {
              return null;
          }
          // 2.查询对应的用户权限
          List<PermissionEntity> listPermission = permissionService.findPermissionByUsername(username);
          List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    
          listPermission.forEach(user -> {
              authorities.add(new SimpleGrantedAuthority("ROLE_" + user.getPermTag()));
          });
          // 3.将该权限添加到security
          userEntity.setAuthorities(authorities);
          return userEntity;
      }
    
    }
    
  • PermissionServiceImpl.java

    package com.baba.security.auth.service.impl;
    
    import com.baba.security.auth.dao.PermissionMapper;
    import com.baba.security.auth.entity.Permission;
    import com.baba.security.auth.entity.PermissionEntity;
    import com.baba.security.auth.service.PermissionService;
    import org.springframework.stereotype.Service;
    
    import javax.annotation.Resource;
    import java.util.List;
    
    @Service
    public class PermissionServiceImpl implements PermissionService {
    
      @Resource
      private PermissionMapper permissionMapper;
    
      @Override
      public int deleteByPrimaryKey(Long id) {
          return permissionMapper.deleteByPrimaryKey(id);
      }
    
      @Override
      public int insert(Permission record) {
          return permissionMapper.insert(record);
      }
    
      @Override
      public int insertSelective(Permission record) {
          return permissionMapper.insertSelective(record);
      }
    
      @Override
      public Permission selectByPrimaryKey(Long id) {
          return permissionMapper.selectByPrimaryKey(id);
      }
    
      @Override
      public int updateByPrimaryKeySelective(Permission record) {
          return permissionMapper.updateByPrimaryKeySelective(record);
      }
    
      @Override
      public int updateByPrimaryKey(Permission record) {
          return permissionMapper.updateByPrimaryKey(record);
      }
    
      @Override
      public List<Permission> findByAll(Permission permission) {
          return permissionMapper.findByAll(permission);
      }
    
      @Override
      public List<PermissionEntity> findPermissionEntity(Permission permission) {
          return permissionMapper.findPermissionEntity(permission);
      }
    
      @Override
      public List<PermissionEntity> findPermissionByUsername(String username) {
          return permissionMapper.findPermissionByUsername(username);
      }
    
    }
    
    
  1. UserServiceImpl.java

    package com.baba.security.auth.service.impl;
    
    import com.baba.security.auth.dao.UserMapper;
    import com.baba.security.auth.entity.User;
    import com.baba.security.auth.service.UserService;
    import org.springframework.stereotype.Service;
    
    import javax.annotation.Resource;
    import java.util.List;
    
    @Service
    public class UserServiceImpl implements UserService {
    
     @Resource
     private UserMapper userMapper;
    
     @Override
     public int deleteByPrimaryKey(Long id) {
         return userMapper.deleteByPrimaryKey(id);
     }
    
     @Override
     public int insert(User record) {
         return userMapper.insert(record);
     }
    
     @Override
     public int insertSelective(User record) {
         return userMapper.insertSelective(record);
     }
    
     @Override
     public User selectByPrimaryKey(Long id) {
         return userMapper.selectByPrimaryKey(id);
     }
    
     @Override
     public int updateByPrimaryKeySelective(User record) {
         return userMapper.updateByPrimaryKeySelective(record);
     }
    
     @Override
     public int updateByPrimaryKey(User record) {
         return userMapper.updateByPrimaryKey(record);
     }
    
     @Override
     public List<User> findByAll(User user) {
         return userMapper.findByAll(user);
     }
    
     @Override
     public User findByUsername(String username) {
         return userMapper.findByUsername(username);
     }
    
    }
    
    
    
    
    
  • PermissionService.java

    package com.baba.security.auth.service;
    
    
    import com.baba.security.auth.entity.Permission;
    import com.baba.security.auth.entity.PermissionEntity;
    
    import java.util.List;
    
    public interface PermissionService {
    
      int deleteByPrimaryKey(Long id);
    
      int insert(Permission record);
    
      int insertSelective(Permission record);
    
      Permission selectByPrimaryKey(Long id);
    
      int updateByPrimaryKeySelective(Permission record);
    
      int updateByPrimaryKey(Permission record);
    
      List<Permission> findByAll(Permission permission);
    
      List<PermissionEntity> findPermissionEntity(Permission permission);
    
      List<PermissionEntity> findPermissionByUsername(String username);
    }
    
    
  • UserService.java

    package com.baba.security.auth.service;
    
    
    import com.baba.security.auth.entity.User;
    
    import java.util.List;
    
    public interface UserService {
    
    
      int deleteByPrimaryKey(Long id);
    
      int insert(User record);
    
      int insertSelective(User record);
    
      User selectByPrimaryKey(Long id);
    
      int updateByPrimaryKeySelective(User record);
    
      int updateByPrimaryKey(User record);
    
      List<User> findByAll(User user);
    
      User findByUsername(String username);
    
    }
    
    
    
    
    
  • PermissionMapper.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.baba.security.auth.dao.PermissionMapper">
      <resultMap id="BaseResultMap" type="com.baba.security.auth.entity.Permission">
          <!--@mbg.generated-->
          <!--@Table tbl_permission-->
          <id column="id" jdbcType="BIGINT" property="id"/>
          <result column="pid" jdbcType="BIGINT" property="pid"/>
          <result column="name" jdbcType="VARCHAR" property="name"/>
          <result column="e_name" jdbcType="VARCHAR" property="eName"/>
          <result column="tag" jdbcType="VARCHAR" property="tag"/>
          <result column="value" jdbcType="VARCHAR" property="value"/>
          <result column="icon" jdbcType="VARCHAR" property="icon"/>
          <result column="type" jdbcType="INTEGER" property="type"/>
          <result column="url" jdbcType="VARCHAR" property="url"/>
          <result column="status" jdbcType="INTEGER" property="status"/>
          <result column="sort" jdbcType="INTEGER" property="sort"/>
          <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
          <result column="update_time" jdbcType="TIMESTAMP" property="updateTime"/>
          <result column="created_by" jdbcType="VARCHAR" property="createdBy"/>
          <result column="updated_by" jdbcType="VARCHAR" property="updatedBy"/>
      </resultMap>
    
      <resultMap id="PermissionEntityResultMap" type="com.baba.security.auth.entity.PermissionEntity">
          <id column="id" jdbcType="BIGINT" property="id"/>
          <result column="permName" jdbcType="VARCHAR" property="permName"/>
          <result column="permTag" jdbcType="VARCHAR" property="permTag"/>
          <result column="url" jdbcType="VARCHAR" property="url"/>
      </resultMap>
    
      <select id="findPermissionByUsername" parameterType="java.lang.String" resultMap="PermissionEntityResultMap">
          SELECT
              permission.id,permission.`name` permName,permission.tag permTag,permission.url
          FROM
              tbl_user
              USER INNER JOIN tbl_user_role user_role ON USER.id = user_role.user_id
              INNER JOIN tbl_role_permission role_permission ON user_role.role_id = role_permission.role_id
              INNER JOIN tbl_permission permission ON role_permission.perm_id = permission.id
          WHERE
              USER.phone = #{username,jdbcType=VARCHAR} AND permission.type=2
      </select>
    
      <sql id="Base_Column_List">
          <!--@mbg.generated-->
          id, pid, `name`, e_name, tag, `value`, icon, `type`, url, `status`, sort,
          create_time, update_time, created_by, updated_by
      </sql>
      <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
          <!--@mbg.generated-->
          select
          <include refid="Base_Column_List"/>
          from tbl_permission
          where id = #{id,jdbcType=BIGINT}
      </select>
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
          <!--@mbg.generated-->
          delete from tbl_permission
          where id = #{id,jdbcType=BIGINT}
      </delete>
      <insert id="insert" keyColumn="id" keyProperty="id"
              parameterType="com.baba.security.auth.entity.Permission" useGeneratedKeys="true">
          <!--@mbg.generated-->
          insert into tbl_permission (pid, `name`,
          e_name, tag, `value`,
          icon, `type`, url, `status`,
          sort, create_time, update_time,
          created_by, updated_by)
          values (#{pid,jdbcType=BIGINT},  #{name,jdbcType=VARCHAR},
          #{eName,jdbcType=VARCHAR}, #{tag,jdbcType=VARCHAR}, #{value,jdbcType=VARCHAR},
          #{icon,jdbcType=VARCHAR}, #{type,jdbcType=INTEGER}, #{url,jdbcType=VARCHAR}, #{status,jdbcType=INTEGER},
          #{sort,jdbcType=INTEGER}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP},
          #{createdBy,jdbcType=VARCHAR}, #{updatedBy,jdbcType=VARCHAR})
      </insert>
      <insert id="insertSelective" keyColumn="id" keyProperty="id"
              parameterType="com.baba.security.auth.entity.Permission" useGeneratedKeys="true">
          <!--@mbg.generated-->
          insert into tbl_permission
          <trim prefix="(" suffix=")" suffixOverrides=",">
              <if test="pid != null">
                  pid,
              </if>
              <if test="name != null">
                  `name`,
              </if>
              <if test="eName != null">
                  e_name,
              </if>
              <if test="tag != null">
                  tag,
              </if>
              <if test="value != null">
                  `value`,
              </if>
              <if test="icon != null">
                  icon,
              </if>
              <if test="type != null">
                  `type`,
              </if>
              <if test="url != null">
                  url,
              </if>
              <if test="status != null">
                  `status`,
              </if>
              <if test="sort != null">
                  sort,
              </if>
              <if test="createTime != null">
                  create_time,
              </if>
              <if test="updateTime != null">
                  update_time,
              </if>
              <if test="createdBy != null">
                  created_by,
              </if>
              <if test="updatedBy != null">
                  updated_by,
              </if>
          </trim>
          <trim prefix="values (" suffix=")" suffixOverrides=",">
              <if test="pid != null">
                  #{pid,jdbcType=BIGINT},
              </if>
              <if test="name != null">
                  #{name,jdbcType=VARCHAR},
              </if>
              <if test="eName != null">
                  #{eName,jdbcType=VARCHAR},
              </if>
              <if test="tag != null">
                  #{tag,jdbcType=VARCHAR},
              </if>
              <if test="value != null">
                  #{value,jdbcType=VARCHAR},
              </if>
              <if test="icon != null">
                  #{icon,jdbcType=VARCHAR},
              </if>
              <if test="type != null">
                  #{type,jdbcType=INTEGER},
              </if>
              <if test="url != null">
                  #{url,jdbcType=VARCHAR},
              </if>
              <if test="status != null">
                  #{status,jdbcType=INTEGER},
              </if>
              <if test="sort != null">
                  #{sort,jdbcType=INTEGER},
              </if>
              <if test="createTime != null">
                  #{createTime,jdbcType=TIMESTAMP},
              </if>
              <if test="updateTime != null">
                  #{updateTime,jdbcType=TIMESTAMP},
              </if>
              <if test="createdBy != null">
                  #{createdBy,jdbcType=VARCHAR},
              </if>
              <if test="updatedBy != null">
                  #{updatedBy,jdbcType=VARCHAR},
              </if>
          </trim>
      </insert>
      <update id="updateByPrimaryKeySelective" parameterType="com.baba.security.auth.entity.Permission">
          <!--@mbg.generated-->
          update tbl_permission
          <set>
              <if test="pid != null">
                  pid = #{pid,jdbcType=BIGINT},
              </if>
              <if test="name != null">
                  `name` = #{name,jdbcType=VARCHAR},
              </if>
              <if test="eName != null">
                  e_name = #{eName,jdbcType=VARCHAR},
              </if>
              <if test="tag != null">
                  tag = #{tag,jdbcType=VARCHAR},
              </if>
              <if test="value != null">
                  `value` = #{value,jdbcType=VARCHAR},
              </if>
              <if test="icon != null">
                  icon = #{icon,jdbcType=VARCHAR},
              </if>
              <if test="type != null">
                  `type` = #{type,jdbcType=INTEGER},
              </if>
              <if test="url != null">
                  url = #{url,jdbcType=VARCHAR},
              </if>
              <if test="status != null">
                  `status` = #{status,jdbcType=INTEGER},
              </if>
              <if test="sort != null">
                  sort = #{sort,jdbcType=INTEGER},
              </if>
              <if test="createTime != null">
                  create_time = #{createTime,jdbcType=TIMESTAMP},
              </if>
              <if test="updateTime != null">
                  update_time = #{updateTime,jdbcType=TIMESTAMP},
              </if>
              <if test="createdBy != null">
                  created_by = #{createdBy,jdbcType=VARCHAR},
              </if>
              <if test="updatedBy != null">
                  updated_by = #{updatedBy,jdbcType=VARCHAR},
              </if>
          </set>
          where id = #{id,jdbcType=BIGINT}
      </update>
      <update id="updateByPrimaryKey" parameterType="com.baba.security.auth.entity.Permission">
          <!--@mbg.generated-->
          update tbl_permission
          set pid = #{pid,jdbcType=BIGINT},
          `name` = #{name,jdbcType=VARCHAR},
          e_name = #{eName,jdbcType=VARCHAR},
          tag = #{tag,jdbcType=VARCHAR},
          `value` = #{value,jdbcType=VARCHAR},
          icon = #{icon,jdbcType=VARCHAR},
          `type` = #{type,jdbcType=INTEGER},
          url = #{url,jdbcType=VARCHAR},
          `status` = #{status,jdbcType=INTEGER},
          sort = #{sort,jdbcType=INTEGER},
          create_time = #{createTime,jdbcType=TIMESTAMP},
          update_time = #{updateTime,jdbcType=TIMESTAMP},
          created_by = #{createdBy,jdbcType=VARCHAR},
          updated_by = #{updatedBy,jdbcType=VARCHAR}
          where id = #{id,jdbcType=BIGINT}
      </update>
      <select id="findByAll" resultMap="BaseResultMap">
          <!--@mbg.generated-->
          select
          <include refid="Base_Column_List"/>
          from tbl_permission
          <where>
              <if test="id != null">
                  and id=#{id,jdbcType=BIGINT}
              </if>
              <if test="pid != null">
                  and pid=#{pid,jdbcType=BIGINT}
              </if>
              <if test="name != null">
                  and `name`=#{name,jdbcType=VARCHAR}
              </if>
              <if test="eName != null">
                  and e_name=#{eName,jdbcType=VARCHAR}
              </if>
              <if test="tag != null">
                  and tag=#{tag,jdbcType=VARCHAR}
              </if>
              <if test="value != null">
                  and `value`=#{value,jdbcType=VARCHAR}
              </if>
              <if test="icon != null">
                  and icon=#{icon,jdbcType=VARCHAR}
              </if>
              <if test="type != null">
                  and `type`=#{type,jdbcType=INTEGER}
              </if>
              <if test="url != null">
                  and url=#{url,jdbcType=VARCHAR}
              </if>
              <if test="status != null">
                  and `status`=#{status,jdbcType=INTEGER}
              </if>
              <if test="sort != null">
                  and sort=#{sort,jdbcType=INTEGER}
              </if>
              <if test="createTime != null">
                  and create_time=#{createTime,jdbcType=TIMESTAMP}
              </if>
              <if test="updateTime != null">
                  and update_time=#{updateTime,jdbcType=TIMESTAMP}
              </if>
              <if test="createdBy != null">
                  and created_by=#{createdBy,jdbcType=VARCHAR}
              </if>
              <if test="updatedBy != null">
                  and updated_by=#{updatedBy,jdbcType=VARCHAR}
              </if>
          </where>
      </select>
    
      <select id="findPermissionEntity" resultMap="PermissionEntityResultMap">
          select
          id,
          `name` permName,
          tag permTag,
          url
          from tbl_permission
          <where>
              <if test="id != null">
                  and id=#{id,jdbcType=BIGINT}
              </if>
              <if test="pid != null">
                  and pid=#{pid,jdbcType=BIGINT}
              </if>
              <if test="name != null">
                  and `name`=#{name,jdbcType=VARCHAR}
              </if>
              <if test="eName != null">
                  and e_name=#{eName,jdbcType=VARCHAR}
              </if>
              <if test="tag != null">
                  and tag=#{tag,jdbcType=VARCHAR}
              </if>
              <if test="value != null">
                  and `value`=#{value,jdbcType=VARCHAR}
              </if>
              <if test="icon != null">
                  and icon=#{icon,jdbcType=VARCHAR}
              </if>
              <if test="type != null">
                  and `type`=#{type,jdbcType=INTEGER}
              </if>
              <if test="url != null">
                  and url=#{url,jdbcType=VARCHAR}
              </if>
              <if test="status != null">
                  and `status`=#{status,jdbcType=INTEGER}
              </if>
              <if test="sort != null">
                  and sort=#{sort,jdbcType=INTEGER}
              </if>
              <if test="createTime != null">
                  and create_time=#{createTime,jdbcType=TIMESTAMP}
              </if>
              <if test="updateTime != null">
                  and update_time=#{updateTime,jdbcType=TIMESTAMP}
              </if>
              <if test="createdBy != null">
                  and created_by=#{createdBy,jdbcType=VARCHAR}
              </if>
              <if test="updatedBy != null">
                  and updated_by=#{updatedBy,jdbcType=VARCHAR}
              </if>
          </where>
      </select>
    </mapper>
  • RoleMapper.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.baba.security.auth.dao.RoleMapper">
    <resultMap id="BaseResultMap" type="com.baba.security.auth.entity.Role">
      <!--@mbg.generated-->
      <!--@Table tbl_role-->
      <id column="id" jdbcType="INTEGER" property="id" />
      <result column="user_id" jdbcType="BIGINT" property="userId" />
      <result column="role_name" jdbcType="VARCHAR" property="roleName" />
      <result column="role_desc" jdbcType="VARCHAR" property="roleDesc" />
      <result column="create_time" jdbcType="DATE" property="createTime" />
      <result column="update_time" jdbcType="DATE" property="updateTime" />
      <result column="created_by" jdbcType="VARCHAR" property="createdBy" />
      <result column="updated_by" jdbcType="VARCHAR" property="updatedBy" />
    </resultMap>
    <sql id="Base_Column_List">
      <!--@mbg.generated-->
      id, user_id, role_name, role_desc, create_time, update_time, created_by, updated_by
    </sql>
    <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
      <!--@mbg.generated-->
      select 
      <include refid="Base_Column_List" />
      from tbl_role
      where id = #{id,jdbcType=INTEGER}
    </select>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
      <!--@mbg.generated-->
      delete from tbl_role
      where id = #{id,jdbcType=INTEGER}
    </delete>
    <insert id="insert" parameterType="com.baba.security.auth.entity.Role">
      <!--@mbg.generated-->
      insert into tbl_role (id, user_id, role_name, 
        role_desc, create_time, update_time, 
        created_by, updated_by)
      values (#{id,jdbcType=INTEGER}, #{userId,jdbcType=BIGINT}, #{roleName,jdbcType=VARCHAR}, 
        #{roleDesc,jdbcType=VARCHAR}, #{createTime,jdbcType=DATE}, #{updateTime,jdbcType=DATE}, 
        #{createdBy,jdbcType=VARCHAR}, #{updatedBy,jdbcType=VARCHAR})
    </insert>
    <insert id="insertSelective" parameterType="com.baba.security.auth.entity.Role">
      <!--@mbg.generated-->
      insert into tbl_role
      <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="id != null">
          id,
        </if>
        <if test="userId != null">
          user_id,
        </if>
        <if test="roleName != null">
          role_name,
        </if>
        <if test="roleDesc != null">
          role_desc,
        </if>
        <if test="createTime != null">
          create_time,
        </if>
        <if test="updateTime != null">
          update_time,
        </if>
        <if test="createdBy != null">
          created_by,
        </if>
        <if test="updatedBy != null">
          updated_by,
        </if>
      </trim>
      <trim prefix="values (" suffix=")" suffixOverrides=",">
        <if test="id != null">
          #{id,jdbcType=INTEGER},
        </if>
        <if test="userId != null">
          #{userId,jdbcType=BIGINT},
        </if>
        <if test="roleName != null">
          #{roleName,jdbcType=VARCHAR},
        </if>
        <if test="roleDesc != null">
          #{roleDesc,jdbcType=VARCHAR},
        </if>
        <if test="createTime != null">
          #{createTime,jdbcType=DATE},
        </if>
        <if test="updateTime != null">
          #{updateTime,jdbcType=DATE},
        </if>
        <if test="createdBy != null">
          #{createdBy,jdbcType=VARCHAR},
        </if>
        <if test="updatedBy != null">
          #{updatedBy,jdbcType=VARCHAR},
        </if>
      </trim>
    </insert>
    <update id="updateByPrimaryKeySelective" parameterType="com.baba.security.auth.entity.Role">
      <!--@mbg.generated-->
      update tbl_role
      <set>
        <if test="userId != null">
          user_id = #{userId,jdbcType=BIGINT},
        </if>
        <if test="roleName != null">
          role_name = #{roleName,jdbcType=VARCHAR},
        </if>
        <if test="roleDesc != null">
          role_desc = #{roleDesc,jdbcType=VARCHAR},
        </if>
        <if test="createTime != null">
          create_time = #{createTime,jdbcType=DATE},
        </if>
        <if test="updateTime != null">
          update_time = #{updateTime,jdbcType=DATE},
        </if>
        <if test="createdBy != null">
          created_by = #{createdBy,jdbcType=VARCHAR},
        </if>
        <if test="updatedBy != null">
          updated_by = #{updatedBy,jdbcType=VARCHAR},
        </if>
      </set>
      where id = #{id,jdbcType=INTEGER}
    </update>
    <update id="updateByPrimaryKey" parameterType="com.baba.security.auth.entity.Role">
      <!--@mbg.generated-->
      update tbl_role
      set user_id = #{userId,jdbcType=BIGINT},
        role_name = #{roleName,jdbcType=VARCHAR},
        role_desc = #{roleDesc,jdbcType=VARCHAR},
        create_time = #{createTime,jdbcType=DATE},
        update_time = #{updateTime,jdbcType=DATE},
        created_by = #{createdBy,jdbcType=VARCHAR},
        updated_by = #{updatedBy,jdbcType=VARCHAR}
      where id = #{id,jdbcType=INTEGER}
    </update>
    <select id="findByAll" resultMap="BaseResultMap">
          <!--@mbg.generated-->
          select
          <include refid="Base_Column_List"/>
          from tbl_role
          <where>
              <if test="id != null">
                  and id=#{id,jdbcType=INTEGER}
              </if>
              <if test="userId != null">
                  and user_id=#{userId,jdbcType=BIGINT}
              </if>
              <if test="roleName != null">
                  and role_name=#{roleName,jdbcType=VARCHAR}
              </if>
              <if test="roleDesc != null">
                  and role_desc=#{roleDesc,jdbcType=VARCHAR}
              </if>
              <if test="createTime != null">
                  and create_time=#{createTime,jdbcType=DATE}
              </if>
              <if test="updateTime != null">
                  and update_time=#{updateTime,jdbcType=DATE}
              </if>
              <if test="createdBy != null">
                  and created_by=#{createdBy,jdbcType=VARCHAR}
              </if>
              <if test="updatedBy != null">
                  and updated_by=#{updatedBy,jdbcType=VARCHAR}
              </if>
          </where>
      </select>
    </mapper>
  • RolePermissionMapper.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.baba.security.auth.dao.RolePermissionMapper">
    <resultMap id="BaseResultMap" type="com.baba.security.auth.entity.RolePermission">
      <!--@mbg.generated-->
      <!--@Table tbl_role_permission-->
      <result column="role_id" jdbcType="INTEGER" property="roleId" />
      <result column="perm_id" jdbcType="INTEGER" property="permId" />
    </resultMap>
    <sql id="Base_Column_List">
      <!--@mbg.generated-->
      role_id, perm_id
    </sql>
    <insert id="insert" parameterType="com.baba.security.auth.entity.RolePermission">
      <!--@mbg.generated-->
      insert into tbl_role_permission (role_id, perm_id)
      values (#{roleId,jdbcType=INTEGER}, #{permId,jdbcType=INTEGER})
    </insert>
    <insert id="insertSelective" parameterType="com.baba.security.auth.entity.RolePermission">
      <!--@mbg.generated-->
      insert into tbl_role_permission
      <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="roleId != null">
          role_id,
        </if>
        <if test="permId != null">
          perm_id,
        </if>
      </trim>
      <trim prefix="values (" suffix=")" suffixOverrides=",">
        <if test="roleId != null">
          #{roleId,jdbcType=INTEGER},
        </if>
        <if test="permId != null">
          #{permId,jdbcType=INTEGER},
        </if>
      </trim>
    </insert>
    <select id="findByAll" resultMap="BaseResultMap">
          <!--@mbg.generated-->
          select
          <include refid="Base_Column_List"/>
          from tbl_role_permission
          <where>
              <if test="roleId != null">
                  and role_id=#{roleId,jdbcType=INTEGER}
              </if>
              <if test="permId != null">
                  and perm_id=#{permId,jdbcType=INTEGER}
              </if>
          </where>
      </select>
    </mapper>
  • UserMapper.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.baba.security.auth.dao.UserMapper">
    <resultMap id="BaseResultMap" type="com.baba.security.auth.entity.User">
      <!--@mbg.generated-->
      <!--@Table tbl_user-->
      <id column="id" jdbcType="BIGINT" property="id" />
      <result column="pid" jdbcType="BIGINT" property="pid" />
      <result column="tenant_id" jdbcType="BIGINT" property="tenantId" />
      <result column="username" jdbcType="VARCHAR" property="username" />
      <result column="password" jdbcType="VARCHAR" property="password" />
      <result column="nick" jdbcType="VARCHAR" property="nick" />
      <result column="gender" jdbcType="INTEGER" property="gender" />
      <result column="age" jdbcType="INTEGER" property="age" />
      <result column="head_img" jdbcType="VARCHAR" property="headImg" />
      <result column="phone" jdbcType="VARCHAR" property="phone" />
      <result column="state" jdbcType="INTEGER" property="state" />
      <result column="push_token" jdbcType="VARCHAR" property="pushToken" />
      <result column="app_salt" jdbcType="VARCHAR" property="appSalt" />
      <result column="web_salt" jdbcType="VARCHAR" property="webSalt" />
      <result column="enabled" jdbcType="BOOLEAN" property="enabled" />
      <result column="accountNonExpired" jdbcType="BOOLEAN" property="accountNonExpired" />
      <result column="accountNonLocked" jdbcType="BOOLEAN" property="accountNonLocked" />
      <result column="credentialsNonExpired" jdbcType="BOOLEAN" property="credentialsNonExpired" />
      <result column="create_time" jdbcType="DATE" property="createTime" />
      <result column="update_time" jdbcType="DATE" property="updateTime" />
      <result column="create_by" jdbcType="VARCHAR" property="createBy" />
      <result column="update_by" jdbcType="VARCHAR" property="updateBy" />
    </resultMap>
    
    
    <sql id="Base_Column_List">
      <!--@mbg.generated-->
      id, pid, tenant_id, username, `password`, nick, gender, age, head_img, phone, `state`,
      push_token, app_salt, web_salt, enabled, accountNonExpired, accountNonLocked, credentialsNonExpired,
      create_time, update_time, create_by, update_by
    </sql>
    <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
      <!--@mbg.generated-->
      select
      <include refid="Base_Column_List" />
      from tbl_user
      where id = #{id,jdbcType=BIGINT}
    </select>
    
    <select id="findByUsername" parameterType="java.lang.String" resultMap="BaseResultMap">
      select
      <include refid="Base_Column_List" />
      from tbl_user
      where phone = #{username,jdbcType=VARCHAR}
    </select>
    
    
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
      <!--@mbg.generated-->
      delete from tbl_user
      where id = #{id,jdbcType=BIGINT}
    </delete>
    <insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.baba.security.auth.entity.User" useGeneratedKeys="true">
      <!--@mbg.generated-->
      insert into tbl_user (pid, tenant_id, username,
        `password`, nick, gender,
        age, head_img, phone,
        `state`, push_token, app_salt,
        web_salt, enabled, accountNonExpired,
        accountNonLocked, credentialsNonExpired,
        create_time, update_time, create_by,
        update_by)
      values (#{pid,jdbcType=BIGINT}, #{tenantId,jdbcType=BIGINT}, #{username,jdbcType=VARCHAR},
        #{password,jdbcType=VARCHAR}, #{nick,jdbcType=VARCHAR}, #{gender,jdbcType=INTEGER},
        #{age,jdbcType=INTEGER}, #{headImg,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR},
        #{state,jdbcType=INTEGER}, #{pushToken,jdbcType=VARCHAR}, #{appSalt,jdbcType=VARCHAR},
        #{webSalt,jdbcType=VARCHAR}, #{enabled,jdbcType=BOOLEAN}, #{accountNonExpired,jdbcType=BOOLEAN},
        #{accountNonLocked,jdbcType=BOOLEAN}, #{credentialsNonExpired,jdbcType=BOOLEAN},
        #{createTime,jdbcType=DATE}, #{updateTime,jdbcType=DATE}, #{createBy,jdbcType=VARCHAR},
        #{updateBy,jdbcType=VARCHAR})
    </insert>
    <insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.baba.security.auth.entity.User" useGeneratedKeys="true">
      <!--@mbg.generated-->
      insert into tbl_user
      <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="pid != null">
          pid,
        </if>
        <if test="tenantId != null">
          tenant_id,
        </if>
        <if test="username != null">
          username,
        </if>
        <if test="password != null">
          `password`,
        </if>
        <if test="nick != null">
          nick,
        </if>
        <if test="gender != null">
          gender,
        </if>
        <if test="age != null">
          age,
        </if>
        <if test="headImg != null">
          head_img,
        </if>
        <if test="phone != null">
          phone,
        </if>
        <if test="state != null">
          `state`,
        </if>
        <if test="pushToken != null">
          push_token,
        </if>
        <if test="appSalt != null">
          app_salt,
        </if>
        <if test="webSalt != null">
          web_salt,
        </if>
        <if test="enabled != null">
          enabled,
        </if>
        <if test="accountNonExpired != null">
          accountNonExpired,
        </if>
        <if test="accountNonLocked != null">
          accountNonLocked,
        </if>
        <if test="credentialsNonExpired != null">
          credentialsNonExpired,
        </if>
        <if test="createTime != null">
          create_time,
        </if>
        <if test="updateTime != null">
          update_time,
        </if>
        <if test="createBy != null">
          create_by,
        </if>
        <if test="updateBy != null">
          update_by,
        </if>
      </trim>
      <trim prefix="values (" suffix=")" suffixOverrides=",">
        <if test="pid != null">
          #{pid,jdbcType=BIGINT},
        </if>
        <if test="tenantId != null">
          #{tenantId,jdbcType=BIGINT},
        </if>
        <if test="username != null">
          #{username,jdbcType=VARCHAR},
        </if>
        <if test="password != null">
          #{password,jdbcType=VARCHAR},
        </if>
        <if test="nick != null">
          #{nick,jdbcType=VARCHAR},
        </if>
        <if test="gender != null">
          #{gender,jdbcType=INTEGER},
        </if>
        <if test="age != null">
          #{age,jdbcType=INTEGER},
        </if>
        <if test="headImg != null">
          #{headImg,jdbcType=VARCHAR},
        </if>
        <if test="phone != null">
          #{phone,jdbcType=VARCHAR},
        </if>
        <if test="state != null">
          #{state,jdbcType=INTEGER},
        </if>
        <if test="pushToken != null">
          #{pushToken,jdbcType=VARCHAR},
        </if>
        <if test="appSalt != null">
          #{appSalt,jdbcType=VARCHAR},
        </if>
        <if test="webSalt != null">
          #{webSalt,jdbcType=VARCHAR},
        </if>
        <if test="enabled != null">
          #{enabled,jdbcType=BOOLEAN},
        </if>
        <if test="accountNonExpired != null">
          #{accountNonExpired,jdbcType=BOOLEAN},
        </if>
        <if test="accountNonLocked != null">
          #{accountNonLocked,jdbcType=BOOLEAN},
        </if>
        <if test="credentialsNonExpired != null">
          #{credentialsNonExpired,jdbcType=BOOLEAN},
        </if>
        <if test="createTime != null">
          #{createTime,jdbcType=DATE},
        </if>
        <if test="updateTime != null">
          #{updateTime,jdbcType=DATE},
        </if>
        <if test="createBy != null">
          #{createBy,jdbcType=VARCHAR},
        </if>
        <if test="updateBy != null">
          #{updateBy,jdbcType=VARCHAR},
        </if>
      </trim>
    </insert>
    <update id="updateByPrimaryKeySelective" parameterType="com.baba.security.auth.entity.User">
      <!--@mbg.generated-->
      update tbl_user
      <set>
        <if test="pid != null">
          pid = #{pid,jdbcType=BIGINT},
        </if>
        <if test="tenantId != null">
          tenant_id = #{tenantId,jdbcType=BIGINT},
        </if>
        <if test="username != null">
          username = #{username,jdbcType=VARCHAR},
        </if>
        <if test="password != null">
          `password` = #{password,jdbcType=VARCHAR},
        </if>
        <if test="nick != null">
          nick = #{nick,jdbcType=VARCHAR},
        </if>
        <if test="gender != null">
          gender = #{gender,jdbcType=INTEGER},
        </if>
        <if test="age != null">
          age = #{age,jdbcType=INTEGER},
        </if>
        <if test="headImg != null">
          head_img = #{headImg,jdbcType=VARCHAR},
        </if>
        <if test="phone != null">
          phone = #{phone,jdbcType=VARCHAR},
        </if>
        <if test="state != null">
          `state` = #{state,jdbcType=INTEGER},
        </if>
        <if test="pushToken != null">
          push_token = #{pushToken,jdbcType=VARCHAR},
        </if>
        <if test="appSalt != null">
          app_salt = #{appSalt,jdbcType=VARCHAR},
        </if>
        <if test="webSalt != null">
          web_salt = #{webSalt,jdbcType=VARCHAR},
        </if>
        <if test="enabled != null">
          enabled = #{enabled,jdbcType=BOOLEAN},
        </if>
        <if test="accountNonExpired != null">
          accountNonExpired = #{accountNonExpired,jdbcType=BOOLEAN},
        </if>
        <if test="accountNonLocked != null">
          accountNonLocked = #{accountNonLocked,jdbcType=BOOLEAN},
        </if>
        <if test="credentialsNonExpired != null">
          credentialsNonExpired = #{credentialsNonExpired,jdbcType=BOOLEAN},
        </if>
        <if test="createTime != null">
          create_time = #{createTime,jdbcType=DATE},
        </if>
        <if test="updateTime != null">
          update_time = #{updateTime,jdbcType=DATE},
        </if>
        <if test="createBy != null">
          create_by = #{createBy,jdbcType=VARCHAR},
        </if>
        <if test="updateBy != null">
          update_by = #{updateBy,jdbcType=VARCHAR},
        </if>
      </set>
      where id = #{id,jdbcType=BIGINT}
    </update>
    <update id="updateByPrimaryKey" parameterType="com.baba.security.auth.entity.User">
      <!--@mbg.generated-->
      update tbl_user
      set pid = #{pid,jdbcType=BIGINT},
        tenant_id = #{tenantId,jdbcType=BIGINT},
        username = #{username,jdbcType=VARCHAR},
        `password` = #{password,jdbcType=VARCHAR},
        nick = #{nick,jdbcType=VARCHAR},
        gender = #{gender,jdbcType=INTEGER},
        age = #{age,jdbcType=INTEGER},
        head_img = #{headImg,jdbcType=VARCHAR},
        phone = #{phone,jdbcType=VARCHAR},
        `state` = #{state,jdbcType=INTEGER},
        push_token = #{pushToken,jdbcType=VARCHAR},
        app_salt = #{appSalt,jdbcType=VARCHAR},
        web_salt = #{webSalt,jdbcType=VARCHAR},
        enabled = #{enabled,jdbcType=BOOLEAN},
        accountNonExpired = #{accountNonExpired,jdbcType=BOOLEAN},
        accountNonLocked = #{accountNonLocked,jdbcType=BOOLEAN},
        credentialsNonExpired = #{credentialsNonExpired,jdbcType=BOOLEAN},
        create_time = #{createTime,jdbcType=DATE},
        update_time = #{updateTime,jdbcType=DATE},
        create_by = #{createBy,jdbcType=VARCHAR},
        update_by = #{updateBy,jdbcType=VARCHAR}
      where id = #{id,jdbcType=BIGINT}
    </update>
    <select id="findByAll" resultMap="BaseResultMap">
          <!--@mbg.generated-->
          select
          <include refid="Base_Column_List" />
          from tbl_user
          <where>
              <if test="id != null">
                  and id=#{id,jdbcType=BIGINT}
              </if>
              <if test="pid != null">
                  and pid=#{pid,jdbcType=BIGINT}
              </if>
              <if test="tenantId != null">
                  and tenant_id=#{tenantId,jdbcType=BIGINT}
              </if>
              <if test="username != null">
                  and username=#{username,jdbcType=VARCHAR}
              </if>
              <if test="password != null">
                  and `password`=#{password,jdbcType=VARCHAR}
              </if>
              <if test="nick != null">
                  and nick=#{nick,jdbcType=VARCHAR}
              </if>
              <if test="gender != null">
                  and gender=#{gender,jdbcType=INTEGER}
              </if>
              <if test="age != null">
                  and age=#{age,jdbcType=INTEGER}
              </if>
              <if test="headImg != null">
                  and head_img=#{headImg,jdbcType=VARCHAR}
              </if>
              <if test="phone != null">
                  and phone=#{phone,jdbcType=VARCHAR}
              </if>
              <if test="state != null">
                  and `state`=#{state,jdbcType=INTEGER}
              </if>
              <if test="pushToken != null">
                  and push_token=#{pushToken,jdbcType=VARCHAR}
              </if>
              <if test="appSalt != null">
                  and app_salt=#{appSalt,jdbcType=VARCHAR}
              </if>
              <if test="webSalt != null">
                  and web_salt=#{webSalt,jdbcType=VARCHAR}
              </if>
              <if test="enabled != null">
                  and enabled=#{enabled,jdbcType=BOOLEAN}
              </if>
              <if test="accountNonExpired != null">
                  and accountNonExpired=#{accountNonExpired,jdbcType=BOOLEAN}
              </if>
              <if test="accountNonLocked != null">
                  and accountNonLocked=#{accountNonLocked,jdbcType=BOOLEAN}
              </if>
              <if test="credentialsNonExpired != null">
                  and credentialsNonExpired=#{credentialsNonExpired,jdbcType=BOOLEAN}
              </if>
              <if test="createTime != null">
                  and create_time=#{createTime,jdbcType=DATE}
              </if>
              <if test="updateTime != null">
                  and update_time=#{updateTime,jdbcType=DATE}
              </if>
              <if test="createBy != null">
                  and create_by=#{createBy,jdbcType=VARCHAR}
              </if>
              <if test="updateBy != null">
                  and update_by=#{updateBy,jdbcType=VARCHAR}
              </if>
          </where>
      </select>
    </mapper>
  • 启动类

    package com.baba.security.auth;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    /**
     * Spring boot app.
     *
     * @author wulongbo 2021/11/11
     */
    
    @SpringBootApplication(scanBasePackages = {"com.baba.security.common","com.baba.security.auth"})
    @MapperScan("com.baba.security.auth.dao")
    public class Application {
    
      public static void main(String[] args) {
    
          SpringApplication.run(Application.class, args);
      }
    }
    

测试

访问 localhost:8080/auth
image.png
响应头中获取到 authorization 令牌。
我们输错地址看看有没有全局异常响应。
image.png
访问一下其他服务,在重新登录模拟挤号,在访问提示已在其他设备登录。
image.png
image.png
生成的jwt我们可以看看是啥样子的。
访问https://jwt.io/输入token,当然要把前六位(Bearer )去掉
image.png
image.png

说明

后面,我们再使用Oauth2.0来集成开放接口平台


isWulongbo
228 声望26 粉丝

在人生的头三十年,你培养习惯,后三十年,习惯铸就你