mall整合SpringSecurity和JWT实现认证和授权(二)

2023-11-09 21:10

本文主要是介绍mall整合SpringSecurity和JWT实现认证和授权(二),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

接上一篇,controller和service层的代码实现及登录授权流程演示。

登录注册功能实现

添加UmsAdminController类

实现了后台用户登录、注册及获取权限的接口

package com.macro.mall.tiny.controller;	
import com.macro.mall.tiny.common.api.CommonResult;	
import com.macro.mall.tiny.dto.UmsAdminLoginParam;	
import com.macro.mall.tiny.mbg.model.UmsAdmin;	
import com.macro.mall.tiny.mbg.model.UmsPermission;	
import com.macro.mall.tiny.service.UmsAdminService;	
import io.swagger.annotations.Api;	
import io.swagger.annotations.ApiOperation;	
import org.springframework.beans.factory.annotation.Autowired;	
import org.springframework.beans.factory.annotation.Value;	
import org.springframework.stereotype.Controller;	
import org.springframework.validation.BindingResult;	
import org.springframework.web.bind.annotation.*;	
import java.util.HashMap;	
import java.util.List;	
import java.util.Map;	
/**	* 后台用户管理	* Created by macro on 2018/4/26.	*/	
@Controller	
@Api(tags = "UmsAdminController", description = "后台用户管理")	
@RequestMapping("/admin")	
public class UmsAdminController {	@Autowired	private UmsAdminService adminService;	@Value("${jwt.tokenHeader}")	private String tokenHeader;	@Value("${jwt.tokenHead}")	private String tokenHead;	@ApiOperation(value = "用户注册")	@RequestMapping(value = "/register", method = RequestMethod.POST)	@ResponseBody	public CommonResult<UmsAdmin> register(@RequestBody UmsAdmin umsAdminParam, BindingResult result) {	UmsAdmin umsAdmin = adminService.register(umsAdminParam);	if (umsAdmin == null) {	CommonResult.failed();	}	return CommonResult.success(umsAdmin);	}	@ApiOperation(value = "登录以后返回token")	@RequestMapping(value = "/login", method = RequestMethod.POST)	@ResponseBody	public CommonResult login(@RequestBody UmsAdminLoginParam umsAdminLoginParam, BindingResult result) {	String token = adminService.login(umsAdminLoginParam.getUsername(), umsAdminLoginParam.getPassword());	if (token == null) {	return CommonResult.validateFailed("用户名或密码错误");	}	Map<String, String> tokenMap = new HashMap<>();	tokenMap.put("token", token);	tokenMap.put("tokenHead", tokenHead);	return CommonResult.success(tokenMap);	}	@ApiOperation("获取用户所有权限(包括+-权限)")	@RequestMapping(value = "/permission/{adminId}", method = RequestMethod.GET)	@ResponseBody	public CommonResult<List<UmsPermission>> getPermissionList(@PathVariable Long adminId) {	List<UmsPermission> permissionList = adminService.getPermissionList(adminId);	return CommonResult.success(permissionList);	}	
}

添加UmsAdminService接口

package com.macro.mall.tiny.service;	
import com.macro.mall.tiny.mbg.model.UmsAdmin;	
import com.macro.mall.tiny.mbg.model.UmsPermission;	
import java.util.List;	
/**	* 后台管理员Service	* Created by macro on 2018/4/26.	*/	
public interface UmsAdminService {	/**	* 根据用户名获取后台管理员	*/	UmsAdmin getAdminByUsername(String username);	/**	* 注册功能	*/	UmsAdmin register(UmsAdmin umsAdminParam);	/**	* 登录功能	* @param username 用户名	* @param password 密码	* @return 生成的JWT的token	*/	String login(String username, String password);	/**	* 获取用户所有权限(包括角色权限和+-权限)	*/	List<UmsPermission> getPermissionList(Long adminId);	
}

添加UmsAdminServiceImpl类

package com.macro.mall.tiny.service.impl;	
import com.macro.mall.tiny.common.utils.JwtTokenUtil;	
import com.macro.mall.tiny.dao.UmsAdminRoleRelationDao;	
import com.macro.mall.tiny.dto.UmsAdminLoginParam;	
import com.macro.mall.tiny.mbg.mapper.UmsAdminMapper;	
import com.macro.mall.tiny.mbg.model.UmsAdmin;	
import com.macro.mall.tiny.mbg.model.UmsAdminExample;	
import com.macro.mall.tiny.mbg.model.UmsPermission;	
import com.macro.mall.tiny.service.UmsAdminService;	
import org.slf4j.Logger;	
import org.slf4j.LoggerFactory;	
import org.springframework.beans.BeanUtils;	
import org.springframework.beans.factory.annotation.Autowired;	
import org.springframework.beans.factory.annotation.Value;	
import org.springframework.security.authentication.AuthenticationManager;	
import org.springframework.security.authentication.BadCredentialsException;	
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;	
import org.springframework.security.core.AuthenticationException;	
import org.springframework.security.core.context.SecurityContextHolder;	
import org.springframework.security.core.userdetails.UserDetails;	
import org.springframework.security.core.userdetails.UserDetailsService;	
import org.springframework.security.crypto.password.PasswordEncoder;	
import org.springframework.stereotype.Service;	
import java.util.Date;	
import java.util.List;	
/**	* UmsAdminService实现类	* Created by macro on 2018/4/26.	*/	
@Service	
public class UmsAdminServiceImpl implements UmsAdminService {	private static final Logger LOGGER = LoggerFactory.getLogger(UmsAdminServiceImpl.class);	@Autowired	private UserDetailsService userDetailsService;	@Autowired	private JwtTokenUtil jwtTokenUtil;	@Autowired	private PasswordEncoder passwordEncoder;	@Value("${jwt.tokenHead}")	private String tokenHead;	@Autowired	private UmsAdminMapper adminMapper;	@Autowired	private UmsAdminRoleRelationDao adminRoleRelationDao;	@Override	public UmsAdmin getAdminByUsername(String username) {	UmsAdminExample example = new UmsAdminExample();	example.createCriteria().andUsernameEqualTo(username);	List<UmsAdmin> adminList = adminMapper.selectByExample(example);	if (adminList != null && adminList.size() > 0) {	return adminList.get(0);	}	return null;	}	@Override	public UmsAdmin register(UmsAdmin umsAdminParam) {	UmsAdmin umsAdmin = new UmsAdmin();	BeanUtils.copyProperties(umsAdminParam, umsAdmin);	umsAdmin.setCreateTime(new Date());	umsAdmin.setStatus(1);	//查询是否有相同用户名的用户	UmsAdminExample example = new UmsAdminExample();	example.createCriteria().andUsernameEqualTo(umsAdmin.getUsername());	List<UmsAdmin> umsAdminList = adminMapper.selectByExample(example);	if (umsAdminList.size() > 0) {	return null;	}	//将密码进行加密操作	String encodePassword = passwordEncoder.encode(umsAdmin.getPassword());	umsAdmin.setPassword(encodePassword);	adminMapper.insert(umsAdmin);	return umsAdmin;	}	@Override	public String login(String username, String password) {	String token = null;	try {	UserDetails userDetails = userDetailsService.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 List<UmsPermission> getPermissionList(Long adminId) {	return adminRoleRelationDao.getPermissionList(adminId);	}	
}

修改Swagger的配置

通过修改配置实现调用接口自带Authorization头,这样就可以访问需要登录的接口了。

package com.macro.mall.tiny.config;	
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.ApiInfo;	
import springfox.documentation.service.ApiKey;	
import springfox.documentation.service.AuthorizationScope;	
import springfox.documentation.service.SecurityReference;	
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;	
/**	* Swagger2API文档的配置	*/	
@Configuration	
@EnableSwagger2	
public class Swagger2Config {	@Bean	public Docket createRestApi(){	return new Docket(DocumentationType.SWAGGER_2)	.apiInfo(apiInfo())	.select()	//为当前包下controller生成API文档	.apis(RequestHandlerSelectors.basePackage("com.macro.mall.tiny.controller"))	.paths(PathSelectors.any())	.build()	//添加登录认证	.securitySchemes(securitySchemes())	.securityContexts(securityContexts());	}	private ApiInfo apiInfo() {	return new ApiInfoBuilder()	.title("SwaggerUI演示")	.description("mall-tiny")	.contact("macro")	.version("1.0")	.build();	}	private List<ApiKey> securitySchemes() {	//设置请求头信息	List<ApiKey> result = new ArrayList<>();	ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");	result.add(apiKey);	return result;	}	private List<SecurityContext> securityContexts() {	//设置需要登录认证的路径	List<SecurityContext> result = new ArrayList<>();	result.add(getContextByPath("/brand/.*"));	return result;	}	private SecurityContext getContextByPath(String pathRegex){	return SecurityContext.builder()	.securityReferences(defaultAuth())	.forPaths(PathSelectors.regex(pathRegex))	.build();	}	private List<SecurityReference> defaultAuth() {	List<SecurityReference> result = new ArrayList<>();	AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");	AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];	authorizationScopes[0] = authorizationScope;	result.add(new SecurityReference("Authorization", authorizationScopes));	return result;	}	
}

给PmsBrandController接口中的方法添加访问权限

  • 给查询接口添加pms:brand:read权限

  • 给修改接口添加pms:brand:update权限

  • 给删除接口添加pms:brand:delete权限

  • 给添加接口添加pms:brand:create权限

例子:

@PreAuthorize("hasAuthority('pms:brand:read')")	
public CommonResult<List<PmsBrand>> getBrandList() {	return CommonResult.success(brandService.listAllBrand());	
}

认证与授权流程演示

运行项目,访问API

Swagger api地址:http://localhost:8080/swagger-ui.html

640?wx_fmt=png

未登录前访问接口

640?wx_fmt=png

640?wx_fmt=png

登录后访问接口

  • 进行登录操作:登录帐号test 123456

640?wx_fmt=png

640?wx_fmt=png

  • 点击Authorize按钮,在弹框中输入登录接口中获取到的token信息

640?wx_fmt=png

640?wx_fmt=png

  • 登录后访问获取权限列表接口,发现已经可以正常访问

640?wx_fmt=png

640?wx_fmt=png

访问需要权限的接口

由于test帐号并没有设置任何权限,所以他无法访问具有pms:brand:read权限的获取品牌列表接口。

640?wx_fmt=png

640?wx_fmt=png

改用其他有权限的帐号登录

改用admin 123456登录后访问,点击Authorize按钮打开弹框,点击logout登出后再重新输入新token。

640?wx_fmt=png

640?wx_fmt=png

项目源码地址

https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-04

推荐阅读

  • mall架构及功能概览

  • mall学习所需知识点(推荐资料)

  • mall整合SpringBoot+MyBatis搭建基本骨架

  • mall整合Swagger-UI实现在线API文档

  • mall整合Redis实现缓存功能

  • mall整合SpringSecurity和JWT实现认证和授权(一)


这篇关于mall整合SpringSecurity和JWT实现认证和授权(二)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Java NoClassDefFoundError运行时错误分析解决

《JavaNoClassDefFoundError运行时错误分析解决》在Java开发中,NoClassDefFoundError是一种常见的运行时错误,它通常表明Java虚拟机在尝试加载一个类时未能... 目录前言一、问题分析二、报错原因三、解决思路检查类路径配置检查依赖库检查类文件调试类加载器问题四、常见

Java注解之超越Javadoc的元数据利器详解

《Java注解之超越Javadoc的元数据利器详解》本文将深入探讨Java注解的定义、类型、内置注解、自定义注解、保留策略、实际应用场景及最佳实践,无论是初学者还是资深开发者,都能通过本文了解如何利用... 目录什么是注解?注解的类型内置注编程解自定义注解注解的保留策略实际用例最佳实践总结在 Java 编程

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Java 实用工具类Spring 的 AnnotationUtils详解

《Java实用工具类Spring的AnnotationUtils详解》Spring框架提供了一个强大的注解工具类org.springframework.core.annotation.Annot... 目录前言一、AnnotationUtils 的常用方法二、常见应用场景三、与 JDK 原生注解 API 的

Java controller接口出入参时间序列化转换操作方法(两种)

《Javacontroller接口出入参时间序列化转换操作方法(两种)》:本文主要介绍Javacontroller接口出入参时间序列化转换操作方法,本文给大家列举两种简单方法,感兴趣的朋友一起看... 目录方式一、使用注解方式二、统一配置场景:在controller编写的接口,在前后端交互过程中一般都会涉及

Java中的StringBuilder之如何高效构建字符串

《Java中的StringBuilder之如何高效构建字符串》本文将深入浅出地介绍StringBuilder的使用方法、性能优势以及相关字符串处理技术,结合代码示例帮助读者更好地理解和应用,希望对大家... 目录关键点什么是 StringBuilder?为什么需要 StringBuilder?如何使用 St

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

Java并发编程之如何优雅关闭钩子Shutdown Hook

《Java并发编程之如何优雅关闭钩子ShutdownHook》这篇文章主要为大家详细介绍了Java如何实现优雅关闭钩子ShutdownHook,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 目录关闭钩子简介关闭钩子应用场景数据库连接实战演示使用关闭钩子的注意事项开源框架中的关闭钩子机制1.

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句