2017-04-18 220 views
0

我試圖根據https://github.com/spring-projects/spring-framework/blob/master/src/docs/asciidoc/web/web-websocket.adoc#token-based-authentication實現基於令牌的身份驗證。SockJS/STOMP Web Socket的Spring Security「基於令牌的身份驗證」

我對我的HTTP請求使用基本身份驗證,所以Spring在成功身份驗證後返回x-auth令牌。我將此令牌添加到STOMP CONNECT命令。

@Configuration 
@EnableWebSocketMessageBroker 
public class MyConfig extends AbstractWebSocketMessageBrokerConfigurer { 

    @Override 
    public void configureClientInboundChannel(ChannelRegistration registration) { 
    registration.setInterceptors(new ChannelInterceptorAdapter() { 

     @Override 
     public Message<?> preSend(Message<?> message, MessageChannel channel) { 

      StompHeaderAccessor accessor = 
       MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); 

      if (StompCommand.CONNECT.equals(accessor.getCommand())) { 
       String authToken = accessor.getFirstNativeHeader("X-Auth-Token"); 
       log.debug("webSocket token is {}", authToken); 
       Principal user = ... ; // access authentication header(s) 
       accessor.setUser(user); 
      } 

      return message; 
     } 
    }); 
    } 
} 

但是,我完全失去了我將在「Principal user = ...;」上做的事情。我如何用令牌獲得原則?任何人都可以點亮一下嗎?

+0

可能在[Spring中的Websocket身份驗證和授權]的副本(https://stackoverflow.com/questions/45405332/websocket-authentication-and-authorization-in-spring) –

回答

0

選項A

如果您的WebSocket CONNECT端點是春天確保,你應該能夠得到校長(又名用戶),通過調用Authentication auth = SecurityContextHolder.getContext().getAuthentication();。從那裏,你會打電話auth.getPrincipal()

選項B

我personnaly使用JWT爲我的基於令牌的身份驗證系統。我有,我有一個方法,從我使用的JWT令牌

public Authentication getAuthenticationFromToken(String token) { 
    if (token != null) { 
     UserDetails user = getUserFromToken(token); 

     if (user != null) 
      return new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities()); 
    } 

    return null; 
} 

public UserDetails getUserFromToken(String token) { 
    Jws<Claims> jws = Jwts.parser() 
      .requireIssuer("myIssuer") 
      .setSigningKey("myBase64Secret==") 
      .parseClaimsJws(token); 

    String username = jws.getBody().getSubject(); 
    return userDetailsService.loadUserByUsername(username); 
} 

庫得到了用戶自定義JWTService是https://github.com/jwtk/jjwt

本教程還可以幫助你建立JWT https://www.toptal.com/java/rest-security-with-jwt-spring-security-and-java

+0

我想實現機器後端Web套接字身份驗證和授權,那裏沒有用戶原則,那我該怎麼辦? – Amit

+0

另外,看看這個:https://robertleggett.wordpress.com/2015/05/27/websockets-with-spring-spring-security/ – Marc