Abstract
The code implementation of the Controller and Service layers and the login authorization process demonstration follow.
Login registration function realization
Add UmsAdminController class
Realize the interface of background user login, registration and access
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 = "Background User Management")
@RequestMapping("/admin")
public class UmsAdminController {
@Autowired
private UmsAdminService adminService;
@Value("${jwt.tokenHeader}")
private String tokenHeader;
@Value("${jwt.tokenHead}")
private String tokenHead;
@ApiOperation(value = "User Registration")
@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 = "Return token after login")
@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("Wrong username or password");
}
Map<String, String> tokenMap = new HashMap<>();
tokenMap.put("token", token);
tokenMap.put("tokenHead", tokenHead);
return CommonResult.success(tokenMap);
}
@ApiOperation("Get all user permissions (including +- permissions)")
@RequestMapping(value = "/permission/{adminId}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<UmsPermission>> getPermissionList(@PathVariable Long adminId) {
List<UmsPermission> permissionList = adminService.getPermissionList(adminId);
returnCommonResult.success(permissionList); }}Copy the code
Add the UmsAdminService interface
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 {
/** * Obtain the background administrator */ based on the user name
UmsAdmin getAdminByUsername(String username);
/** * Register function */
UmsAdmin register(UmsAdmin umsAdminParam);
/** * Login function *@paramUsername username *@param"Password," password *@returnGenerated token */ of JWT
String login(String username, String password);
/** * Obtain all user rights (including role rights and +- rights) */
List<UmsPermission> getPermissionList(Long adminId);
}
Copy the code
Add UmsAdminServiceImpl class
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 implementation * 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);
// Check whether there is a user with the same user name
UmsAdminExample example = new UmsAdminExample();
example.createCriteria().andUsernameEqualTo(umsAdmin.getUsername());
List<UmsAdmin> umsAdminList = adminMapper.selectByExample(example);
if (umsAdminList.size() > 0) {
return null;
}
// Encrypt the password
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("Incorrect password");
}
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
token = jwtTokenUtil.generateToken(userDetails);
} catch (AuthenticationException e) {
LOGGER.warn("Login exception :{}", e.getMessage());
}
return token;
}
@Override
public List<UmsPermission> getPermissionList(Long adminId) {
returnadminRoleRelationDao.getPermissionList(adminId); }}Copy the code
Modify Swagger configuration
Modify the configuration to invoke the Authorization header of the interface, so that you can access the interface that needs to be logged in.
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 file configuration */
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi(a){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// Generate API documentation for the controller under the current package
.apis(RequestHandlerSelectors.basePackage("com.macro.mall.tiny.controller"))
.paths(PathSelectors.any())
.build()
// Add login authentication
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private ApiInfo apiInfo(a) {
return new ApiInfoBuilder()
.title("SwaggerUI demonstration")
.description("mall-tiny")
.contact("macro")
.version("1.0")
.build();
}
private List<ApiKey> securitySchemes(a) {
// Set the request header information
List<ApiKey> result = new ArrayList<>();
ApiKey apiKey = new ApiKey("Authorization"."Authorization"."header");
result.add(apiKey);
return result;
}
private List<SecurityContext> securityContexts(a) {
// Set the path for login authentication
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(a) {
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));
returnresult; }}Copy the code
Add access to methods in the PmsBrandController interface
- Add PMS :brand:read permission to the query interface
- Add the PMS :brand:update permission to the interface
- Add the PMS :brand:delete permission to the delete interface
- Add PMS :brand:create permission to the add interface
Example:
@PreAuthorize("hasAuthority('pms:brand:read')")
public CommonResult<List<PmsBrand>> getBrandList() {
return CommonResult.success(brandService.listAllBrand());
}
Copy the code
Demonstration of authentication and authorization process
Run the project and access the API
Swagger API address: http://localhost:8080/swagger-ui.html
Accessing the interface before logging in
Access the interface after login
- Login operation: Log in to account test 123456
- Click the Authorize button and enter the token information obtained in the login interface in the dialog box
- After login, access the interface for obtaining permission list
Access the interface that requires permissions
Because the test account has no permissions set, it cannot access the interface to get the brand list with PMS :brand:read permissions.
Use another authorized account to log in
Use admin 123456 to log in and access, click Authorize button to open the pop-up box, and click logout to logout and re-enter the new token.
Project source code address
Github.com/macrozheng/…
The public,
Mall project full set of learning tutorials serialized, attention to the public number the first time access.