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

2023-10-17 15:20

本文主要是介绍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

项目结构:

2.1 pom.xml

        <!-- spring security 安全认证 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><!--Token生成与解析--><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.0</version></dependency>

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<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) {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<String, Object> 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<String, Object> 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 {@Overridepublic 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
{@Overridepublic 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
{@Overridepublic 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<String> permissions;/*** 用户信息*/private SysUser user;public String getToken(){return token;}public void setToken(String token){this.token = token;}public LoginUser(){}public LoginUser(SysUser user, Set<String> permissions){this.user = user;this.permissions = permissions;}@JsonIgnore@Overridepublic String getPassword(){return user.getPassword();}@Overridepublic String getUsername(){return user.getUserName();}/*** 账户是否未过期,过期无法验证*/@JsonIgnore@Overridepublic boolean isAccountNonExpired(){return true;}/*** 指定用户是否解锁,锁定的用户无法进行身份验证** @return*/@JsonIgnore@Overridepublic boolean isAccountNonLocked(){return true;}/*** 指示是否已过期的用户的凭据(密码),过期的凭据防止认证** @return*/@JsonIgnore@Overridepublic boolean isCredentialsNonExpired(){return true;}/*** 是否可用 ,禁用的用户不能身份验证** @return*/@JsonIgnore@Overridepublic 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<String> getPermissions(){return permissions;}public void setPermissions(Set<String> permissions){this.permissions = permissions;}public SysUser getUser(){return user;}public void setUser(SysUser user){this.user = user;}@Overridepublic Collection<? extends GrantedAuthority> 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 {@Autowiredprivate SysUserService sysUserService;/*** 登录信息验证* @param username* @return* @throws UsernameNotFoundException*/@Overridepublic 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 {@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate JwtTokenUtil jwtTokenUtil;/*** 登录验证** @param username 用户名* @param password 密码* @return 结果*/public LoginUser login(String username, String password) {String token = null;LoginUser loginUser = null;// 用户验证Authentication authentication = null;// 该方法会去调用UserDetailsServiceImpl.loadUserByUsernameauthentication = 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<String, Object> {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 {/*** 自定义用户认证逻辑*/@Resourceprivate UserDetailsService userDetailsService;/*** 自定义权限不足处理类*/@Autowiredprivate AccessDeniedHandlerImpl accessDeniedHandler;/*** 自定义认证失败处理类*/@Autowiredprivate AuthenticationEntryPointImpl authenticationEntryPoint;/*** 自定义退出处理类*/@Autowiredprivate LogoutSuccessHandlerImpl logoutSuccessHandler;/*** token认证过滤器*/@Autowiredprivate JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;/*** 注入 AuthenticationManager** @return* @throws Exception*/@Bean@Overridepublic 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       |   用户登录后可访问*/@Overrideprotected 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 filterhttpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);}/*** 自定义身份认证*/@Overrideprotected void configure(AuthenticationManagerBuilder builder) throws Exception{builder.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());}/*** 强散列哈希加密实现密码加密*/@Beanpublic 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 {@Autowiredprivate 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*/@Beanpublic 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<ApiKey> securitySchemes(){List<ApiKey> apiKeyList = new ArrayList<ApiKey>();apiKeyList.add(new ApiKey("token", "token", "header"));return apiKeyList;}/*** 安全上下文*/private List<SecurityContext> securityContexts(){List<SecurityContext> securityContexts = new ArrayList<>();securityContexts.add(SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex("^(?!auth).*$")).build());return securityContexts;}/*** 默认的安全上引用*/private List<SecurityReference> defaultAuth(){AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];authorizationScopes[0] = authorizationScope;List<SecurityReference> 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 Boot2 + Spring Security + JWT 实现项目级前后端分离认证授权的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/226276

相关文章

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

HTTP 与 SpringBoot 参数提交与接收协议方式

《HTTP与SpringBoot参数提交与接收协议方式》HTTP参数提交方式包括URL查询、表单、JSON/XML、路径变量、头部、Cookie、GraphQL、WebSocket和SSE,依据... 目录HTTP 协议支持多种参数提交方式,主要取决于请求方法(Method)和内容类型(Content-Ty

深度解析Java @Serial 注解及常见错误案例

《深度解析Java@Serial注解及常见错误案例》Java14引入@Serial注解,用于编译时校验序列化成员,替代传统方式解决运行时错误,适用于Serializable类的方法/字段,需注意签... 目录Java @Serial 注解深度解析1. 注解本质2. 核心作用(1) 主要用途(2) 适用位置3

sky-take-out项目中Redis的使用示例详解

《sky-take-out项目中Redis的使用示例详解》SpringCache是Spring的缓存抽象层,通过注解简化缓存管理,支持Redis等提供者,适用于方法结果缓存、更新和删除操作,但无法实现... 目录Spring Cache主要特性核心注解1.@Cacheable2.@CachePut3.@Ca

QT Creator配置Kit的实现示例

《QTCreator配置Kit的实现示例》本文主要介绍了使用Qt5.12.12与VS2022时,因MSVC编译器版本不匹配及WindowsSDK缺失导致配置错误的问题解决,感兴趣的可以了解一下... 目录0、背景:qt5.12.12+vs2022一、症状:二、原因:(可以跳过,直奔后面的解决方法)三、解决方

深入浅出Spring中的@Autowired自动注入的工作原理及实践应用

《深入浅出Spring中的@Autowired自动注入的工作原理及实践应用》在Spring框架的学习旅程中,@Autowired无疑是一个高频出现却又让初学者头疼的注解,它看似简单,却蕴含着Sprin... 目录深入浅出Spring中的@Autowired:自动注入的奥秘什么是依赖注入?@Autowired

Spring 依赖注入与循环依赖总结

《Spring依赖注入与循环依赖总结》这篇文章给大家介绍Spring依赖注入与循环依赖总结篇,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. Spring 三级缓存解决循环依赖1. 创建UserService原始对象2. 将原始对象包装成工

Java中如何正确的停掉线程

《Java中如何正确的停掉线程》Java通过interrupt()通知线程停止而非强制,确保线程自主处理中断,避免数据损坏,线程池的shutdown()等待任务完成,shutdownNow()强制中断... 目录为什么不强制停止为什么 Java 不提供强制停止线程的能力呢?如何用interrupt停止线程s

MySQL中On duplicate key update的实现示例

《MySQL中Onduplicatekeyupdate的实现示例》ONDUPLICATEKEYUPDATE是一种MySQL的语法,它在插入新数据时,如果遇到唯一键冲突,则会执行更新操作,而不是抛... 目录1/ ON DUPLICATE KEY UPDATE的简介2/ ON DUPLICATE KEY UP

Python中Json和其他类型相互转换的实现示例

《Python中Json和其他类型相互转换的实现示例》本文介绍了在Python中使用json模块实现json数据与dict、object之间的高效转换,包括loads(),load(),dumps()... 项目中经常会用到json格式转为object对象、dict字典格式等。在此做个记录,方便后续用到该方