ServiceComb实战combDemo
步骤一、配置POM



    4.0.0

    cn.qchcolud
    combDemo
    0.0.1-SNAPSHOT
    jar

    combDemo
    Demo project for ServiceComb-Spring

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.12.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
        
            org.hibernate
            hibernate-validator
        

        
            org.springframework.boot
            spring-boot-starter
        
          
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.apache.servicecomb
            spring-boot-starter-provider
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
  mysql
  mysql-connector-java


  org.springframework.boot
  spring-boot-starter-data-jpa


    io.jsonwebtoken
    jjwt-api
    0.10.5


    io.jsonwebtoken
    jjwt-impl
    0.10.5
    runtime


    io.jsonwebtoken
    jjwt-jackson
    0.10.5
    runtime



    com.fasterxml.jackson.core
    jackson-databind
    2.8.8.1

    

    
        
            
                org.apache.servicecomb
                java-chassis-dependencies
                1.0.0-m2
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
                org.springframework.boot
                spring-boot-maven-plugin
                1.5.12.RELEASE
                
                    
                        
                            repackage
                        
                        
                            target/bin
                            exec
                        
                    
                
            
            
                org.apache.maven.plugins
                maven-jar-plugin
                2.6
                
                    
                        
                            .
                        
                    
                
            
        
    


步骤二、application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/combDemo?useSSL=false
spring.datasource.username=root
spring.datasource.password=1234
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

步骤三、工程源码


package cn.qchcolud.combDemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.apache.servicecomb.springboot.starter.provider.EnableServiceComb;

@SpringBootApplication
@EnableServiceComb
public class CombDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(CombDemoApplication.class, args);
    }
}
package cn.qchcolud.combDemo.dto;

public class UserDTO {
      private String name;
      private String password;
      public String getName() {
        return name;
      }
      public String getPassword() {
        return password;
      }
      public UserDTO() {
      }
      public UserDTO(String name, String password) {
        this.name = name;
        this.password = password;
      }
    }
package cn.qchcolud.combDemo.entity;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "T_User")
public class UserEntity {
  @Id
  private String name;

  private String password;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public UserEntity() {
  }

  public UserEntity(String name, String password) {
    this.name = name;
    this.password = password;
  }
}
package cn.qchcolud.combDemo.jwt;

import java.time.ZonedDateTime;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import static io.jsonwebtoken.SignatureAlgorithm.HS512;

@Component
public class JwtTokenStore implements TokenStore {
  private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenStore.class);

  private final String secretKey;

  private final int secondsToExpire;

  public JwtTokenStore() {
    this.secretKey = "someSecretKeyForAuthenticagggggggggggggggggggggtiondfgdgfdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd";
    this.secondsToExpire = 60 * 60 * 24;
  }

  public JwtTokenStore(String secretKey, int secondsToExpire) {
    this.secretKey = secretKey;
    this.secondsToExpire = secondsToExpire;
  }

  @Override
  public String generate(String userName) {
    return Jwts.builder().setSubject(userName)
        .setExpiration(Date.from(ZonedDateTime.now().plusSeconds(secondsToExpire).toInstant()))
        .signWith(HS512, secretKey).compact();
  }

  @Override
  public boolean validate(String token) {
    try {
      return StringUtils.isNotEmpty(Jwts.parser()
       .setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject());
    } catch (JwtException | IllegalArgumentException e) {
      LOGGER.info("validateToken token : " + token + " failed", e);
    }
    return false;
  }
}
package cn.qchcolud.combDemo.jwt;

public interface TokenStore {
      String generate(String userName);

      boolean validate(String token);
    }
package cn.qchcolud.combDemo.repository;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

import cn.qchcolud.combDemo.entity.UserEntity;

@Repository
public interface UserRepository extends PagingAndSortingRepository {
  UserEntity findByName(String name);
}
package cn.qchcolud.combDemo.service;

import org.springframework.http.ResponseEntity;

import cn.qchcolud.combDemo.dto.UserDTO;

public interface UserService {
      ResponseEntity logon(UserDTO user);
      ResponseEntity login(UserDTO user);
    }
package cn.qchcolud.combDemo.service;

import org.apache.commons.lang3.StringUtils;
import org.apache.servicecomb.provider.rest.common.RestSchema;

import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.qchcolud.combDemo.dto.UserDTO;
import cn.qchcolud.combDemo.entity.UserEntity;
import cn.qchcolud.combDemo.jwt.TokenStore;
import cn.qchcolud.combDemo.repository.UserRepository;
import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
import static org.springframework.http.HttpHeaders.AUTHORIZATION;

@RestSchema(schemaId = "user")
@RequestMapping(path = "/")
public class UserServiceImpl implements UserService {
  private final UserRepository repository;

  private final TokenStore tokenStore;

  @Autowired
  public UserServiceImpl(UserRepository repository, TokenStore tokenStore) {
    this.repository = repository;
    this.tokenStore = tokenStore;
  }

  @Override
  @PostMapping(path = "logon")
  public ResponseEntity logon(@RequestBody UserDTO user) {
    if (validateUser(user)) {
      UserEntity dbUser = repository.findByName(user.getName());
      if (dbUser == null) {
        UserEntity entity = new UserEntity(user.getName(), user.getPassword());
        repository.save(entity);
        return new ResponseEntity<>(true, HttpStatus.OK);
      }
      throw new InvocationException(BAD_REQUEST, "user name had exist");
    }
    throw new InvocationException(BAD_REQUEST, "incorrect user");
  }

  @Override
  @PostMapping(path = "login")
  public ResponseEntity login(@RequestBody UserDTO user) {

      System.out.println("-->"+user.getName()+"--"+user.getPassword());
    if (validateUser(user)) {
      UserEntity dbUser = repository.findByName(user.getName());
      if (dbUser != null) {
        if (dbUser.getPassword().equals(user.getPassword())) {
          String token = tokenStore.generate(user.getName());
          HttpHeaders headers = generateAuthenticationHeaders(token);
          //add authentication header
          return new ResponseEntity<>(true, headers, HttpStatus.OK);
        }
        throw new InvocationException(BAD_REQUEST, "wrong password");
      }
      throw new InvocationException(BAD_REQUEST, "user name not exist");
    }
    throw new InvocationException(BAD_REQUEST, "incorrect user");
  }

  private boolean validateUser(UserDTO user) {
    return user != null && StringUtils.isNotEmpty(user.getName()) && StringUtils.isNotEmpty(user.getPassword());
  }

  private HttpHeaders generateAuthenticationHeaders(String token) {
    HttpHeaders headers = new HttpHeaders();
    headers.add(AUTHORIZATION, token);
    return headers;
  }
}