java - 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
}
解决方案
此错误告诉您 Java 无法解析要使用的身份验证定义,因为您要导入两个。您需要的是
org.springframework.security.core.Authentication
,所以只需删除另一个导入。
推荐阅读
- google-maps - 当 Alternatives 属性设置为 false 时,Google Directions API 如何确定要返回的路线
- javascript - 如何格式化从 Object.values 中获取的 JSON 数据字符串?
- php - 将 cURL 转换为 wp_remote_post 不起作用,即 privat24 API
- google-apps-script - 谷歌表格停止脚本“删除重复行”将所有公式转换为值并仅删除列 A:A 中的重复项
- hyperledger-fabric - 提交使用私有数据的交易时如何选择背书节点
- javascript - 如何在 Element UI 的 Table 的行中显示动态信息
- ubuntu - 在 Ubuntu 18.04 上启用 root 用户
- corda - corda - 如何在节点中实现corda帐户?
- ruby - Ruby postgres 脚本未运行
- ruby-on-rails - 每次我运行 docker-compose run web 时 Docker 多个容器