失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > GitHub开源项目学习 电商系统Mall (五) mall整合SpringSecurity和JWT实现认证和授权(二)

GitHub开源项目学习 电商系统Mall (五) mall整合SpringSecurity和JWT实现认证和授权(二)

时间:2023-04-20 21:39:29

相关推荐

GitHub开源项目学习 电商系统Mall (五) mall整合SpringSecurity和JWT实现认证和授权(二)

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

/macrozheng/mall

登录注册功能实现

UmsAdminController类

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

/*** 后台用户管理*/@Controller@Api(tags = "UmsAdminController", description = "后台用户管理")@RequestMapping("/admin")public class UmsAdminController {@Autowiredprivate UmsAdminService adminService;@Value("${jwt.tokenHeader}")private String tokenHeader;@Value("${jwt.tokenHead}")private String tokenHead;@ApiOperation(value = "用户注册")@RequestMapping(value = "/register", method = RequestMethod.POST)@ResponseBodypublic 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)@ResponseBodypublic 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)@ResponseBodypublic CommonResult<List<UmsPermission>> getPermissionList(@PathVariable Long adminId) {List<UmsPermission> permissionList = adminService.getPermissionList(adminId);return CommonResult.success(permissionList);}}

添加UmsAdminService接口

/*** 后台管理员Service*/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类

/*** UmsAdminService实现类*/@Servicepublic class UmsAdminServiceImpl implements UmsAdminService {private static final Logger LOGGER = LoggerFactory.getLogger(UmsAdminServiceImpl.class);@Autowiredprivate UserDetailsService userDetailsService;@Autowiredprivate JwtTokenUtil jwtTokenUtil;@Autowiredprivate PasswordEncoder passwordEncoder;@Value("${jwt.tokenHead}")private String tokenHead;@Autowiredprivate UmsAdminMapper adminMapper;@Autowiredprivate UmsAdminRoleRelationDao adminRoleRelationDao;@Overridepublic 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;}@Overridepublic 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;}@Overridepublic 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;}@Overridepublic List<UmsPermission> getPermissionList(Long adminId) {return adminRoleRelationDao.getPermissionList(adminId);}}

修改Swagger的配置

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

private List<ApiKey> securitySchemes() {//设置请求头信息List<ApiKey> result = new ArrayList<>();ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");result.add(apiKey);return result;}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接口中的方法添加访问权限

给查询接口添加pmsread权限给修改接口添加pmsupdate权限给删除接口添加pmsdelete权限给添加接口添加pmscreate权限

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

如果觉得《GitHub开源项目学习 电商系统Mall (五) mall整合SpringSecurity和JWT实现认证和授权(二)》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。