首页 > 解决方案 > JWT getPrincipal 错误,对 Authentication 的引用不明确

问题描述

我正在使用 spring boot 对我的应用程序执行 JWT 安全性,当我尝试生成令牌时,我遇到了以下消息的错误。方法中的错误getPrincipal()

java: reference to Authentication is ambiguous
  both enum org.apache.tomcat.util.net.openssl.ciphers.Authentication in org.apache.tomcat.util.net.openssl.ciphers and interface org.springframework.security.core.Authentication in org.springframework.security.core match

和代码:

package com.accessjobs.pjp.security;

import com.accessjobs.pjp.domain.User;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.security.core.Authentication;  // **here is the error** 

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.accessjobs.pjp.security.SecurityConstants.EXPIRATION_TIME;
import static com.accessjobs.pjp.security.SecurityConstants.SECRET;

@Component
public class JwtTokenProvider {

    //Generate the token

    public String generateToken(Authentication authentication){
        User user = (User)authentication.getPrincipal();  //  ** and the error on this method **
        Date now = new Date(System.currentTimeMillis());

        Date expiryDate = new Date(now.getTime() + EXPIRATION_TIME);

        String userId = Long.toString(user.getId());

        Map<String,Object> claims = new HashMap<>();
        claims.put("id", (Long.toString(user.getId())));
        claims.put("username", user.getEmail());
        claims.put("fullName", user.getFullName());

        return Jwts.builder()
                .setSubject(userId)
                .setClaims(claims)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    //Validate the token

    //Get user Id from token
}    

标签: javaspringsecurity

解决方案


此错误告诉您 Java 无法解析要使用的身份验证定义,因为您要导入两个。您需要的是 org.springframework.security.core.Authentication,所以只需删除另一个导入。


推荐阅读