Spring Boot2 + Spring Security + JWT 实现项目级前后端分离认证授权

一 简介

Spring Security 是 Spring 家族中的一个安全管理框架。相比与另外一个安全框架 Shiro,它提供了更丰富的功能,扩展性更好,社区资源也比 Shiro 丰富。在 Spring Boot 出现之前,Spring Security 就已经发展了多年了,但是使用的并不多,安全管理这个领域,一直是 Shiro 的天下。
相对于 Shiro,在 SSM/SSH 中整合 Spring Security 都是比较麻烦的操作,所以 Spring Security 虽然功能比 Shiro 强大,但是使用反而没有 Shiro 多(Shiro 虽然功能没有 Spring Security 多,但是对于大部分项目而言,Shiro 上手简单也够用了)。
自从有了 Spring Boot 之后,Spring Boot 对于 Spring Security 提供了 自动化配置方案,可以零配置使用 Spring Security。

一般 WEB 应用的需要进行认证和授权。

  • 认证:验证当前访问系统的是不是系统用户,并且要确认具体是那个用户。
  • 授权:经过认证后判断当前用户是否有权限进行某个操作。

常见的安全管理技术栈的组合是这样的:

  • SSM + Shiro
  • Spring Boot/Spring Cloud + Spring Security

注意:这只是一个推荐的组合而已,如果单纯从技术上来说,无论怎么组合,都是可以运行的。

二 实际使用

项目技术:Spring Boo2 、Spring Security、MyBatis、MySQL

项目结构:

Spring Boot2 + Spring Security + JWT 实现项目级前后端分离认证授权_第1张图片

2.1 pom.xml

        
        
            org.springframework.boot
            spring-boot-starter-security
        

        
        
            io.jsonwebtoken
            jjwt
            0.9.0
        

2.2 application.properties

# jwt token配置
# 令牌自定义标识
jwt.token.header=token
# 令牌秘钥
jwt.token.secret=abcdefghijklmnopqrstuvwxyz
# 令牌有效期(默认30分钟)
jwt.token.expireTime=30

2.3 JwtToken工具类

package com.modules.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName JwtTokenUtil
 * @Description JwtToken生成的工具类
 * @Author li'chao
 * @Date 2022-3-8 17:17
 * @Version 1.0
 **/
@Slf4j
@Component
public class JwtTokenUtil {

    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";

    // 令牌自定义标识
    @Value("${jwt.token.header}")
    private String header;

    // 令牌秘钥
    @Value("${jwt.token.secret}")
    private String secret;

    // 令牌有效期(默认30分钟)
    @Value("${jwt.token.expireTime}")
    private Long expiration;


    /**
     * 根据负责生成JWT的token
     */
    private String generateToken(Map 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) {
            log.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是否已经失效
     */
    public 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 claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    /**
     * 根据用户信息生成token
     */
    public String generateToken(LoginUser loginUser) {
        Map claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, loginUser.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);
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    public String getToken(HttpServletRequest request)
    {
        return request.getHeader(header);
    }
}

2.4 自定义权限不足处理类

package com.modules.security.handle;

import com.alibaba.fastjson.JSON;
import com.modules.common.utils.ServletUtils;
import com.modules.common.web.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 当访问接口没有权限时,自定义的返回结果
 *
 * @author li'chao
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        ServletUtils.renderString(response, JSON.toJSONString(Result.unauth("权限不足")));
    }
}

2.5 自定义认证失败处理类

package com.modules.security.handle;

import com.alibaba.fastjson.JSON;
import com.modules.common.utils.ServletUtils;
import com.modules.common.web.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败处理类 自定义返回未授权
 *
 * @author li'chao
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint
{

    @Override
    public void commence(HttpServletRequest equest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        ServletUtils.renderString(response, JSON.toJSONString(Result.auth("token认证失败")));
    }
}

2.6 自定义 token 验证类

package com.modules.security.handle;

import com.alibaba.fastjson.JSON;
import com.modules.common.utils.ServletUtils;
import com.modules.common.web.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败处理类 自定义返回未授权
 *
 * @author li'chao
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint
{

    @Override
    public void commence(HttpServletRequest equest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        ServletUtils.renderString(response, JSON.toJSONString(Result.auth("token认证失败")));
    }
}

2.7 自定义登录处理

package com.modules.security;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.modules.system.entity.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Set;

/**
 * 登录用户身份权限
 *
 * @author li'chao
 */
public class LoginUser implements UserDetails
{
    private static final long serialVersionUID = 1L;

    /**
     * 用户唯一标识
     */
    private String token;

    /**
     * 登陆时间
     */
    private Long loginTime;

    /**
     * 过期时间
     */
    private Long expireTime;

    /**
     * 登录IP地址
     */
    private String ipaddr;

    /**
     * 登录地点
     */
    private String loginLocation;

    /**
     * 浏览器类型
     */
    private String browser;

    /**
     * 操作系统
     */
    private String os;

    /**
     * 权限列表
     */
    private Set permissions;

    /**
     * 用户信息
     */
    private SysUser user;

    public String getToken()
    {
        return token;
    }

    public void setToken(String token)
    {
        this.token = token;
    }

    public LoginUser()
    {
    }

    public LoginUser(SysUser user, Set permissions)
    {
        this.user = user;
        this.permissions = permissions;
    }

    @JsonIgnore
    @Override
    public String getPassword()
    {
        return user.getPassword();
    }

    @Override
    public String getUsername()
    {
        return user.getUserName();
    }

    /**
     * 账户是否未过期,过期无法验证
     */
    @JsonIgnore
    @Override
    public boolean isAccountNonExpired()
    {
        return true;
    }

    /**
     * 指定用户是否解锁,锁定的用户无法进行身份验证
     *
     * @return
     */
    @JsonIgnore
    @Override
    public boolean isAccountNonLocked()
    {
        return true;
    }

    /**
     * 指示是否已过期的用户的凭据(密码),过期的凭据防止认证
     *
     * @return
     */
    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired()
    {
        return true;
    }

    /**
     * 是否可用 ,禁用的用户不能身份验证
     *
     * @return
     */
    @JsonIgnore
    @Override
    public boolean isEnabled()
    {
        return true;
    }

    public Long getLoginTime()
    {
        return loginTime;
    }

    public void setLoginTime(Long loginTime)
    {
        this.loginTime = loginTime;
    }

    public String getIpaddr()
    {
        return ipaddr;
    }

    public void setIpaddr(String ipaddr)
    {
        this.ipaddr = ipaddr;
    }

    public String getLoginLocation()
    {
        return loginLocation;
    }

    public void setLoginLocation(String loginLocation)
    {
        this.loginLocation = loginLocation;
    }

    public String getBrowser()
    {
        return browser;
    }

    public void setBrowser(String browser)
    {
        this.browser = browser;
    }

    public String getOs()
    {
        return os;
    }

    public void setOs(String os)
    {
        this.os = os;
    }

    public Long getExpireTime()
    {
        return expireTime;
    }

    public void setExpireTime(Long expireTime)
    {
        this.expireTime = expireTime;
    }

    public Set getPermissions()
    {
        return permissions;
    }

    public void setPermissions(Set permissions)
    {
        this.permissions = permissions;
    }

    public SysUser getUser()
    {
        return user;
    }

    public void setUser(SysUser user)
    {
        this.user = user;
    }

    @Override
    public Collection getAuthorities()
    {
        return null;
    }
}
package com.modules.security.service;

import com.modules.common.enmus.PublicEnum;
import com.modules.common.exception.CustomException;
import com.modules.common.utils.StringUtils;
import com.modules.security.LoginUser;
import com.modules.system.entity.SysUser;
import com.modules.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.Service;

/**
 * @ClassName UserDetailsServiceImpl
 * @Description 用户验证处理
 * @Author li'chao
 * @Date 2022-3-9 22:20
 * @Version 1.0
 **/
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 登录信息验证
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.selectUserByLoginName(username);
        if (StringUtils.isNull(sysUser))
        {
            log.info("登录用户:{} 不存在.", username);
            throw new UsernameNotFoundException("登录账号不存在");
        }
        else if (PublicEnum.DELETE.getCode().equals(sysUser.getStatus()))
        {
            log.info("登录用户:{} 已被删除.", username);
            throw new CustomException("账号已被删除");
        }
        else if (PublicEnum.DISABLE.getCode().equals(sysUser.getStatus()))
        {
            log.info("登录用户:{} 已被停用.", username);
            throw new CustomException("账号已停用");
        }
        return createLoginUser(sysUser);
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user, null);
    }
}
package com.modules.security.service;

import com.modules.security.JwtTokenUtil;
import com.modules.security.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

/**
 * @ClassName LoginService
 * @Description 登录校验
 * @Author li'chao
 * @Date 2022-3-11 14:21
 * @Version 1.0
 **/
@Slf4j
@Service
public class LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public LoginUser login(String username, String password) {
        String token = null;
        LoginUser loginUser = null;
        // 用户验证
        Authentication authentication = null;
        // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
        authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        loginUser = (LoginUser) authentication.getPrincipal();
        token = jwtTokenUtil.generateToken(loginUser);
        loginUser.setToken(token);
        return loginUser;
    }
}
package com.modules.common.web;


import com.modules.common.utils.StringUtils;

import java.util.HashMap;

/**
 * 操作消息提醒
 *
 * @author lc
 */
public class Result extends HashMap {
    private static final long serialVersionUID = 1L;

    public static final String CODE_TAG = "code";

    public static final String MSG_TAG = "msg";

    public static final String DATA_TAG = "data";
    public static final String success_Count = "successCount";
    public static final String fail_Count = "failCount";
    public static final String messCell_Count = "messCellCount";

    /**
     * 状态类型
     */
    public enum Type {
        /**
         * 成功
         */
        SUCCESS(200),
        /**
         * 警告
         */
        WARN(300),

        /**
         * 失败
         */
        FAIL(400),

        /**
         * 错误
         */
        ERROR(500),

        /**
         * 权限不足
         */
        UNAUTH(600),

        /**
         * token认证失败
         */
        AUTH(700);

        private final int value;


        Type(int value) {
            this.value = value;
        }

        public int value() {
            return this.value;
        }
    }

    /**
     * 初始化一个新创建的 Result 对象,使其表示一个空消息。
     *
     * @param type
     * @param msg
     * @param successCount
     * @param failCount
     * @param messCellCount
     * @param data
     */
    public Result(Type type, String msg, int successCount, int failCount, int messCellCount, Object data) {
        super.put(CODE_TAG, type.value);
        super.put(MSG_TAG, msg);
        if (StringUtils.isNotNull(data)) {
            super.put(DATA_TAG, data);
        }
        super.put(success_Count, successCount);
        super.put(fail_Count, failCount);
        super.put(messCell_Count, messCellCount);

    }

    /**
     * 初始化一个新创建的 Result 对象
     *
     * @param type 状态类型
     * @param msg  返回内容
     */
    public Result(Type type, String msg) {
        super.put(CODE_TAG, type.value);
        super.put(MSG_TAG, msg);
    }

    /**
     * 初始化一个新创建的 Result 对象
     *
     * @param type 状态类型
     * @param msg  返回内容
     * @param data 数据对象
     */
    public Result(Type type, Object msg, Object data) {
        super.put(CODE_TAG, type.value);
        super.put(MSG_TAG, msg);
        if (StringUtils.isNotNull(data)) {
            super.put(DATA_TAG, data);
        }
    }

    /**
     * 返回成功消息
     *
     * @return 成功消息
     */
    public static Result success() {
        return success("操作成功");
    }

    /**
     * 返回成功数据
     *
     * @return 成功消息
     */
    public static Result success(Object data) {
        return success("操作成功", data);
    }

    /**
     * 返回成功消息
     *
     * @param msg 返回内容
     * @return 成功消息
     */
    public static Result success(String msg) {
        return success(msg, null);
    }

    /**
     * 返回成功消息
     *
     * @param msg  返回内容
     * @param data 数据对象
     * @return 成功消息
     */
    public static Result success(String msg, Object data) {
        return new Result(Type.SUCCESS, msg, data);
    }

    /**
     * 返回成功消息
     *
     * @param msg           返回内容
     * @param data          数据对象
     * @param successCount  成功数据集条数
     * @param failCount     失败条数条数
     * @param messCellCount 异常单元格条数
     * @return 成功消息
     */
    public static Result success(String msg, int successCount, int failCount, int messCellCount, Object data) {
        return new Result(Type.SUCCESS, msg, successCount, failCount, messCellCount, data);
    }

    /**
     * 返回成功消息
     *
     * @param msg           返回内容
     * @param data          数据对象
     * @param successCount  成功数据集条数
     * @param failCount     失败条数条数
     * @param messCellCount 异常单元格条数
     * @return 失败消息
     */
    public static Result error(String msg, int successCount, int failCount, int messCellCount, Object data) {
        return new Result(Type.ERROR, msg, successCount, failCount, messCellCount, data);
    }


    /**
     * 返回警告消息
     *
     * @param msg 返回内容
     * @return 警告消息
     */
    public static Result warn(String msg) {
        return warn(msg, null);
    }

    /**
     * 返回警告消息
     *
     * @param msg  返回内容
     * @param data 数据对象
     * @return 警告消息
     */
    public static Result warn(String msg, Object data) {
        return new Result(Type.WARN, msg, data);
    }

    /**
     * 返回错误消息
     *
     * @return
     */
    public static Result error() {
        return error("操作失败");
    }

    /**
     * 返回错误消息
     *
     * @param msg 返回内容
     * @return 警告消息
     */
    public static Result error(Object msg) {
        return error(msg, null);
    }

    /**
     * 返回错误消息
     *
     * @param msg  返回内容
     * @param data 数据对象
     * @return 警告消息
     */
    public static Result error(Object msg, Object data) {
        return new Result(Type.ERROR, msg, data);
    }

    /**
     * 返回权限不足消息
     *
     * @return
     */
    public static Result unauth() {
        return error("权限不足");
    }

    /**
     * 返回权限不足消息
     *
     * @param msg 返回内容
     * @return 警告消息
     */
    public static Result unauth(String msg) {
        return error(msg, null);
    }

    /**
     * 返回无权限信息
     *
     * @param msg  返回内容
     * @param data 数据对象
     * @return 警告消息
     */
    public static Result unauth(String msg, Object data) {
        return new Result(Type.UNAUTH, msg, data);
    }

    /**
     * 返回token认证失败消息
     *
     * @return
     */
    public static Result auth() {
        return error("token认证失败");
    }

    /**
     * 返回token认证失败消息
     *
     * @param msg 返回内容
     * @return 警告消息
     */
    public static Result auth(String msg) {
        return error(msg, null);
    }

    /**
     * 返回token认证失败消息
     *
     * @param msg  返回内容
     * @param data 数据对象
     * @return 警告消息
     */
    public static Result auth(String msg, Object data) {
        return new Result(Type.AUTH, msg, data);
    }

    /**
     * 返回失败消息
     *
     * @return
     */
    public static Result fail()
    {
        return fail("操作失败");
    }

    /**
     * 返返回失败消息
     *
     * @param msg 返回内容
     * @return 警告消息
     */
    public static Result fail(String msg)
    {
        return fail(msg, null);
    }

    /**
     * 返回失败消息
     *
     * @param msg 返回内容
     * @param data 数据对象
     * @return 警告消息
     */
    public static Result fail(String msg, Object data)
    {
        return new Result(Type.FAIL, msg, data);
    }

}

2.8 SpringSecurity 核心配置

package com.modules.common.config;

import com.modules.security.filter.JwtAuthenticationTokenFilter;
import com.modules.security.handle.AccessDeniedHandlerImpl;
import com.modules.security.handle.AuthenticationEntryPointImpl;
import com.modules.security.handle.LogoutSuccessHandlerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.method.configuration.EnableGlobalMethodSecurity;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @ClassName SecurityConfig
 * @Description SpringSecurity的配置
 * @Author li'chao
 * @Date 2022-3-8 17:46
 * @Version 1.0
 **/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 自定义用户认证逻辑
     */
    @Resource
    private UserDetailsService userDetailsService;

    /**
     * 自定义权限不足处理类
     */
    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandler;

    /**
     * 自定义认证失败处理类
     */
    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPoint;

    /**
     * 自定义退出处理类
     */
    @Autowired
    private LogoutSuccessHandlerImpl logoutSuccessHandler;

    /**
     * token认证过滤器
     */
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;


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


    /**
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问(非remember-me下自动登录)
     * hasAnyAuthority     |   如果有参数,参数表示权限,则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数,参数表示角色,则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数,参数表示权限,则其权限可以访问
     * hasIpAddress        |   如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
     * hasRole             |   如果有参数,参数表示角色,则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        httpSecurity
                // CRSF禁用,因为不使用session
                .csrf().disable()
                .exceptionHandling()
                // 认证失败处理类
                .authenticationEntryPoint(authenticationEntryPoint)
                // 权限不足处理类
                .accessDeniedHandler(accessDeniedHandler)
                .and()
                // 基于token,所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 过滤请求
                .authorizeRequests()
                // 对于登录login 验证码captchaImage 允许匿名访问
                .antMatchers("/user/**", "/captchaImage").anonymous()
                .antMatchers(
                        HttpMethod.GET,
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                ).permitAll()
                .antMatchers("/profile/**").anonymous()
                .antMatchers("/common/download**").anonymous()
                .antMatchers("/common/download/resource**").anonymous()
                .antMatchers("/swagger-ui.html").anonymous()
                .antMatchers("/swagger-resources/**").anonymous()
                .antMatchers("/webjars/**").anonymous()
                .antMatchers("/*/api-docs").anonymous()
                .antMatchers("/druid/**").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                .and()
                .headers().frameOptions().disable();
        httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
        // 添加JWT filter
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

    /**
     * 自定义身份认证
     */
    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception
    {
        builder.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    /**
     * 强散列哈希加密实现密码加密
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder()
    {
        return new BCryptPasswordEncoder();
    }

}

2.9 登录控制类

package com.modules.system.controller;

import com.modules.common.aspectj.Log;
import com.modules.common.enmus.BusinessType;
import com.modules.common.web.BaseController;
import com.modules.common.web.Result;
import com.modules.security.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录管理
 *
 * @author lc
 */
@Api(tags = "登录管理")
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/user")
public class LoginController extends BaseController {

    @Autowired
    private LoginService loginService;

    @Log(title = "用户登录", businessType = BusinessType.LOGIN)
    @ApiOperation(value = "用户登录", notes = "用户登录")
    @PostMapping(value = "/login")
    public Result login(HttpServletRequest request,
                        @ApiParam(name = "loginName", value = "登录账号") @RequestParam(value = "loginName", required = true) String loginName,
                        @ApiParam(name = "password", value = "密码") @RequestParam(value = "password", required = true) String password) {
        try {
            return success(loginService.login(loginName, password));
        }catch (Exception e) {
            if(e instanceof BadCredentialsException){
                log.error("BadCredentialsException=====>账号或者密码错误", e.getMessage());
                return error("账号或者密码错误");
            }else {
                log.error("CustomException=====>", e.getMessage());
                return error(e.getMessage());
            }
        }
    }
}

2.10 Swagger2的接口配置

package com.modules.common.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * Swagger2的接口配置
 *
 * @author lc
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Value("${swagger.show}")
    private boolean swaggerShow;

    /**
     * 创建API
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                // 是否开启
                .enable(swaggerShow)
                // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
                .apiInfo(apiInfo())
                // 全局header配置
//                .globalOperationParameters(parameters)
                // 设置哪些接口暴露给Swagger展示
                .select()
                // 扫描所有有注解的api,用这种方式更灵活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 扫描指定包中的swagger注解
                //.apis(RequestHandlerSelectors.basePackage("com.modules.swagger"))
                // 扫描所有 .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                /* 设置安全模式,swagger可以设置访问token */
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    /**
     * 安全模式,这里指定token通过Authorization头请求头传递
     */
    private List securitySchemes()
    {
        List apiKeyList = new ArrayList();
        apiKeyList.add(new ApiKey("token", "token", "header"));
        return apiKeyList;
    }

    /**
     * 安全上下文
     */
    private List securityContexts()
    {
        List securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(PathSelectors.regex("^(?!auth).*$"))
                        .build());
        return securityContexts;
    }

    /**
     * 默认的安全上引用
     */
    private List defaultAuth()
    {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("token", authorizationScopes));
        return securityReferences;
    }

    /**
     * 添加摘要信息
     */
    private ApiInfo apiInfo() {
        // 用ApiInfoBuilder进行定制
        return new ApiInfoBuilder()
                // 设置标题
                .title("标题:系统接口文档")
                // 描述
                .description("描述:用于描述系统接口...")
                // 作者信息
                .contact(new Contact("lc", null, null))
                // 版本
                .version("版本号:" + "v1.0.0")
                .build();
    }
}

你可能感兴趣的:(Spring,Cloud,Spring,Security,安全管理框架,认证授权,token,JWT)