提交 0dc39aac 编写于 作者: M ManongJu

重构网关进行权限校验

上级 70ce26cc
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.microservice.skeleton.common</groupId>
<artifactId>mss-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mss-common</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>com.microservice.skeleton</groupId>
<artifactId>Micro-Service-Skeleton-Parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>
package com.microservice.skeleton.common.vo;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import java.util.Date;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Mr.Yangxiufeng
* Date: 2018-06-13
* Time: 10:39
*/
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MenuVo {
private String id;
private String code;
private String pCode;
private String pId;
private String name;
private String url;
private Integer isMenu;
private Integer level;
private Integer sort;
private Integer status;
private String icon;
private Date createTime;
private Date updateTime;
}
package com.microservice.skeleton.common.vo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Mr.Yangxiufeng
* Date: 2018-05-16
* Time: 11:04
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result<T> implements Serializable {
private static final String CODE = "code";
private static final String MSG = "msg";
private static final long serialVersionUID = 2633283546876721434L;
private Integer code=200;
private String msg="操作成功";
private String description;
private T data;
private HashMap<String,Object> exend;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public Result setData(T data) {
this.data = data;
return this;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@JsonIgnore
public HashMap<String, Object> getExend() {
return exend;
}
public void setExend(HashMap<String, Object> exend) {
this.exend = exend;
}
public Result() {
exend = new HashMap<>();
}
public static Result failure(int code, String msg) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
public static Result ok(String msg) {
Result result = new Result();
result.put("msg", msg);
return result;
}
public static Result ok(Map<String, Object> map) {
Result result = new Result();
result.exend.putAll(map);
return result;
}
public static Result ok() {
return new Result();
}
public Result put(String key, Object value) {
exend.put(key, value);
return this;
}
}
package com.microservice.skeleton.common.vo;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* Created with IntelliJ IDEA.
......@@ -12,11 +14,20 @@ import java.io.Serializable;
* Time: 21:03
*/
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RoleVo implements Serializable {
private static final long serialVersionUID = 2179037393108205286L;
private Integer roleId;
private Integer id;
private String name;
private String value;
private String tips;
private Date createTime;
private Date updateTime;
private Integer status;
}
package com.microservice.skeleton.common.vo;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Mr.Yangxiufeng
* Date: 2018-05-10
* Time: 21:00
*/
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserVo implements Serializable {
private static final long serialVersionUID = 3881610071550902762L;
private Integer id;
private String avatar;
private String username;
private String password;
private String salt;
private String name;
private Date birthday;
private Integer sex;
private String email;
private String phone;
private Integer status;
private Date createTime;
private Date updateTime;
}
......@@ -2,6 +2,7 @@ package com.microservice.skeleton.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
......
package com.microservice.skeleton.gateway.config;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler;
/**
* Created by Mr.Yangxiufeng on 2017/12/29.
......@@ -12,13 +17,46 @@ import org.springframework.security.oauth2.config.annotation.web.configuration.E
* ProjectName:Mirco-Service-Skeleton
*/
@Configuration
//@EnableOAuth2Sso
//@EnableResourceServer
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@EnableResourceServer
public class SecurityConfig extends ResourceServerConfigurerAdapter {
@Autowired
private OAuth2WebSecurityExpressionHandler expressionHandler;
private static final String[] AUTH_WHITELIST = {
"/**/v2/api-docs",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui.html",
"swagger-resources/configuration/ui",
"/doc.html",
"/webjars/**"
};
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/v2/api-docs","/uaa/**").permitAll();
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
.authorizeRequests();
for (String au:AUTH_WHITELIST
) {
http.authorizeRequests().antMatchers(au).permitAll();
}
http.authorizeRequests().anyRequest().authenticated();
registry.anyRequest()
.access("@permissionService.hasPermission(request,authentication)");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().mvcMatchers("/v2/api-docs ").permitAll();
http.csrf().disable();
public void configure(ResourceServerSecurityConfigurer resources) {
resources.expressionHandler(expressionHandler);
}
@Bean
public OAuth2WebSecurityExpressionHandler oAuth2WebSecurityExpressionHandler(ApplicationContext applicationContext) {
OAuth2WebSecurityExpressionHandler expressionHandler = new OAuth2WebSecurityExpressionHandler();
expressionHandler.setApplicationContext(applicationContext);
return expressionHandler;
}
}
package com.microservice.skeleton.gateway.service;
import org.springframework.security.core.Authentication;
import javax.servlet.http.HttpServletRequest;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Mr.Yangxiufeng
* Date: 2018-05-14
* Time: 16:01
*/
public interface PermissionService {
boolean hasPermission(HttpServletRequest request, Authentication authentication);
}
package com.microservice.skeleton.gateway.service.impl;
import com.microservice.skeleton.gateway.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Mr.Yangxiufeng
* Date: 2018-05-14
* Time: 16:01
*/
@Service("permissionService")
@Slf4j
public class PermissionServiceImpl implements PermissionService {
/**
* 可以做URLs匹配,规则如下
*
* ?匹配一个字符
* *匹配0个或多个字符
* **匹配0个或多个目录
* 用例如下
* <p>https://www.cnblogs.com/zhangxiaoguang/p/5855113.html</p>
*/
private AntPathMatcher antPathMatcher = new AntPathMatcher();
@Override
public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
Object principal = authentication.getPrincipal();
String requestUrl = request.getRequestURI();
log.info("requestUrl:{}",requestUrl);
List<SimpleGrantedAuthority> grantedAuthorityList = (List<SimpleGrantedAuthority>) authentication.getAuthorities();
boolean hasPermission = false;
if (principal != null){
if (CollectionUtils.isEmpty(grantedAuthorityList)){
return hasPermission;
}
for (SimpleGrantedAuthority authority:grantedAuthorityList
) {
if (antPathMatcher.match(authority.getAuthority(),requestUrl)){
hasPermission = true;
break;
}
}
}
return hasPermission;
}
}
......@@ -42,21 +42,25 @@ zuul:
strip-prefix: true
sensitiveHeaders:
serviceId: auth2.0-center
#security:
# basic:
# enabled: false
# oauth2:
security:
basic:
enabled: false
oauth2:
# sso:
# loginPath: /login
# client:
# ##网关的地址
# access-token-uri: http://localhost:9030/uaa/oauth/token
# user-authorization-uri: http://localhost:9030/uaa/oauth/authorize
# resource:
# user-info-uri: http://localhost:9060/user
# prefer-token-info: false
# client-id: webApp
# client-secret: webApp
resource:
user-info-uri: http://localhost:9060/user
prefer-token-info: false
#security:
# oauth2:
# resource:
# id: resource
# id: gateway
# user-info-uri: http://localhost:9060/user
# prefer-token-info: false
##############end#####################
......
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
\ No newline at end of file
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.microservice.skeleton.modules</groupId>
<artifactId>Micro-Service-Skeleton-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>microservice.skeleton.upms</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mss-upms</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--注册中心-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>com.microservice.skeleton.common</groupId>
<artifactId>mss-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.babylikebird</groupId>
<artifactId>com.snowflake.id</artifactId>
<version>0.0.1</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>${tk.mybatis.starter.version}</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-generator</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger2.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger2.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<configurationFile>
${basedir}/src/test/resources/generatorConfig.xml
</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!--<version>5.1.29</version>-->
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<!--<version>4.0.0</version>-->
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
package com.microservice.skeleton.upms;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class UpmsApplication {
public static void main(String[] args) {
SpringApplication.run(UpmsApplication.class, args);
}
}
package com.microservice.skeleton.upms.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.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Mr.Yangxiufeng
* Date: 2018-04-18
* Time: 14:52
*/
@EnableSwagger2
@Configuration
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.microservice.skeleton.upms.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("resource文档")
.description("resource接口说明文档")
.termsOfServiceUrl("")
.contact(new Contact("杨秀峰","franky.yang@foxmail.com","franky.yang@foxmail.com"))
.version("1.0")
.build();
}
}
package com.microservice.skeleton.upms.controller;
import com.microservice.skeleton.common.vo.Result;
import com.microservice.skeleton.upms.entity.RcMenu;
import com.microservice.skeleton.upms.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Mr.Yangxiufeng
* Date: 2018-06-13
* Time: 10:28
*/
@Slf4j
@RestController
@RequestMapping("permission")
public class PermissionController {
@Autowired
private PermissionService permissionService;
@GetMapping("getRolePermission/{roleId}")
public Result getRolePermission(@PathVariable("roleId") Integer roleId){
List<RcMenu> menuList = permissionService.getPermissionsByRoleId(roleId);
return Result.ok().setData(menuList);
}
}
package com.microservice.skeleton.upms.controller;
import com.microservice.skeleton.common.vo.Result;
import com.microservice.skeleton.upms.entity.RcRole;
import com.microservice.skeleton.upms.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Mr.Yangxiufeng
* Date: 2018-06-13
* Time: 10:27
*/
@RestController
@RequestMapping("role")
public class RoleController {
@Autowired
private RoleService roleService;
@GetMapping("getRoleByUserId/{userId}")
public Result getRoleByUserId(@PathVariable("userId") Integer userId){
List<RcRole> roleList = roleService.getRoleByUserId(userId);
return Result.ok().setData(roleList);
}
}
package com.microservice.skeleton.upms.controller;
import com.microservice.skeleton.common.vo.Result;
import com.microservice.skeleton.upms.entity.RcUser;
import com.microservice.skeleton.upms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Mr.Yangxiufeng
* Date: 2018-06-13
* Time: 10:27
*/
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("findByUsername/{username}")
public Result findByUsername(@PathVariable("username") String username){
RcUser user = userService.findByUsername(username);
if (user == null){
return Result.failure(100,"用户不存在");
}
return Result.ok().setData(user);
}
}
package com.microservice.skeleton.auth.entity;
package com.microservice.skeleton.upms.entity;
import javax.persistence.*;
import java.util.Date;
import javax.persistence.*;
/**
* Created by Mr.Yangxiufeng on 2017/12/27.
* Time:10:34
* ProjectName:Mirco-Service-Skeleton
*/
@Entity
@Table(name = "rc_menu")
public class RcMenuEntity {
public class RcMenu {
@Id
@GeneratedValue(generator = "JDBC")
private String id;
/**
* 菜单编码
*/
private String code;
/**
* 菜单父编码
*/
@Column(name = "p_code")
private String pCode;
/**
* 父菜单ID
*/
@Column(name = "p_id")
private String pId;
/**
* 名称
*/
private String name;
/**
* 请求地址
*/
private String url;
/**
* 是否是菜单
*/
@Column(name = "is_menu")
private Integer isMenu;
/**
* 菜单层级
*/
private Integer level;
/**
* 菜单排序
*/
private Integer sort;
private Integer status;
private String icon;
@Column(name = "create_time")
private Date createTime;
@Column(name = "update_time")
private Date updateTime;
@Id
@Column(name = "id")
/**
* @return id
*/
public String getId() {
return id;
}
/**
* @param id
*/
public void setId(String id) {
this.id = id;
}
@Basic
@Column(name = "code")
/**
* 获取菜单编码
*
* @return code - 菜单编码
*/
public String getCode() {
return code;
}
/**
* 设置菜单编码
*
* @param code 菜单编码
*/
public void setCode(String code) {
this.code = code;
}
@Basic
@Column(name = "p_code")
/**
* 获取菜单父编码
*
* @return p_code - 菜单父编码
*/
public String getpCode() {
return pCode;
}
/**
* 设置菜单父编码
*
* @param pCode 菜单父编码
*/
public void setpCode(String pCode) {
this.pCode = pCode;
}
@Basic
@Column(name = "p_id")
/**
* 获取父菜单ID
*
* @return p_id - 父菜单ID
*/
public String getpId() {
return pId;
}
/**
* 设置父菜单ID
*
* @param pId 父菜单ID
*/
public void setpId(String pId) {
this.pId = pId;
}
@Basic
@Column(name = "name")
/**
* 获取名称
*
* @return name - 名称
*/
public String getName() {
return name;
}
/**
* 设置名称
*
* @param name 名称
*/
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "url")
/**
* 获取请求地址
*
* @return url - 请求地址
*/
public String getUrl() {
return url;
}
/**
* 设置请求地址
*
* @param url 请求地址
*/
public void setUrl(String url) {
this.url = url;
}
@Basic
@Column(name = "is_menu")
/**
* 获取是否是菜单
*
* @return is_menu - 是否是菜单
*/
public Integer getIsMenu() {
return isMenu;
}
/**
* 设置是否是菜单
*
* @param isMenu 是否是菜单
*/
public void setIsMenu(Integer isMenu) {
this.isMenu = isMenu;
}
@Basic
@Column(name = "level")
/**
* 获取菜单层级
*
* @return level - 菜单层级
*/
public Integer getLevel() {
return level;
}
/**
* 设置菜单层级
*
* @param level 菜单层级
*/
public void setLevel(Integer level) {
this.level = level;
}
@Basic
@Column(name = "sort")
/**
* 获取菜单排序
*
* @return sort - 菜单排序
*/
public Integer getSort() {
return sort;
}
/**
* 设置菜单排序
*
* @param sort 菜单排序
*/
public void setSort(Integer sort) {
this.sort = sort;
}
@Basic
@Column(name = "status")
/**
* @return status
*/
public Integer getStatus() {
return status;
}
/**
* @param status
*/
public void setStatus(Integer status) {
this.status = status;
}
@Basic
@Column(name = "icon")
/**
* @return icon
*/
public String getIcon() {
return icon;
}
/**
* @param icon
*/
public void setIcon(String icon) {
this.icon = icon;
}
@Basic
@Column(name = "create_time")
/**
* @return create_time
*/
public Date getCreateTime() {
return createTime;
}
/**
* @param createTime
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Basic
@Column(name = "update_time")
/**
* @return update_time
*/
public Date getUpdateTime() {
return updateTime;
}
/**
* @param updateTime
*/
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RcMenuEntity that = (RcMenuEntity) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (code != null ? !code.equals(that.code) : that.code != null) return false;
if (pCode != null ? !pCode.equals(that.pCode) : that.pCode != null) return false;
if (pId != null ? !pId.equals(that.pId) : that.pId != null) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (url != null ? !url.equals(that.url) : that.url != null) return false;
if (isMenu != null ? !isMenu.equals(that.isMenu) : that.isMenu != null) return false;
if (level != null ? !level.equals(that.level) : that.level != null) return false;
if (sort != null ? !sort.equals(that.sort) : that.sort != null) return false;
if (status != null ? !status.equals(that.status) : that.status != null) return false;
if (icon != null ? !icon.equals(that.icon) : that.icon != null) return false;
if (createTime != null ? !createTime.equals(that.createTime) : that.createTime != null) return false;
if (updateTime != null ? !updateTime.equals(that.updateTime) : that.updateTime != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (code != null ? code.hashCode() : 0);
result = 31 * result + (pCode != null ? pCode.hashCode() : 0);
result = 31 * result + (pId != null ? pId.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (url != null ? url.hashCode() : 0);
result = 31 * result + (isMenu != null ? isMenu.hashCode() : 0);
result = 31 * result + (level != null ? level.hashCode() : 0);
result = 31 * result + (sort != null ? sort.hashCode() : 0);
result = 31 * result + (status != null ? status.hashCode() : 0);
result = 31 * result + (icon != null ? icon.hashCode() : 0);
result = 31 * result + (createTime != null ? createTime.hashCode() : 0);
result = 31 * result + (updateTime != null ? updateTime.hashCode() : 0);
return result;
}
}
}
\ No newline at end of file
package com.microservice.skeleton.auth.entity;
package com.microservice.skeleton.upms.entity;
import javax.persistence.*;
import java.util.Date;
import javax.persistence.*;
/**
* Created by Mr.Yangxiufeng on 2017/12/27.
* Time:10:34
* ProjectName:Mirco-Service-Skeleton
*/
@Entity
@Table(name = "rc_role")
public class RcRoleEntity {
private int id;
public class RcRole {
@Id
@GeneratedValue(generator = "JDBC")
private Integer id;
private String name;
private String value;
private String tips;
@Column(name = "create_time")
private Date createTime;
@Column(name = "update_time")
private Date updateTime;
private int status;
@Id
@Column(name = "id")
public int getId() {
private Integer status;
/**
* @return id
*/
public Integer getId() {
return id;
}
public void setId(int id) {
/**
* @param id
*/
public void setId(Integer id) {
this.id = id;
}
@Basic
@Column(name = "name")
/**
* @return name
*/
public String getName() {
return name;
}
/**
* @param name
*/
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "value")
/**
* @return value
*/
public String getValue() {
return value;
}
/**
* @param value
*/
public void setValue(String value) {
this.value = value;
}
@Basic
@Column(name = "tips")
/**
* @return tips
*/
public String getTips() {
return tips;
}
/**
* @param tips
*/
public void setTips(String tips) {
this.tips = tips;
}
@Basic
@Column(name = "create_time")
/**
* @return create_time
*/
public Date getCreateTime() {
return createTime;
}
/**
* @param createTime
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Basic
@Column(name = "update_time")
/**
* @return update_time
*/
public Date getUpdateTime() {
return updateTime;
}
/**
* @param updateTime
*/
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Basic
@Column(name = "status")
public int getStatus() {
/**
* @return status
*/
public Integer getStatus() {
return status;
}
public void setStatus(int status) {
/**
* @param status
*/
public void setStatus(Integer status) {
this.status = status;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RcRoleEntity that = (RcRoleEntity) o;
if (id != that.id) return false;
if (status != that.status) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (value != null ? !value.equals(that.value) : that.value != null) return false;
if (tips != null ? !tips.equals(that.tips) : that.tips != null) return false;
if (createTime != null ? !createTime.equals(that.createTime) : that.createTime != null) return false;
if (updateTime != null ? !updateTime.equals(that.updateTime) : that.updateTime != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (value != null ? value.hashCode() : 0);
result = 31 * result + (tips != null ? tips.hashCode() : 0);
result = 31 * result + (createTime != null ? createTime.hashCode() : 0);
result = 31 * result + (updateTime != null ? updateTime.hashCode() : 0);
result = 31 * result + status;
return result;
}
}
}
\ No newline at end of file
package com.microservice.skeleton.auth.entity;
package com.microservice.skeleton.upms.entity;
import javax.persistence.*;
import java.util.Date;
import javax.persistence.*;
/**
* Created by Mr.Yangxiufeng on 2017/12/27.
* Time:10:34
* ProjectName:Mirco-Service-Skeleton
*/
@Entity
@Table(name = "rc_user")
public class RcUserEntity {
private int id;
public class RcUser {
@Id
@GeneratedValue(generator = "JDBC")
private Integer id;
private String avatar;
private String username;
private String password;
private String salt;
private String name;
private Date birthday;
private Integer sex;
private String email;
private String phone;
private Integer status;
@Column(name = "create_time")
private Date createTime;
@Column(name = "update_time")
private Date updateTime;
@Id
@Column(name = "id")
public int getId() {
/**
* @return id
*/
public Integer getId() {
return id;
}
public void setId(int id) {
/**
* @param id
*/
public void setId(Integer id) {
this.id = id;
}
@Basic
@Column(name = "avatar")
/**
* @return avatar
*/
public String getAvatar() {
return avatar;
}
/**
* @param avatar
*/
public void setAvatar(String avatar) {
this.avatar = avatar;
}
@Basic
@Column(name = "username")
/**
* @return username
*/
public String getUsername() {
return username;
}
/**
* @param username
*/
public void setUsername(String username) {
this.username = username;
}
@Basic
@Column(name = "password")
/**
* @return password
*/
public String getPassword() {
return password;
}
/**
* @param password
*/
public void setPassword(String password) {
this.password = password;
}
@Basic
@Column(name = "salt")
/**
* @return salt
*/
public String getSalt() {
return salt;
}
/**
* @param salt
*/
public void setSalt(String salt) {
this.salt = salt;
}
@Basic
@Column(name = "name")
/**
* @return name
*/
public String getName() {
return name;
}
/**
* @param name
*/
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "birthday")
/**
* @return birthday
*/
public Date getBirthday() {
return birthday;
}
/**
* @param birthday
*/
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Basic
@Column(name = "sex")
/**
* @return sex
*/
public Integer getSex() {
return sex;
}
/**
* @param sex
*/
public void setSex(Integer sex) {
this.sex = sex;
}
@Basic
@Column(name = "email")
/**
* @return email
*/
public String getEmail() {
return email;
}
/**
* @param email
*/
public void setEmail(String email) {
this.email = email;
}
@Basic
@Column(name = "phone")
/**
* @return phone
*/
public String getPhone() {
return phone;
}
/**
* @param phone
*/
public void setPhone(String phone) {
this.phone = phone;
}
@Basic
@Column(name = "status")
/**
* @return status
*/
public Integer getStatus() {
return status;
}
/**
* @param status
*/
public void setStatus(Integer status) {
this.status = status;
}
@Basic
@Column(name = "create_time")
/**
* @return create_time
*/
public Date getCreateTime() {
return createTime;
}
/**
* @param createTime
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Basic
@Column(name = "update_time")
/**
* @return update_time
*/
public Date getUpdateTime() {
return updateTime;
}
/**
* @param updateTime
*/
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RcUserEntity that = (RcUserEntity) o;
if (id != that.id) return false;
if (avatar != null ? !avatar.equals(that.avatar) : that.avatar != null) return false;
if (username != null ? !username.equals(that.username) : that.username != null) return false;
if (password != null ? !password.equals(that.password) : that.password != null) return false;
if (salt != null ? !salt.equals(that.salt) : that.salt != null) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (birthday != null ? !birthday.equals(that.birthday) : that.birthday != null) return false;
if (sex != null ? !sex.equals(that.sex) : that.sex != null) return false;
if (email != null ? !email.equals(that.email) : that.email != null) return false;
if (phone != null ? !phone.equals(that.phone) : that.phone != null) return false;
if (status != null ? !status.equals(that.status) : that.status != null) return false;
if (createTime != null ? !createTime.equals(that.createTime) : that.createTime != null) return false;
if (updateTime != null ? !updateTime.equals(that.updateTime) : that.updateTime != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (avatar != null ? avatar.hashCode() : 0);
result = 31 * result + (username != null ? username.hashCode() : 0);
result = 31 * result + (password != null ? password.hashCode() : 0);
result = 31 * result + (salt != null ? salt.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (birthday != null ? birthday.hashCode() : 0);
result = 31 * result + (sex != null ? sex.hashCode() : 0);
result = 31 * result + (email != null ? email.hashCode() : 0);
result = 31 * result + (phone != null ? phone.hashCode() : 0);
result = 31 * result + (status != null ? status.hashCode() : 0);
result = 31 * result + (createTime != null ? createTime.hashCode() : 0);
result = 31 * result + (updateTime != null ? updateTime.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "RcUserEntity{" +
"id=" + id +
", avatar='" + avatar + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", salt='" + salt + '\'' +
", name='" + name + '\'' +
", birthday=" + birthday +
", sex=" + sex +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
", status=" + status +
", createTime=" + createTime +
", updateTime=" + updateTime +
'}';
}
}
}
\ No newline at end of file
package com.microservice.skeleton.upms.mapper;
import com.microservice.skeleton.upms.entity.RcMenu;
import org.apache.ibatis.annotations.Select;
import tk.mybatis.mapper.common.Mapper;
import java.util.List;
@org.apache.ibatis.annotations.Mapper
public interface RcMenuMapper extends Mapper<RcMenu> {
@Select(value = "select menu.* from rc_menu menu,rc_privilege p where menu.id=p.menu_id and p.role_id=#{roleId}")
List<RcMenu> getPermissionsByRoleId(Integer roleId);
}
\ No newline at end of file
package com.microservice.skeleton.upms.mapper;
import com.microservice.skeleton.upms.entity.RcRole;
import org.apache.ibatis.annotations.Select;
import tk.mybatis.mapper.common.Mapper;
import java.util.List;
@org.apache.ibatis.annotations.Mapper
public interface RcRoleMapper extends Mapper<RcRole> {
@Select(value = "select role.* from rc_role role,rc_user_role ur where role.id=ur.role_id and ur.user_id=#{userId}")
List<RcRole> getRoleByUserId(Integer userId);
}
\ No newline at end of file
package com.microservice.skeleton.upms.mapper;
import com.microservice.skeleton.upms.entity.RcUser;
import tk.mybatis.mapper.common.Mapper;
@org.apache.ibatis.annotations.Mapper
public interface RcUserMapper extends Mapper<RcUser> {
}
\ No newline at end of file
package com.microservice.skeleton.upms.service;
import com.microservice.skeleton.upms.entity.RcMenu;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Mr.Yangxiufeng
* Date: 2018-06-13
* Time: 10:12
*/
public interface PermissionService {
List<RcMenu> getPermissionsByRoleId(Integer roleId);
}
package com.microservice.skeleton.upms.service;
import com.microservice.skeleton.upms.entity.RcRole;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Mr.Yangxiufeng
* Date: 2018-05-10
* Time: 20:26
*/
public interface RoleService {
List<RcRole> getRoleByUserId(Integer userId);
}
package com.microservice.skeleton.upms.service;
import com.microservice.skeleton.upms.entity.RcUser;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Mr.Yangxiufeng
* Date: 2018-05-09
* Time: 9:48
*/
public interface UserService {
RcUser findByUsername(String username);
}
package com.microservice.skeleton.upms.service.impl;
import com.microservice.skeleton.upms.entity.RcMenu;
import com.microservice.skeleton.upms.mapper.RcMenuMapper;
import com.microservice.skeleton.upms.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Mr.Yangxiufeng
* Date: 2018-06-13
* Time: 10:12
*/
@Service
public class PermissionServiceImpl implements PermissionService {
@Autowired
private RcMenuMapper menuMapper;
@Override
public List<RcMenu> getPermissionsByRoleId(Integer roleId) {
return menuMapper.getPermissionsByRoleId(roleId);
}
}
package com.microservice.skeleton.upms.service.impl;
import com.microservice.skeleton.upms.entity.RcRole;
import com.microservice.skeleton.upms.mapper.RcRoleMapper;
import com.microservice.skeleton.upms.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Mr.Yangxiufeng
* Date: 2018-05-10
* Time: 20:28
*/
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
private RcRoleMapper roleMapper;
@Override
public List<RcRole> getRoleByUserId(Integer userId) {
return roleMapper.getRoleByUserId(userId);
}
}
server:
port: 9023
port: 9021
spring:
application:
name: resource
zipkin:
base-url: http://localhost:9050
name: mss-upms
datasource:
url: jdbc:mysql://localhost:3306/zuul-auth?useUnicode=true&characterEncoding=utf-8
username: root
password: 123456
druid:
driver-class-name: com.mysql.jdbc.Driver
mapper:
mappers:
com.microservice.skeleton.upms.mapper
eureka:
instance:
prefer-ip-address: true
prefer-ip-address: true #使用IP注册
instance-id: ${spring.cloud.client.ipAddress}:${server.port}
##续约更新时间间隔设置5秒,m默认30s
lease-renewal-interval-in-seconds: 5
......@@ -15,17 +22,4 @@ eureka:
lease-expiration-duration-in-seconds: 10
client:
service-url:
defaultZone: http://mss-eureka1:9010/eureka/,http://mss-eureka2:9011/eureka/
endpoints:
health:
sensitive: false
enabled: true
management:
security:
enabled: false
security:
oauth2:
resource:
id: resource
user-info-uri: http://localhost:9030/uaa/user
prefer-token-info: false
\ No newline at end of file
defaultZone: http://mss-eureka1:9010/eureka/,http://mss-eureka2:9011/eureka/
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.microservice.skeleton.upms.mapper.RcMenuMapper">
<resultMap id="BaseResultMap" type="com.microservice.skeleton.upms.entity.RcMenu">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="VARCHAR" property="id" />
<result column="code" jdbcType="VARCHAR" property="code" />
<result column="p_code" jdbcType="VARCHAR" property="pCode" />
<result column="p_id" jdbcType="VARCHAR" property="pId" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="url" jdbcType="VARCHAR" property="url" />
<result column="is_menu" jdbcType="INTEGER" property="isMenu" />
<result column="level" jdbcType="INTEGER" property="level" />
<result column="sort" jdbcType="INTEGER" property="sort" />
<result column="status" jdbcType="INTEGER" property="status" />
<result column="icon" jdbcType="VARCHAR" property="icon" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
<result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
</resultMap>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.microservice.skeleton.upms.mapper.RcRoleMapper">
<resultMap id="BaseResultMap" type="com.microservice.skeleton.upms.entity.RcRole">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="value" jdbcType="VARCHAR" property="value" />
<result column="tips" jdbcType="VARCHAR" property="tips" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
<result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
<result column="status" jdbcType="INTEGER" property="status" />
</resultMap>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.microservice.skeleton.upms.mapper.RcUserMapper">
<resultMap id="BaseResultMap" type="com.microservice.skeleton.upms.entity.RcUser">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="INTEGER" property="id" />
<result column="avatar" jdbcType="VARCHAR" property="avatar" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="salt" jdbcType="VARCHAR" property="salt" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="birthday" jdbcType="TIMESTAMP" property="birthday" />
<result column="sex" jdbcType="INTEGER" property="sex" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="phone" jdbcType="VARCHAR" property="phone" />
<result column="status" jdbcType="INTEGER" property="status" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
<result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
</resultMap>
<resultMap id="userVoMap" type="com.microservice.skeleton.common.vo.UserVo">
<id column="id" jdbcType="INTEGER" property="userId" />
<result column="avatar" jdbcType="VARCHAR" property="avatar" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="salt" jdbcType="VARCHAR" property="salt" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="birthday" jdbcType="TIMESTAMP" property="birthday" />
<result column="sex" jdbcType="INTEGER" property="sex" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="phone" jdbcType="VARCHAR" property="phone" />
<result column="status" jdbcType="INTEGER" property="status" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
</resultMap>
</mapper>
\ No newline at end of file
package com.microservice.skeleton.upms;
import com.microservice.skeleton.upms.entity.RcUser;
import com.microservice.skeleton.upms.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
import static org.apache.ibatis.io.Resources.getResourceAsStream;
@RunWith(SpringRunner.class)
@SpringBootTest
public class GeneratorTests {
@Autowired
UserService userService;
@Test
public void contextLoads() {
RcUser user = userService.findByUsername("admin");
System.out.println(user);
}
@Test
public void generate() throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(getResourceAsStream("generatorConfig.xml"));
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
for (String warning : warnings) {
System.out.println(warning);
}
}
}
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!--suppress MybatisGenerateCustomPluginInspection -->
<generatorConfiguration>
<context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<property name="javaFileEncoding" value="UTF-8"/>
<!--<property name="useMapperCommentGenerator" value="true"/>-->
<!--通用 Mapper 插件,可以生成带注解的实体类-->
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
<property name="caseSensitive" value="true"/>
<!--<property name="forceAnnotation" value="true"/>-->
<!--<property name="beginningDelimiter" value="`"/>-->
<!--<property name="endingDelimiter" value="`"/>-->
</plugin>
<!--&lt;!&ndash;通用代码生成器插件&ndash;&gt;-->
<!--&lt;!&ndash;mapper接口&ndash;&gt;-->
<!--<plugin type="tk.mybatis.mapper.generator.TemplateFilePlugin">-->
<!--<property name="targetProject" value="src\main\java"/>-->
<!--<property name="targetPackage" value="com.microservice.skeleton.upms.mapper"/>-->
<!--<property name="templatePath" value="generator/mapper.ftl"/>-->
<!--<property name="mapperSuffix" value="Dao"/>-->
<!--<property name="fileName" value="${tableClass.shortClassName}${mapperSuffix}.java"/>-->
<!--</plugin>-->
<!--&lt;!&ndash;mapper.xml&ndash;&gt;-->
<!--<plugin type="tk.mybatis.mapper.generator.TemplateFilePlugin">-->
<!--<property name="targetProject" value="src\main\resources"/>-->
<!--<property name="targetPackage" value="mapper"/>-->
<!--<property name="mapperPackage" value="com.microservice.skeleton.upms.mapper"/>-->
<!--&lt;!&ndash;<property name="templatePath" value="generator/mapperXml.ftl"/>&ndash;&gt;-->
<!--<property name="mapperSuffix" value="Dao"/>-->
<!--<property name="fileName" value="${tableClass.shortClassName}${mapperSuffix}.xml"/>-->
<!--</plugin>-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/zuul-auth"
userId="root"
password="123456">
</jdbcConnection>
<!--MyBatis 生成器只需要生成 Model-->
<javaModelGenerator targetPackage="com.microservice.skeleton.upms.entity" targetProject="src\main\java"/>
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>
<javaClientGenerator targetPackage="com.microservice.skeleton.upms.mapper" targetProject="src/main/java"
type="XMLMAPPER"/>
<!--<table tableName="rc_user">-->
<!--<generatedKey column="id" sqlStatement="JDBC"/>-->
<!--</table>-->
<!--<table tableName="rc_role"-->
<!--&gt;-->
<!--<generatedKey column="id" sqlStatement="JDBC"/>-->
<!--</table>-->
<table tableName="rc_menu">
<generatedKey column="id" sqlStatement="JDBC"/>
</table>
</context>
</generatorConfiguration>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.microservice.skeleton.modules</groupId>
<artifactId>Micro-Service-Skeleton-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<parent>
<groupId>com.microservice.skeleton</groupId>
<artifactId>Micro-Service-Skeleton-Parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<name>mss-modules</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<modules>
<module>mss-upms</module>
<module>mss-resource</module>
</modules>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
......@@ -15,8 +15,12 @@
<name>mss-oauth</name>
<description>Demo project for Spring Boot</description>
<dependencies>
<dependency>
<groupId>com.microservice.skeleton.common</groupId>
<artifactId>mss-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
......@@ -34,12 +38,16 @@
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
......
......@@ -3,10 +3,14 @@ package com.microservice.skeleton.auth;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableHystrix
public class AuthCenterApplication {
public static void main(String[] args) {
......
package com.microservice.skeleton.auth.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
* Created by Mr.Yangxiufeng on 2017/12/27.
* Time:10:34
* ProjectName:Mirco-Service-Skeleton
*/
@Entity
@Table(name = "rc_privilege")
public class RcPrivilegeEntity implements Serializable{
private static final long serialVersionUID = 7945786697073389306L;
private Integer roleId;
private String menuId;
private Date createTime;
@Id
@Column(name = "role_id")
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
@Basic
@Column(name = "menu_id")
public String getMenuId() {
return menuId;
}
public void setMenuId(String menuId) {
this.menuId = menuId;
}
@Basic
@Column(name = "create_time")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RcPrivilegeEntity that = (RcPrivilegeEntity) o;
if (roleId != null ? !roleId.equals(that.roleId) : that.roleId != null) return false;
if (menuId != null ? !menuId.equals(that.menuId) : that.menuId != null) return false;
if (createTime != null ? !createTime.equals(that.createTime) : that.createTime != null) return false;
return true;
}
@Override
public int hashCode() {
int result = roleId != null ? roleId.hashCode() : 0;
result = 31 * result + (menuId != null ? menuId.hashCode() : 0);
result = 31 * result + (createTime != null ? createTime.hashCode() : 0);
return result;
}
}
package com.microservice.skeleton.auth.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
* Created by Mr.Yangxiufeng on 2017/12/27.
* Time:10:34
* ProjectName:Mirco-Service-Skeleton
*/
@Entity
@Table(name = "rc_user_role")
public class RcUserRoleEntity implements Serializable{
private static final long serialVersionUID = 6803189083763570768L;
private int id;
private Integer userId;
private Integer roleId;
private Date createTime;
private String createBy;
@Id
@Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Id
@Column(name = "user_id")
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
@Basic
@Column(name = "role_id")
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
@Basic
@Column(name = "create_time")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Basic
@Column(name = "create_by")
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RcUserRoleEntity that = (RcUserRoleEntity) o;
if (id != that.id) return false;
if (userId != null ? !userId.equals(that.userId) : that.userId != null) return false;
if (roleId != null ? !roleId.equals(that.roleId) : that.roleId != null) return false;
if (createTime != null ? !createTime.equals(that.createTime) : that.createTime != null) return false;
if (createBy != null ? !createBy.equals(that.createBy) : that.createBy != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (userId != null ? userId.hashCode() : 0);
result = 31 * result + (roleId != null ? roleId.hashCode() : 0);
result = 31 * result + (createTime != null ? createTime.hashCode() : 0);
result = 31 * result + (createBy != null ? createBy.hashCode() : 0);
return result;
}
}
package com.microservice.skeleton.auth.repository;
import com.microservice.skeleton.auth.entity.RcMenuEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by Mr.Yangxiufeng on 2017/12/29.
* Time:12:39
* ProjectName:Mirco-Service-Skeleton
*/
@Repository
public interface PermissionRepository extends JpaRepository<RcMenuEntity,Integer> {
@Query(value = "select menu.* from rc_menu menu,rc_privilege p where menu.id=p.menu_id and p.role_id=?1",nativeQuery = true)
List<RcMenuEntity> getPermissionsByRoleId(Integer roleId);
}
package com.microservice.skeleton.auth.repository;
import com.microservice.skeleton.auth.entity.RcRoleEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by Mr.Yangxiufeng on 2017/12/27.
* Time:16:09
* ProjectName:Mirco-Service-Skeleton
*/
@Repository
public interface RoleRepository extends JpaRepository<RcRoleEntity,Integer>{
@Query(value = "select role.* from rc_role role,rc_user_role ur where role.id=ur.role_id and ur.user_id=?1",nativeQuery = true)
List<RcRoleEntity> getRoleValuesByUserId(Integer userId);
}
package com.microservice.skeleton.auth.repository;
import com.microservice.skeleton.auth.entity.RcUserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* Created by Mr.Yangxiufeng on 2017/12/27.
* Time:14:52
* ProjectName:Mirco-Service-Skeleton
*/
@Repository
public interface UserRepository extends JpaRepository<RcUserEntity,Integer>{
RcUserEntity findByUsername(String username);
}
package com.microservice.skeleton.auth.service;
import com.microservice.skeleton.auth.entity.RcMenuEntity;
import com.microservice.skeleton.auth.service.impl.PermissionServiceImpl;
import com.microservice.skeleton.common.vo.MenuVo;
import com.microservice.skeleton.common.vo.Result;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
......@@ -9,6 +15,8 @@ import java.util.List;
* Time:12:37
* ProjectName:Mirco-Service-Skeleton
*/
@FeignClient(name = "mss-upms",fallback = PermissionServiceImpl.class)
public interface PermissionService {
List<RcMenuEntity> getPermissionsByRoleId(Integer roleId);
@GetMapping("permission/getRolePermission/{roleId}")
Result<List<MenuVo>> getRolePermission(@PathVariable("roleId") Integer roleId);
}
package com.microservice.skeleton.auth.service;
import com.microservice.skeleton.auth.entity.RcRoleEntity;
import com.microservice.skeleton.auth.service.impl.RoleServiceImpl;
import com.microservice.skeleton.common.vo.Result;
import com.microservice.skeleton.common.vo.RoleVo;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
/**
* Created by Mr.Yangxiufeng on 2017/12/29.
* Time:12:30
* ProjectName:Mirco-Service-Skeleton
*/
@FeignClient(name = "mss-upms",fallback = RoleServiceImpl.class)
public interface RoleService {
List<RcRoleEntity> getRoleValuesByUserId(Integer userId);
@GetMapping("role/getRoleByUserId/{userId}")
Result<List<RoleVo>> getRoleByUserId(@PathVariable("userId") Integer userId);
}
package com.microservice.skeleton.auth.service;
import com.microservice.skeleton.auth.entity.RcUserEntity;
import com.microservice.skeleton.auth.service.impl.UserServiceImpl;
import com.microservice.skeleton.common.vo.Result;
import com.microservice.skeleton.common.vo.UserVo;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* Created by Mr.Yangxiufeng on 2017/12/27.
* Time:15:12
* ProjectName:Mirco-Service-Skeleton
*/
@FeignClient(name = "mss-upms",fallback = UserServiceImpl.class)
public interface UserService {
RcUserEntity findByUsername(String username);
@GetMapping("user/findByUsername/{username}")
Result<UserVo> findByUsername(@PathVariable("username") String username);
}
package com.microservice.skeleton.auth.service.impl;
import com.microservice.skeleton.auth.entity.RcMenuEntity;
import com.microservice.skeleton.auth.repository.PermissionRepository;
import com.microservice.skeleton.auth.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import com.microservice.skeleton.common.vo.MenuVo;
import com.microservice.skeleton.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by Mr.Yangxiufeng on 2017/12/29.
* Time:12:38
* ProjectName:Mirco-Service-Skeleton
* Created with IntelliJ IDEA.
* Description:
* User: Mr.Yangxiufeng
* Date: 2018-06-13
* Time: 11:14
*/
@Slf4j
@Service
public class PermissionServiceImpl implements PermissionService {
@Autowired
private PermissionRepository permissionRepository;
@Override
public List<RcMenuEntity> getPermissionsByRoleId(Integer roleId) {
return permissionRepository.getPermissionsByRoleId(roleId);
public Result<List<MenuVo>> getRolePermission(Integer roleId) {
log.info("调用{}失败","getRolePermission");
return Result.failure(100,"调用getRolePermission失败");
}
}
package com.microservice.skeleton.auth.service.impl;
import com.microservice.skeleton.auth.entity.RcRoleEntity;
import com.microservice.skeleton.auth.repository.RoleRepository;
import com.microservice.skeleton.auth.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import com.microservice.skeleton.common.vo.Result;
import com.microservice.skeleton.common.vo.RoleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by Mr.Yangxiufeng on 2017/12/29.
* Time:12:31
* ProjectName:Mirco-Service-Skeleton
* Created with IntelliJ IDEA.
* Description:
* User: Mr.Yangxiufeng
* Date: 2018-06-13
* Time: 11:06
*/
@Service
@Slf4j
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleRepository roleRepository;
@Override
public List<RcRoleEntity> getRoleValuesByUserId(Integer userId) {
return roleRepository.getRoleValuesByUserId(userId);
public Result<List<RoleVo>> getRoleByUserId(Integer userId) {
log.info("调用{}失败","getRoleByUserId");
return Result.failure(100,"调用getRoleByUserId失败");
}
}
package com.microservice.skeleton.auth.service.impl;
import com.microservice.skeleton.auth.entity.RcMenuEntity;
import com.microservice.skeleton.auth.entity.RcRoleEntity;
import com.microservice.skeleton.auth.entity.RcUserEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microservice.skeleton.auth.service.PermissionService;
import com.microservice.skeleton.auth.service.RoleService;
import com.microservice.skeleton.auth.service.UserService;
import com.microservice.skeleton.common.vo.MenuVo;
import com.microservice.skeleton.common.vo.Result;
import com.microservice.skeleton.common.vo.RoleVo;
import com.microservice.skeleton.common.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
......@@ -15,7 +17,6 @@ import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
......@@ -34,10 +35,12 @@ public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private PermissionService permissionService;
private ObjectMapper objectMapper = new ObjectMapper();
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
RcUserEntity userEntity = userService.findByUsername(username);
if (userEntity == null) {
Result<UserVo> userResult = userService.findByUsername(username);
if (userResult.getCode() == 100) {
throw new UsernameNotFoundException("用户:" + username + ",不存在!");
}
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
......@@ -45,20 +48,28 @@ public class UserDetailsServiceImpl implements UserDetailsService {
boolean accountNonExpired = true; // 过期性 :true:没过期 false:过期
boolean credentialsNonExpired = true; // 有效性 :true:凭证有效 false:凭证无效
boolean accountNonLocked = true; // 锁定性 :true:未锁定 false:已锁定
List<RcRoleEntity> roleValues = roleService.getRoleValuesByUserId(userEntity.getId());
for (RcRoleEntity role:roleValues){
//角色必须是ROLE_开头,可以在数据库中设置
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_"+role.getValue());
grantedAuthorities.add(grantedAuthority);
//获取权限
List<RcMenuEntity> permissionList = permissionService.getPermissionsByRoleId(role.getId());
for (RcMenuEntity menu:permissionList
) {
GrantedAuthority authority = new SimpleGrantedAuthority(menu.getCode());
grantedAuthorities.add(authority);
UserVo userVo = new UserVo();
BeanUtils.copyProperties(userResult.getData(),userVo);
Result<List<RoleVo>> roleResult = roleService.getRoleByUserId(userVo.getId());
if (roleResult.getCode() != 100){
List<RoleVo> roleVoList = roleResult.getData();
for (RoleVo role:roleVoList){
//角色必须是ROLE_开头,可以在数据库中设置
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_"+role.getValue());
grantedAuthorities.add(grantedAuthority);
//获取权限
Result<List<MenuVo>> perResult = permissionService.getRolePermission(role.getId());
if (perResult.getCode() != 100){
List<MenuVo> permissionList = perResult.getData();
for (MenuVo menu:permissionList
) {
GrantedAuthority authority = new SimpleGrantedAuthority(menu.getCode());
grantedAuthorities.add(authority);
}
}
}
}
User user = new User(userEntity.getUsername(), userEntity.getPassword(),
User user = new User(userVo.getUsername(), userVo.getPassword(),
enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuthorities);
return user;
}
......
package com.microservice.skeleton.auth.service.impl;
import com.microservice.skeleton.auth.entity.RcUserEntity;
import com.microservice.skeleton.auth.repository.UserRepository;
import com.microservice.skeleton.auth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import com.microservice.skeleton.common.vo.Result;
import com.microservice.skeleton.common.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
* Created by Mr.Yangxiufeng on 2017/12/27.
* Time:15:13
* ProjectName:Mirco-Service-Skeleton
* Created with IntelliJ IDEA.
* Description:
* User: Mr.Yangxiufeng
* Date: 2018-06-13
* Time: 10:56
*/
@Service
@Slf4j
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public RcUserEntity findByUsername(String username) {
return userRepository.findByUsername(username);
public Result<UserVo> findByUsername(String username) {
log.info("调用{}失败","findByUsername");
return Result.failure(100,"调用findByUsername接口失败");
}
}
......@@ -46,3 +46,19 @@ logging:
org:
springframework:
web: info
###feign 默认关闭熔断,请看HystrixFeignConfiguration
feign:
hystrix:
enabled: true
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 60000
ribbon:
ReadTimeout: 30000
ConnectTimeout: 60000
MaxAutoRetries: 0
MaxAutoRetriesNextServer: 1
\ No newline at end of file
package com.microservice.skeleton.auth;
import com.microservice.skeleton.auth.entity.RcUserEntity;
import com.microservice.skeleton.auth.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
......@@ -15,8 +14,6 @@ public class AuthCenterApplicationTests {
UserService userService;
@Test
public void contextLoads() {
RcUserEntity user = userService.findByUsername("test1");
System.out.println(user);
}
}
......@@ -80,16 +80,4 @@
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册