mall整合SpringSecurity及JWT認(rèn)證授權(quán)實(shí)戰(zhàn)下
摘要
接上一篇,controller和service層的代碼實(shí)現(xiàn)及登錄授權(quán)流程演示。
登錄注冊功能實(shí)現(xiàn)
添加UmsAdminController類
實(shí)現(xiàn)了后臺用戶登錄、注冊及獲取權(quán)限的接口
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("獲取用戶所有權(quán)限(包括+-權(quán)限)")
@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 {
/**
* 根據(jù)用戶名獲取后臺管理員
*/
UmsAdmin getAdminByUsername(String username);
/**
* 注冊功能
*/
UmsAdmin register(UmsAdmin umsAdminParam);
/**
* 登錄功能
* @param username 用戶名
* @param password 密碼
* @return 生成的JWT的token
*/
String login(String username, String password);
/**
* 獲取用戶所有權(quán)限(包括角色權(quán)限和+-權(quán)限)
*/
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實(shí)現(xiàn)類
* 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;
}
//將密碼進(jìn)行加密操作
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的配置
通過修改配置實(shí)現(xiàn)調(diào)用接口自帶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()
//為當(dāng)前包下controller生成API文檔
.apis(RequestHandlerSelectors.basePackage("com.macro.mall.tiny.controller"))
.paths(PathSelectors.any())
.build()
//添加登錄認(rèn)證
.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() {
//設(shè)置請求頭信息
List<ApiKey> result = new ArrayList<>();
ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");
result.add(apiKey);
return result;
}
private List<SecurityContext> securityContexts() {
//設(shè)置需要登錄認(rèn)證的路徑
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接口中的方法添加訪問權(quán)限
- 給查詢接口添加pms:brand:read權(quán)限
- 給修改接口添加pms:brand:update權(quán)限
- 給刪除接口添加pms:brand:delete權(quán)限
- 給添加接口添加pms:brand:create權(quán)限
例子:
@PreAuthorize("hasAuthority('pms:brand:read')")
public CommonResult<List<PmsBrand>> getBrandList() {
return CommonResult.success(brandService.listAllBrand());
}
認(rèn)證與授權(quán)流程演示
運(yùn)行項目,訪問API
Swagger api地址:http://localhost:8080/swagger-ui.html

未登錄前訪問接口


登錄后訪問接口
進(jìn)行登錄操作:登錄帳號test 123456


點(diǎn)擊Authorize按鈕,在彈框中輸入登錄接口中獲取到的token信息


登錄后訪問獲取權(quán)限列表接口,發(fā)現(xiàn)已經(jīng)可以正常訪問


訪問需要權(quán)限的接口
由于test帳號并沒有設(shè)置任何權(quán)限,所以他無法訪問具有pms:brand:read權(quán)限的獲取品牌列表接口。


改用其他有權(quán)限的帳號登錄
改用admin 123456登錄后訪問,點(diǎn)擊Authorize按鈕打開彈框,點(diǎn)擊logout登出后再重新輸入新token。


項目源碼地址github.com/macrozheng/…
mall持續(xù)更新地址:https://github.com/macrozheng/mall
以上就是mall整合SpringSecurity及JWT認(rèn)證授權(quán)實(shí)戰(zhàn)下的詳細(xì)內(nèi)容,更多關(guān)于mall整合SpringSecurity JWT的資料請關(guān)注腳本之家其它相關(guān)文章!
- SpringSecurity+Redis+Jwt實(shí)現(xiàn)用戶認(rèn)證授權(quán)
- springboot+springsecurity+mybatis+JWT+Redis?實(shí)現(xiàn)前后端離實(shí)戰(zhàn)教程
- SpringBoot3.0+SpringSecurity6.0+JWT的實(shí)現(xiàn)
- SpringSecurity整合JWT的使用示例
- SpringBoot整合SpringSecurity和JWT和Redis實(shí)現(xiàn)統(tǒng)一鑒權(quán)認(rèn)證
- SpringBoot+SpringSecurity+jwt實(shí)現(xiàn)驗證
- SpringSecurity詳解整合JWT實(shí)現(xiàn)全過程
- mall整合SpringSecurity及JWT實(shí)現(xiàn)認(rèn)證授權(quán)實(shí)戰(zhàn)
- Java SpringSecurity+JWT實(shí)現(xiàn)登錄認(rèn)證
- springSecurity+jwt使用小結(jié)
相關(guān)文章
SpringBoot EasyPoi動態(tài)導(dǎo)入導(dǎo)出的兩種方式實(shí)現(xiàn)方法詳解
項目里使用的是EasyPoi來處理導(dǎo)入導(dǎo)出功能的。近日因業(yè)務(wù)需求調(diào)整,一些導(dǎo)出功能的導(dǎo)出列需要根據(jù)不同的條件動態(tài)導(dǎo)出2022-09-09
使用ByteArrayOutputStream寫入字符串方式
這篇文章主要介紹了使用ByteArrayOutputStream寫入字符串方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
Mabatis錯誤提示Parameter index out of range的處理方法
這篇文章主要介紹了Mabatis錯誤提示Parameter index out of range 的處理方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08
Java文件操作工具類fileUtil實(shí)例【文件增刪改,復(fù)制等】
這篇文章主要介紹了Java文件操作工具類fileUtil,結(jié)合實(shí)例形式分析了java針對文件進(jìn)行讀取、增加、刪除、修改、復(fù)制等操作的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-10-10
基于SpringBoot實(shí)現(xiàn)自定義插件的流程詳解
在SpringBoot中,插件是一種擴(kuò)展機(jī)制,它可以幫助我們在應(yīng)用程序中快速地添加一些額外的功能,在本文中,我們將介紹如何使用 SpringBoot實(shí)現(xiàn)自定義插件,需要的朋友可以參考下2023-06-06
基于SpringBoot實(shí)現(xiàn)圖片上傳與顯示
這篇文章主要為大家詳細(xì)介紹了基于SpringBoot實(shí)現(xiàn)圖片上傳與顯示,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-08-08
Java的Struts框架中登陸功能的實(shí)現(xiàn)和表單處理器的使用
這篇文章主要介紹了Java的Struts框架中登陸功能的實(shí)現(xiàn)和表單處理器的使用,Struts框架是Java的SSH三大web開發(fā)框架之一,需要的朋友可以參考下2015-12-12
springdata jpa使用Example快速實(shí)現(xiàn)動態(tài)查詢功能
這篇文章主要介紹了springdata jpa使用Example快速實(shí)現(xiàn)動態(tài)查詢功能,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11

