使用SSO OIDC身份验证协议从WSO2 IS检索JWT令牌

时间:2018-11-14 14:46:49

标签: node.js express jwt wso2is

我正在实现一个基本的NodeJS应用程序,该应用程序将连接到WSO2 Identity Server以进行身份​​验证。

我使用带有openid-connect的SSO对其进行了配置。当我收到回调时,jwt令牌作为片段标识符返回,因为我认为它作为GET请求返回。如何从服务器端本身检索此JWT?

这是我尝试登录时URL的外观 https://localhost:9443/oauth2/authorize?response_type=id_token&client_id={CLIENT_ID}&scope=openid%20profile%20email&nonce=aaa&redirect_uri=http://localhost:3001/auth/callback 使用服务提供商提供的内容将client_id替换为实际的client_id

这是WSO2如何返回回调的示例。 http://localhost:3001/auth/callback#id_token={TOKEN}

1 个答案:

答案 0 :(得分:0)

如果将JAVA用于后端开发,则可以使用servlet过滤器来拦截此JWT令牌并对其进行处理。以下是您可以使用的示例过滤器。您可以使用WSO2 Application Server部署您的应用程序。

public class JWTAction implements Filter {
private static final Logger logger = Logger.getLogger(JWTAction.class);
private static final PropertyReader propertyReader = new PropertyReader();


/**
 * This method is for get public key
 *
 * @return return for getting public key
 * @throws IOException              if unable to load the file
 * @throws KeyStoreException        if unable to get instance
 * @throws CertificateException     if unable to certify
 * @throws NoSuchAlgorithmException cause by other underlying exceptions(KeyStoreException)
 */

private static PublicKey getPublicKey() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException {

    InputStream file = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(propertyReader.getSsoKeyStoreName());
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    //loading key store with password
    keystore.load(file, propertyReader.getSsoKeyStorePassword().toCharArray());
    Certificate cert = keystore.getCertificate(propertyReader.getSsoCertAlias());
    return cert.getPublicKey();
}

public void init(FilterConfig filterConfig) {

}


public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                     FilterChain filterChain) throws IOException {

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    String jwt = request.getHeader("X-JWT-Assertion");
    String ssoRedirectUrl = propertyReader.getSsoRedirectUrl();

    if (jwt == null || "".equals(jwt)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Redirecting to {}");
        }
        response.sendRedirect(ssoRedirectUrl);
        return;
    }

    String username = null;
    String roles = null;

    try {

        SignedJWT signedJWT = SignedJWT.parse(jwt);
        JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) getPublicKey());

        if (signedJWT.verify(verifier)) {
            if (logger.isDebugEnabled()) {
                logger.debug("JWT validation success for token: {}");
            }
            username = signedJWT.getJWTClaimsSet().getClaim("http://wso2.org/claims/emailaddress").toString();
            roles = signedJWT.getJWTClaimsSet().getClaim("http://wso2.org/claims/role").toString();
            if (logger.isDebugEnabled()) {
                logger.debug("User = {" + username + "} | Roles = " + roles);
            }
        } else {
            logger.error("JWT validation failed for token: {" + jwt + "}");
            response.sendRedirect(ssoRedirectUrl);
            return;
        }
    } catch (ParseException e) {
        logger.error("Parsing JWT token failed");
    } catch (JOSEException e) {
        logger.error("Verification of jwt failed");
    } catch (Exception e) {
        logger.error("Failed to validate the jwt {" + jwt + "}");
    }

    if (username != null && roles != null) {
        request.getSession().setAttribute("user", username);
        request.getSession().setAttribute("roles", roles);
    }

    try {
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ServletException e) {
        logger.error("Failed to pass the request, response objects through filters", e);
    }
}

public void destroy() {

}

}