[英]Passing JWT token to SockJS
我需要在與SockJS握手時發送令牌。 我嘗試了很多建議的實現,但調用了同樣的異常
java.lang.IllegalArgumentException: JWT String argument cannot be null or empty.
在后端WebSocketConfig
@Configuration
@EnableWebSocketMessageBroker
@CrossOrigin
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/socket");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket").withSockJS();
}
}
嘗試與套接字建立連接的函數。 簡單的javascript。
function connect() {
var socket = new SockJS('http://localhost:8889/websocket',
null,
{
transports: ['xhr-streaming'],
headers: {'Authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9...' }
});
stompClient = Stomp.over(socket);
stompClient.connect({},function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/socket/event', function (greeting) {
showGreeting(JSON.parse(greeting.body).content);
});
});
}
問題出在握手上,那些標題似乎沒有正確傳遞令牌。 我在握手上嘗試了很多變化,但在我的情況下我找不到正確的。
我從這里得到了實現的想法,之后我嘗試在握手后使用頭文件,但我發現它需要立即使用令牌。
https://github.com/sockjs/sockjs-client/issues/196#issuecomment-61469141
編輯:添加WebSecurityConfig
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.cors()
.configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues())
.and()
.csrf()
.disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers("/login/**").permitAll()
.antMatchers("/websocket/**").permitAll()
.anyRequest().authenticated();
// Custom JWT based security filter
JwtAuthorizationTokenFilter authenticationTokenFilter = new JwtAuthorizationTokenFilter(userDetailsService(), jwtTokenUtil, tokenHeader);
httpSecurity
.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
}//end configure(HttpSecurity)
createAuthenticationToken
@ApiOperation(value = "Login with the user credentials",
response = JwtAuthenticationResponse.class)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "Not Found",response = ExceptionResponse.class),
@ApiResponse(code = 400, message = "Bad Request",response = ExceptionResponse.class),
@ApiResponse(code = 200 , message = "OK", response = JwtAuthenticationResponse.class)
})
@RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(
@ApiParam(value = "User's email and password", required = true)
@RequestBody JwtAuthenticationRequest authenticationRequest)
throws AuthenticationException {
ResponseEntity<?> response;
//authenticate the user
final User user = userService.getByEmail(authenticationRequest.getEmail());
try {
authenticate(user.getUsername(), authenticationRequest.getPassword(),user.getId(),user.getAuthority().getName());
// Reload password post-security so we can generate the token
final UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails);
// Return the token
response = ResponseEntity.ok(new JwtAuthenticationResponse(token,user.getUsername(),user.getFirstName(),user.getLastName(),
user.getEmail(),user.getId(),user.getAuthority().getName(),jwtTokenUtil.getExpirationTime(token)));
}catch(NullPointerException e) {
response = new ResponseEntity<>(new ExceptionResponse(404,"User Not Found","Authentication Failure"),HttpStatus.NOT_FOUND);
}catch(AuthenticationException e) {
response = new ResponseEntity<>(new ExceptionResponse(400,"Invalid E-mail or Password","Authentication Failure"),HttpStatus.BAD_REQUEST);
}//end try
return response;
}//end createAuthenticationToken(JwtAuthenticationRequest)
堆棧跟蹤(當從帶有后端的websocket發生握手和連接時,相同的異常被捕獲了四次)。 我把它添加到pastebin上,因為它會破壞帖子。
例外
2019-05-16 11:36:17.936 WARN 11584 --- [nio-8889-exec-9] a.d.s.JwtAuthorizationTokenFilter : couldn't find bearer string, will ignore the header
2019-05-16 11:36:17.937 ERROR 11584 --- [nio-8889-exec-9] a.d.s.JwtAuthorizationTokenFilter : an error occured during getting username from token
java.lang.IllegalArgumentException: JWT String argument cannot be null or empty.
at io.jsonwebtoken.lang.Assert.hasText(Assert.java:135) ~[jjwt-0.9.0.jar:0.9.0]
at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:479) ~[jjwt-0.9.0.jar:0.9.0]
at io.jsonwebtoken.impl.DefaultJwtParser.parseClaimsJws(DefaultJwtParser.java:541) ~[jjwt-0.9.0.jar:0.9.0]
at package.security.JwtTokenUtil.getAllClaimsFromToken(JwtTokenUtil.java:59) ~[classes/:na]
at package.security.JwtTokenUtil.getClaimFromToken(JwtTokenUtil.java:52) ~[classes/:na]
at package.security.JwtTokenUtil.getUsernameFromToken(JwtTokenUtil.java:34) ~[classes/:na]
at package.security.JwtAuthorizationTokenFilter.extractUsername(JwtAuthorizationTokenFilter.java:79) [classes/:na]
at package.security.JwtAuthorizationTokenFilter.doFilterInternal(JwtAuthorizationTokenFilter.java:44) [classes/:na]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
...
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) [spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) [spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.20.jar:8.5.20]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.20.jar:8.5.20]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
...
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799) [tomcat-embed-core-8.5.20.jar:8.5.20]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.20.jar:8.5.20]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.20.jar:8.5.20]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1457) [tomcat-embed-core-8.5.20.jar:8.5.20]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.20.jar:8.5.20]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_201]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_201]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.20.jar:8.5.20]
at java.lang.Thread.run(Unknown Source) [na:1.8.0_201]
用於注冊自定義身份驗證攔截器的服務器端配置。 請注意,攔截器只需要在CONNECT消息上進行身份驗證和設置用戶頭。 Spring會記錄並保存經過身份驗證的用戶,並將其與同一會話中的后續STOMP消息相關聯。 以下示例顯示如何注冊自定義身份驗證攔截器:
@Configuration
@EnableWebSocketMessageBroker
public class MyConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(new ChannelInterceptor() {
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor =
MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (StompCommand.CONNECT.equals(accessor.getCommand())) {
Authentication user = ... ; // access authentication header(s)
accessor.setUser(user);
}
return message;
}
});
}
}
另請注意,當您使用Spring Security的消息授權時,您需要確保在Spring Security之前訂購身份驗證ChannelInterceptor配置。 最好通過在自己的WebSocketMessageBrokerConfigurer實現中聲明自定義攔截器來實現,該實現使用@Order(Ordered.HIGHEST_PRECEDENCE + 99)進行標記。
另一種方式:同樣,SockJS JavaScript客戶端不提供使用SockJS傳輸請求發送HTTP頭的方法。 正如您可以看到sockjs-client問題196.相反,它確實允許發送可用於發送令牌的查詢參數,然后使用Spring,您可以設置一些過濾器,該過濾器將使用提供的令牌識別會話。 ,但這有其自身的缺點(例如,令牌可能無意中使用服務器日志中的URL記錄)。
Websocket在HTTP標頭中不遵循相同的模式。 這就是為什么,即使你在標題中發送令牌,它也找不到。 之前我有同樣的問題,我改變了websocket安全結構。
我的示例代碼是這樣的:
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.setInterceptors(new ChannelInterceptorAdapter() {
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
MessageHeaders headers = message.getHeaders();
SimpMessageType type = (SimpMessageType) headers.get("simpMessageType");
List<String> tokenList = accessor.getNativeHeader("Authorization");
String token = null;
if(tokenList == null || tokenList.size() < 1) {
return message;
} else {
token = tokenList.get(0);
if(token == null) {
return message;
}
}
// validate and convert to a Principal based on your own requirements e.g.
// authenticationManager.authenticate(JwtAuthentication(token))
try{
JwtAuthenticationToken jwtAuthenticationToken = new JwtAuthenticationToken(new RawAccessJwtToken(tokenExtractor.extract(token)));
Authentication yourAuth = jwtAuthenticationProvider.authenticate(jwtAuthenticationToken);
accessor.setUser(yourAuth);
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage());
}
// not documented anywhere but necessary otherwise NPE in StompSubProtocolHandler!
accessor.setLeaveMutable(true);
return MessageBuilder.createMessage(message.getPayload(), accessor.getMessageHeaders());
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.