SpringBoot集成SpringSecurity完成权限拦截操作

SpringBoot集成 SpringSecurityJWT 实现认证和授权(一)

SpringSecurity(SpringSecurity是一个强大的可高度定制的认证和授权框架,对于Spring应用来说它是一套Web安全标准)

JWT(JWT是JSON WEB TOKEN的缩写,它是基于 RFC 7519 标准定义的一种可以安全传输的的JSON对象,由于使用了数字签名,所以是可信任和安全的。)

JWT实现认证和授权的原理

  • 用户调用登录接口,登录成功后获取到JWTtoken
  • 之后用户每次调用接口都在http请求的header(头部)中添加一个叫Authorization的头,值为JWT的token;
  • 后台程序通过对Authorization头中信息的解码及数字签名校验来获取其中的用户信息,从而实现认证和授权。

项目使用表说明

  • user_admin:后台用户表
  • user_role:后台用户角色表
  • user_permission:后台用户权限表
  • user_admin_role_relation:后台用户和角色关系表,用户与角色是多对多关系
  • user_role_permission_relation:后台用户角色和权限关系表,角色与权限是多对多关系

整合SpringSecurity及JWT

1. 引用依赖;

<dependencies>
    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-securityartifactId>
    dependency>
    
    <dependency>
        <groupId>cn.hutoolgroupId>
        <artifactId>hutool-allartifactId>
        <version>4.5.7version>
    dependency>
    
    <dependency>
        <groupId>io.jsonwebtokengroupId>
        <artifactId>jjwtartifactId>
        <version>0.9.0version>
    dependency>
dependencies>

2. application.yml

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/mall?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
    type: com.zaxxer.hikari.HikariDataSource
    initialization-mode: always
    continue-on-error: true
    hikari:
      minimum-idle: 5
      connection-test-query: SELECT 1 FROM DUAL
      maximum-pool-size: 20
      auto-commit: true
      idle-timeout: 30000
      pool-name: SpringBootDemoHikariCP
      max-lifetime: 60000
      connection-timeout: 30000

mybatis:
  configuration:
    # 下划线转驼峰
    map-underscore-to-camel-case: true
  mapper-locations: classpath:mappers/*.xml
  type-aliases-package: com.zhihao.entity

jwt:
  secret: zhihao #加密密钥
  expiration: 3000 #过期时间
  tokenHeader: authorize #获取请求头的key
  tokenHead: Bearer  #和前端约定token加上的前缀

3.添加JWT token的工具类(用于生成和解析token的工具类)

/**
 * JwtToken生成的工具类
 * 
 */
@Component
public class JwtTokenUtil {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);
    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;

    /**
     * 根据负责生成JWT的token
     */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 从token中获取JWT中的负载
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            LOGGER.info("JWT格式验证失败:{}",token);
        }
        return claims;
    }

    /**
     * 生成token的过期时间
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     * 从token中获取登录用户名
     */
    public String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username =  claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 验证token是否还有效
     *
     * @param token       客户端传入的token
     * @param userDetails 从数据库中查询出来的用户信息
     */
    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUserNameFromToken(token);
        return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
    }

    /**
     * 判断token是否已经失效
     */
    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }

    /**
     * 从token中获取过期时间
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
     * 根据用户信息生成token
     */
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    /**
     * 判断token是否可以被刷新
     */
    public boolean canRefresh(String token) {
        return !isTokenExpired(token);
    }

    /**
     * 刷新token
     */
    public String refreshToken(String token) {
        Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }
}

4. 添加SpringSecurity的配置类

/**
 * SpringSecurity的配置
 */
@Configuration
@EnableWebSecurity //启用security
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UmsAdminService adminService;
    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf()// 由于使用的是JWT,我们这里不需要csrf 进行关闭
                .disable()
                .sessionManagement()// 基于token,所以不管理Session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, // 允许对于网站静态资源的无授权访问
                        "/",
                        "/*.html",
                        "/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/swagger-resources/**",
                        "/v2/api-docs/**"
                )
                .permitAll()
                .antMatchers("/login", "/register")// 对登录注册要允许匿名访问
                .permitAll()
                .antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求
                .permitAll()
//                .antMatchers("/**")//测试时全部运行访问
//                .permitAll()
                .anyRequest()// 除上面外的所有请求全部需要鉴权认证
                .authenticated();
        // 禁用缓存
        httpSecurity.headers().cacheControl();
        // 添加自定义 JWT 过滤器
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //添加自定义未授权和未登录结果返回
        httpSecurity
                .exceptionHandling() //异常处理
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);
    }

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

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

    @Bean
    public UserDetailsService userDetailsService() {
        //获取登录用户信息
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                //根据用户名获取用户
                UmsAdmin admin = adminService.getAdminByUsername(username);
            if (admin != null) {
                //获取用户的所有权限
                List<UmsPermission> permissionList = adminService.getPermissionList(admin.getId());
                //返回自己实现的用户用户信息
                return new AdminUserDetails(admin,permissionList);
            }
            throw new UsernameNotFoundException("用户名或密码错误");
            }
        };
    }

    /**
     * 注册自定义JWT登录授权过滤器
     * @return JwtAuthenticationTokenFilter
     */
    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
        return new JwtAuthenticationTokenFilter();
    }

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

}

相关依赖及方法说明

  • configure(HttpSecurity httpSecurity):用于配置需要拦截的url路径、jwt过滤器及出异常后的处理器;
  • configure(AuthenticationManagerBuilder auth):用于配置UserDetailsService及PasswordEncoder;
  • RestfulAccessDeniedHandler:当用户没有访问权限时的处理器,用于返回JSON格式的处理结果;
  • RestAuthenticationEntryPoint:当未登录或token失效时,返回JSON格式的结果;
  • UserDetailsService:SpringSecurity定义的核心接口,用于根据用户名获取用户信息,需要自行实现;
  • UserDetails:SpringSecurity定义用于封装用户信息的类(主要是用户信息和权限),需要自行实现;
  • PasswordEncoder:SpringSecurity定义的用于对密码进行编码及比对的接口,目前使用的是BCryptPasswordEncoder;
  • JwtAuthenticationTokenFilter:在用户名和密码校验前添加的过滤器,如果有jwt的token,会自行根据token信息进行登录。

5.RestfulAccessDeniedHandler

当用户没有访问权限时的处理器

/**
 * 当访问接口没有权限时,自定义的返回结果
 */
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler{
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException e) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSONUtil.parse(CommonResult.forbidden(e.getMessage())));
//        response.getWriter().println(e.getMessage());
        response.getWriter().flush();
    }
}

6. RestAuthenticationEntryPoint

当未登录或token失效时,返回JSON格式的结果;

/**
 * 当未登录或者token失效访问接口时,自定义的返回结果
 */
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSONUtil.parse(CommonResult.unauthorized(authException.getMessage())));
//        response.getWriter().println(authException.getMessage());
        response.getWriter().flush();
    }
}

7. 自定义JWT过滤器JwtAuthenticationTokenFilter

/**
 * JWT登录授权过滤器
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        //获取请求头
        String authHeader = request.getHeader(this.tokenHeader);
        if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
            String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
            //根据token获取用户名
            String username = jwtTokenUtil.getUserNameFromToken(authToken);
            LOGGER.info("用户名: username:{}", username);
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    LOGGER.info("authenticated user:{}", username);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        //放行
        chain.doFilter(request, response);
    }
}

8. UmsAdminService

public interface UmsAdminService {

    /**
     * 根据用户名获取用户
     *
     * @param username 用户名
     * @return com.zhihao.entity.UmsAdmin
     * @author: zhihao
     * @date: 15/1/2020
     */
    UmsAdmin getAdminByUsername(String username);

    /** 
     * 根据用户id获取用户拥有的权限 
     *
     * @param id 用户id
     * @return java.util.List 
     * @author: zhihao
     * @date: 15/1/2020 
     */
    List<UmsPermission> getPermissionList(Long id);
}

9. 实现类和mapper接口与xml文件.(登录那放上全部)

登录功能与权限校验实现

1. UmsAdminController

@RestController
public class UmsAdminController {

    @Autowired
    private UmsAdminService umsAdminService;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    private Map<String,Object> resultMap;
    
    //注册省略..其他等等省略

    /**
     * 登录接口,登录成功返回token
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public CommonResult login(String username,String password){
        resultMap = new HashMap<>();
        String token = umsAdminService.login(username, password);
        if (token == null) {
            return CommonResult.failed("用户名或密码错误");
        }
        resultMap.put("token", token);
        return CommonResult.success(resultMap);
    }

    /**
     * 登出功能
     * @return
     */
    @PostMapping(value = "/logout")
    public CommonResult logout() {
        return CommonResult.success(null);
    }

    /**
     * 刷新token
     * @param request
     * @return
     */
    @GetMapping(value = "/refreshToken")
    @ResponseBody
    public CommonResult refreshToken(HttpServletRequest request) {
        //获取去掉前缀请求头的token
        String token = request.getHeader(tokenHeader).substring(6);
        String refreshToken = umsAdminService.refreshToken(token);
        if (refreshToken == null) {
            return CommonResult.failed("token已经过期!");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        return CommonResult.success(tokenMap);
    }

    /**
     * 权限测试接口
     * @return
     */
    @GetMapping("/test")
    @PreAuthorize("hasAuthority('pms:brand:delete')")
    public CommonResult getBrandList() {
        return CommonResult.success("权限访问成功");
    }
}

2. 修改后的UmsAdminService

public interface UmsAdminService {

    /**
     * 根据用户名获取用户
     *
     * @param username 用户名
     * @return com.zhihao.entity.UmsAdmin
     * @author: zhihao
     * @date: 15/1/2020
     */
    UmsAdmin getAdminByUsername(String username);

    /**
     * 根据用户id获取用户拥有的权限
     *
     * @param id 用户id
     * @return java.util.List
     * @author: zhihao
     * @date: 15/1/2020
     */
    List<UmsPermission> getPermissionList(Long id);

    /**
     * 登录成功返回token
     * @param username
     * @param password
     * @return
     */
    String login(String username,String password);

    /**
     * 刷新token
     * @param token
     * @return
     */
    String refreshToken(String token);
}

3. UmsAdminServiceImpl实现类

/**
 * @Author: zhihao
 * @Date: 15/1/2020 下午 9:32
 * @Description:
 * @Versions 1.0
 **/
@Service
public class UmsAdminServiceImpl implements UmsAdminService {
   private Logger LOGGER = LoggerFactory.getLogger(UmsAdminServiceImpl.class);

    @Autowired
    private UmsAdminMapper umsAdminMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Override
    public UmsAdmin getAdminByUsername(String username) {
        return umsAdminMapper.getAdminByUsername(username);
    }

    @Override
    public List<UmsPermission> getPermissionList(Long id) {
        return umsAdminMapper.getPermissionList(id);
    }


    @Override
    public String login(String username, String password) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByUsername(username);
            if(!passwordEncoder.matches(password,userDetails.getPassword())){
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    @Override
    public String refreshToken(String token) {
        if (jwtTokenUtil.canRefresh(token)){
            return jwtTokenUtil.refreshToken(token);
        }
        return null;
    }

    public UserDetails loadUserByUsername(String username){
        //获取用户信息
        UmsAdmin admin = getAdminByUsername(username);
        if (admin != null) {
            List<UmsPermission> permissionList = getPermissionList(admin.getId());
            return new AdminUserDetails(admin,permissionList);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }
}

4. dao层UmsAdminMapper

@Mapper
public interface UmsAdminMapper {

    UmsAdmin getAdminByUsername(String username);

    List<UmsPermission> getPermissionList(Long id);
}

UmsAdminMapper.xml


DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhihao.dao.UmsAdminMapper">

    <select id="getAdminByUsername" parameterType="string" resultType="com.zhihao.entity.UmsAdmin">
        select *  from ums_admin where username = #{username}
    select>

    <select id="getPermissionList" parameterType="long" resultType="com.zhihao.entity.UmsPermission">
        SELECT * FROM `ums_permission` pr
        LEFT JOIN ums_role_permission_relation re ON pr.pid = re.permission_id
        LEFT JOIN ums_role ro ON ro.id = re.role_id
        LEFT JOIN ums_admin_role_relation r ON r.role_id=ro.id
        LEFT JOIN ums_admin ad ON ad.id = r.admin_id
        WHERE ad.id = #{id}
    select>
mapper>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vO7z5jsN-1579102390934)(https://app.yinxiang.com/FileSharing.action?hash=1/031b2da0b4dea7e84c8e1784cfb9aa82-46136)]

UmsPermissionUmsAdmin 实体类与数据库文件在项目代码里面

  • from ums_admin where username = #{username}

    SELECT * FROM `ums_permission` pr LEFT JOIN ums_role_permission_relation re ON pr.pid = re.permission_id LEFT JOIN ums_role ro ON ro.id = re.role_id LEFT JOIN ums_admin_role_relation r ON r.role_id=ro.id LEFT JOIN ums_admin ad ON ad.id = r.admin_id WHERE ad.id = #{id}
```

SpringBoot集成SpringSecurity完成权限拦截操作_第1张图片
项目帐号密码都是123456

UmsPermissionUmsAdmin 实体类与数据库文件在项目代码里面

项目代码(点击打开)

你可能感兴趣的:(Java,SpringBoot,Spring)