您好我在尝试在java rest中实现jjwt令牌时遇到了问题。我在创建令牌时使用静态方法,当我在控制台上测试它时,每次都能很好地工作。但是当我尝试在端点上创建它时(String方法),会出现一些错误。 AJAX调用工作正常,我不知道为什么在控制台上显示令牌工作正常,当我尝试在端点上的简单javascript警报(xhr.responseText)上显示它时,我不能做它。我可以看到令牌是一个字符串,为什么我无法显示它?。
这是创建令牌字符串的静态方法:
public class ValidateToken{
public static String createToken(String user){
Key key = MacProvider.generateKey();
String token = Jwts.builder().setSubject(user).signWith(SignatureAlgorithm.HS256, key).compact();
return token;
}
}
这是控制台上的测试方法,效果很好:
public static void main(String args[]){
String user="TokenTest";
System.out.println(ValidateToken.createToken(user));
}
这是java端点:
@Path("/validateToken")
public class Autenticacion_stateless {
@POST
@Path("/validate")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String createToken(@FormParam("user") String user){
String response= null;
try
{
ValidateToken.createToken(user);
}
catch(SignatureException e)
{
System.out.println("It does'nt work.");
}
return response;
}
}
这是AJAX电话:
function createToken(){
user= document.getElementById("user");
var xhr= new XMLHttpRequest();
var url= "/Proyecto_Final_AAB/rest/validateToken/validate";
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(xhr.responseText);
}
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("user="+user.value);
}
这是带有输入文本的html文件:
<html>
<head>
<script type="text/javascript" src="src/js/token.js"></script>
</head>
<body>
<input type="text" id="user">
<input type="button" value="send" onclick="createToken()">
</body>
</html>
This is the image with the token on console
abr 19, 2017 9:19:13 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
ADVERTENCIA: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Proyecto_Final_AAB' did not find a matching property.
abr 19, 2017 9:19:13 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMACIÓN: Server version: Apache Tomcat/7.0.75
abr 19, 2017 9:19:13 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMACIÓN: Server built: Jan 18 2017 20:54:42 UTC
abr 19, 2017 9:19:13 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMACIÓN: Server number: 7.0.75.0
abr 19, 2017 9:19:13 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMACIÓN: OS Name: Windows 7
abr 19, 2017 9:19:13 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMACIÓN: OS Version: 6.1
abr 19, 2017 9:19:13 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMACIÓN: Architecture: x86
abr 19, 2017 9:19:13 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMACIÓN: Java Home: C:\Program Files\Java\jre1.8.0_121
abr 19, 2017 9:19:13 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMACIÓN: JVM Version: 1.8.0_121-b13
abr 19, 2017 9:19:13 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMACIÓN: JVM Vendor: Oracle Corporation
abr 19, 2017 9:19:13 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMACIÓN: CATALINA_BASE: C:\Users\user\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
abr 19, 2017 9:19:13 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMACIÓN: CATALINA_HOME: C:\Program Files\Apache Software Foundation\Tomcat 7.0
abr 19, 2017 9:19:13 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMACIÓN: Command line argument: -Dcatalina.base=C:\Users\user\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
abr 19, 2017 9:19:13 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMACIÓN: Command line argument: -Dcatalina.home=C:\Program Files\Apache Software Foundation\Tomcat 7.0
abr 19, 2017 9:19:13 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMACIÓN: Command line argument: -Dwtp.deploy=C:\Users\user\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
abr 19, 2017 9:19:13 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMACIÓN: Command line argument: -Djava.endorsed.dirs=C:\Program Files\Apache Software Foundation\Tomcat 7.0\endorsed
abr 19, 2017 9:19:13 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMACIÓN: Command line argument: -Dfile.encoding=Cp1252
abr 19, 2017 9:19:13 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFORMACIÓN: La biblioteca nativa de Apache Tomcat basada en ARP que permite un rendimiento óptimo en entornos de desarrollo no ha sido hallada en java.library.path: C:\Program Files\Java\jre1.8.0_121\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre1.8.0_121/bin/client;C:/Program Files/Java/jre1.8.0_121/bin;C:/Program Files/Java/jre1.8.0_121/lib/i386;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Users\user\AppData\Roaming\npm;C:\Users\user\Downloads\eclipse-jee-neon-2-win32\eclipse;;.
abr 19, 2017 9:19:14 PM org.apache.coyote.AbstractProtocol init
INFORMACIÓN: Initializing ProtocolHandler ["http-bio-8079"]
abr 19, 2017 9:19:14 PM org.apache.coyote.AbstractProtocol init
INFORMACIÓN: Initializing ProtocolHandler ["ajp-bio-8008"]
abr 19, 2017 9:19:14 PM org.apache.catalina.startup.Catalina load
INFORMACIÓN: Initialization processed in 836 ms
abr 19, 2017 9:19:14 PM org.apache.catalina.core.StandardService startInternal
INFORMACIÓN: Arrancando servicio Catalina
abr 19, 2017 9:19:14 PM org.apache.catalina.core.StandardEngine startInternal
INFORMACIÓN: Starting Servlet Engine: Apache Tomcat/7.0.75
abr 19, 2017 9:19:14 PM org.apache.catalina.util.SessionIdGeneratorBase createSecureRandom
INFORMACIÓN: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [146] milliseconds.
abr 19, 2017 9:19:16 PM org.apache.catalina.startup.TaglibUriRule body
INFORMACIÓN: TLD skipped. URI: urn:com:sun:jersey:api:view is already defined
abr 19, 2017 9:19:16 PM org.apache.catalina.startup.TldConfig execute
INFORMACIÓN: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
abr 19, 2017 9:19:16 PM com.sun.jersey.api.core.servlet.WebAppResourceConfig init
INFORMACIÓN: Scanning for root resource and provider classes in the Web app resource paths:
/WEB-INF/lib
/WEB-INF/classes
abr 19, 2017 9:19:18 PM com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFORMACIÓN: Root resource classes found:
class org.comunidadIT.proyecto.accesoDatos.AutenticarSuperAdministrador
class org.comunidadIT.proyecto.controladores.AdminSeg
class org.comunidadIT.proyecto.controladores.SuperAdmin
class org.comunidadIT.proyecto.controladores.Administradores
class org.comunidadIT.proyecto.accesoDatos.AutenticarAdministradorVuelo
class org.comunidadIT.proyecto.accesoDatos.Autenticacion_stateless
class org.comunidadIT.proyecto.accesoDatos.AutenticarAdministradorSeguridad
class org.comunidadIT.proyecto.controladores.AdminVuelos
class org.comunidadIT.proyecto.accesoDatos.AutenticarUsuario
class org.comunidadIT.proyecto.controladores.Empleados
abr 19, 2017 9:19:18 PM com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFORMACIÓN: Provider classes found:
class org.codehaus.jackson.jaxrs.JacksonJsonProvider
class org.codehaus.jackson.jaxrs.JsonParseExceptionMapper
class com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider
class org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider
class com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider
class org.codehaus.jackson.jaxrs.JsonMappingExceptionMapper
abr 19, 2017 9:19:18 PM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFORMACIÓN: Initiating Jersey application, version 'Jersey: 1.19.1 03/11/2016 02:42 PM'
abr 19, 2017 9:19:19 PM org.apache.coyote.AbstractProtocol start
INFORMACIÓN: Starting ProtocolHandler ["http-bio-8079"]
abr 19, 2017 9:19:19 PM org.apache.coyote.AbstractProtocol start
INFORMACIÓN: Starting ProtocolHandler ["ajp-bio-8008"]
abr 19, 2017 9:19:19 PM org.apache.catalina.startup.Catalina start
INFORMACIÓN: Server startup in 5375 ms
abr 19, 2017 9:19:34 PM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
GRAVE: The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container
java.lang.NoSuchFieldError: USE_DEFAULTS
at com.fasterxml.jackson.annotation.JsonInclude$Value.<clinit>(JsonInclude.java:204)
at com.fasterxml.jackson.databind.cfg.MapperConfig.<clinit>(MapperConfig.java:44)
at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:549)
at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:465)
at io.jsonwebtoken.impl.DefaultJwtBuilder.<clinit>(DefaultJwtBuilder.java:42)
at io.jsonwebtoken.Jwts.builder(Jwts.java:116)
at org.comunidadIT.proyecto.accesoDatos.ValidarToken.crearToken(ValidarToken.java:25)
at org.comunidadIT.proyecto.accesoDatos.Autenticacion_stateless.createToken(Autenticacion_stateless.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
abr 19, 2017 9:19:34 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: El Servlet.service() para el servlet [Servlet_Aeropuerto] en el contexto con ruta [/Proyecto_Final_AAB] lanzó la excepción [java.lang.NoSuchFieldError: USE_DEFAULTS] con causa raíz
java.lang.NoSuchFieldError: USE_DEFAULTS
at com.fasterxml.jackson.annotation.JsonInclude$Value.<clinit>(JsonInclude.java:204)
at com.fasterxml.jackson.databind.cfg.MapperConfig.<clinit>(MapperConfig.java:44)
at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:549)
at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:465)
at io.jsonwebtoken.impl.DefaultJwtBuilder.<clinit>(DefaultJwtBuilder.java:42)
at io.jsonwebtoken.Jwts.builder(Jwts.java:116)
at org.comunidadIT.proyecto.accesoDatos.ValidarToken.crearToken(ValidarToken.java:25)
at org.comunidadIT.proyecto.accesoDatos.Autenticacion_stateless.createToken(Autenticacion_stateless.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
这是我的pom.xml:
http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0
<dependencies>
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-bundle -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.19</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.ws.rs/jsr311-api -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
<!-- JJWT Token dependencias de github -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.jaxrs/jackson-jaxrs-json-provider -->
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.9.0.pr1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0.pr1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0.pr1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
</dependencies>
<groupId>
Proyecto_Final_AAB</groupId>
<artifactId>Proyecto_Final_AAB</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project>
我已经添加了依赖项的屏幕截图,并手动添加了参考库: Maven dep and Manually libs added
答案 0 :(得分:0)
这对我来说就像jackson libs jjwt使用的文件冲突和你手动或通过其他jar导入的文件冲突。
如果你去Maven repository,你会在下面看到JJWT依赖于jackson-databind。 (v 2.8.2)在这种情况下。
检查您在类路径中实际拥有的版本,并且我打赌它有所不同。
如果您仍然无法解决问题,请尝试this tool。