kotlin框架-jwt

后端新框架学习

1、配置文件 resource/bootstorp.yaml

  配置nacos(配置、服务)

spring:
  cloud:
    nacos:
      discovery:
        server-addr: ***
      config:
        enabled: false # disable nacos config     false  执行默认配置文件application.yaml,   true   执行nacos配置,在nacos后台配置
        server-addr: *** #Nacos as configuration center address
        file-extension: yaml  #Specifies the configuration of yaml format
      username: ***
      password: ***
  application:
    name: teamy-server

 

2、配置文件 resource/bootstorp.yaml,默认执行的配置文件

  端口配置  

server:
  port: 8090
 jwt配置
jwt:
  secret: secretkey    #secret key - should be encrypted  jwt密钥,需修改
  token:
    validity: '18000000'  #过期时间

3、application-dev.yaml配置文件

  数据库配置文件

  也可配置oss、小程序id、公众号等

  使用方法 (以jwt配置使用为例)

@Value("\${jwt.secret}")

 

4、登录CorpAuthService/admin_login

    @RequestMapping(value = ["/admin_login"], method = arrayOf(RequestMethod.POST))
    fun login(@RequestBody appuser: CorpUser): OperationStatus {
        var user: CorpUser? = null
        var os = OperationStatus();
        if (appuser.phone != "") {
            user = this.auMapper.select_by_phone(appuser.phone)
        } else if (appuser.username != "") {
            user = this.auMapper.select_admin_by_username(appuser.username)
        } else if (appuser.email != "") {
            user = this.auMapper.select_by_email(appuser.email)
        }
        if (user == null) {
            os.ok = false;
            os.msg = "用户不存在。"
        } else {
            os = this.check_password(user, appuser.password)
            if(os.ok){
                var evt = AuthEvent(AuthEvent.Action_Reg, appuser.id)
                this.publisher.publishEvent(evt)
                appuser.id=user.id
                appuser.corp_id=user.corp_id
                appuser.role=user.role
                appuser.nickname=user.nickname
                appuser.username=user.username
                appuser.corp=corpMapper.select(user.corp_id)
                appuser.token=jwtUtil.generateToken(appuser.id) 返回token
                os.payload=appuser;
            }
        }
        return os;
    }
    fun generateToken(id:String): String {
        val claims = Jwts.claims().setSubject(id)  将用户id封装在jwt中

        val nowMillis = System.currentTimeMillis()
        val expMillis = nowMillis + tokenValidity
        val exp = Date(expMillis)
        return Jwts.builder().setClaims(claims).setIssuedAt(Date(nowMillis)).setExpiration(exp)
                .signWith(SignatureAlgorithm.HS512, jwtSecret).compact()
    }

5、拦截器

@Component
class JwtTokenFilter : OncePerRequestFilter(){
    @Autowired
    private val jwtTokenUtil: JwtUtil?=null;
    private val log = LoggerFactory.getLogger(JwtTokenFilter::class.java)

    override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) {
        // Get authorization header and validate
        val token: String? = request.getHeader(HttpHeaders.AUTHORIZATION)
        log.debug("过滤:"+token)
        if(isEmpty(token)){
            chain.doFilter(request, response)
            log.debug("jwt空")
            return
        }
        // Get jwt token and validate
        val os=jwtTokenUtil!!.validateToken(token)
        if (os.ok) {
            //设置自定义Header
            val claims: Claims = os.payload as Claims;
            log.debug("getClaims:"+claims.toString())

            var id=claims["sub"].toString()
            log.debug("jwt id:"+id)
            val mutableRequest =  MutableHttpServletRequest(request);
            mutableRequest.putHeader("x-teamy-user-id", id);

            // Get user identity and set it on the spring security context
            this.authenticateAppUser(id,"Guest")
            chain.doFilter(mutableRequest, response)
        }else{
            chain.doFilter(request, response)
            log.warn(os.msg)
        }

    }
    fun authenticateAppUser(id: String,role:String) {
        val authList = mutableListOf<GrantedAuthority>()
        authList.add(SimpleGrantedAuthority(role))
        val au = AuthUser(id, authList)
        val simpleAuthentication = SimpleAuthentication(au)
        SecurityContextHolder.getContext().authentication = simpleAuthentication
    }
}

6、测试接口

    @RequestMapping(value = ["/echo"], method = arrayOf(RequestMethod.GET))
    fun info(@RequestHeader("x-teamy-user-id") id:String):OperationStatus{
        val os=OperationStatus()
       log.info("测试消息")
        os.ok=true
        os.msg="测试消息7:"+id+messageProperties?.url
        return os
    }

7、JWT工作流程图

 

 @................

 

 

 

 

 

 

 


 

posted @ 2021-10-15 16:27  奋斗中的懒人  阅读(227)  评论(0编辑  收藏  举报