对接OKTA 使用SAML2.0协议

那年烟雨落申城
• 阅读 129

对接OKTA 使用SAML2.0协议

缘起

给客户做项目,客户要求内部使用okta登陆,使用SAML2.0协议,需要对接。

okta初探

OKTA是SSO,有个网站可以让我们测试,地址:okta developer,SAML协议的交互流程大致如下

  1. 浏览器打开需要登录系统登陆界面,系统登陆界面只有一个登陆按钮,没有输入用户名密码的地方(原因是OKTA使用域账户登陆的时候,能直接获取域账户名,除了这个还有好多客户端都支持,比如Apple账户)

  2. 点击按钮,跳转到OKTA页面,这个页面只有一个loading动画,个人猜测里面有获取当前域账户名的代码

  3. 然后再次一个跳转,这个跳转跳到一个回调url,这个url官方名称为Single Sign On URL,记住它,后面会用到。跳转到这个页面后,浏览器会发送一个POST请求,content-typeapplication/x-www-form-urlencoded,参数包含一个SAMLResponseRelayState(这个是在OKTA控制台配置的回传参数)大概的样子是 对接OKTA 使用SAML2.0协议

  4. 第3步中的SAMLResponse就是一个xml文档的base64编码后的数据,回调地址接收到SAMLResponse进行校验,并获取登陆名

    OKTA的配置

  5. Single Sign On URL配置我们的系统的地址,是OKTA将认证完成后告诉我们结果的一个接口,接收参数是SAMLResponseRelayState,格式是application/x-www-form-urlencoded,java中方法签名大概是:

    @RequestMapping(value = "/login/success",method = {RequestMethod.POST})
     public String loginSuccess(String SAMLResponse, String RelayState){
    
         System.out.println("sAMLResponse:"+SAMLResponse);
         System.out.println("RelayState:" + RelayState);
    
         return "success";
     }

    配置的地方如下: 对接OKTA 使用SAML2.0协议

  6. 全部配置完后会得到一个页面大致如下 对接OKTA 使用SAML2.0协议 注意:Identity Provider Single Sign-On URL这个就是上面第一步中点击按钮跳转到的链接X.509 Certificate这部分是公钥,用来验证SAMLResponse中签名的公钥

  7. 这个页面可以让你上传一个csv文件(包含登陆名信息)加入到你的group里面,登陆是否能成功,就是取你的域账户名,查询是否在你的group里面,当然你可以配置更复杂的规则 对接OKTA 使用SAML2.0协议

验证逻辑

  1. 引入jar包:
     <dependency>
         <groupId>org.opensaml</groupId>
         <artifactId>opensaml</artifactId>
         <version>2.6.4</version>
     </dependency>
  2. 验证逻辑:
    import org.joda.time.DateTime;
    import org.joda.time.DateTimeZone;
    import org.opensaml.Configuration;
    import org.opensaml.DefaultBootstrap;
    import org.opensaml.saml2.core.Assertion;
    import org.opensaml.saml2.core.Response;
    import org.opensaml.xml.ConfigurationException;
    import org.opensaml.xml.XMLObject;
    import org.opensaml.xml.io.Unmarshaller;
    import org.opensaml.xml.io.UnmarshallerFactory;
    import org.opensaml.xml.io.UnmarshallingException;
    import org.opensaml.xml.security.x509.BasicX509Credential;
    import org.opensaml.xml.signature.Signature;
    import org.opensaml.xml.signature.SignatureValidator;
    import org.opensaml.xml.util.Base64;
    import org.opensaml.xml.validation.ValidationException;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.xml.sax.SAXException;
    

import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec;

public class Test {

private static final Logger logger = LoggerFactory.getLogger(Test.class);
private static final String pattern = "yyyy-MM-dd HH:mm:ss";
private static final BasicX509Credential credential = new BasicX509Credential();
//X.509 Certificate
public static final String publicKeyStr = "xxxxxxx";
//responseMsg就是SAMLResponse
public String validate(String responseMsg) {


    ByteArrayInputStream byteArrayInputStream = null;
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        byteArrayInputStream = new ByteArrayInputStream(Base64.decode(publicKeyStr));
        X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(byteArrayInputStream);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(certificate.getPublicKey().getEncoded());
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
        credential.setPublicKey(publicKey);
    } catch (CertificateException e) {

        logger.error("加载okta PublicKey失败", e);
    } catch (NoSuchAlgorithmException e) {

        logger.error("加载okta PublicKey失败", e);
    } catch (InvalidKeySpecException e) {

        logger.error("加载okta PublicKey失败", e);
    }finally {
        if(byteArrayInputStream != null){
            try {
                byteArrayInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    try (ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64.decode(responseMsg))) {
        DefaultBootstrap.bootstrap();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(inputStream);
        Element documentElement = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(documentElement);
        XMLObject xmlObject = unmarshaller.unmarshall(documentElement);
        Response response = (Response) xmlObject;
        Assertion assertion = response.getAssertions().get(0);
        //验证签名
        Signature signature = assertion.getSignature();
        SignatureValidator signatureValidator = new SignatureValidator(credential);
        //签名验证失败会抛错
        signatureValidator.validate(signature);
        //校验是否登录成功
        String successStr = response.getStatus().getStatusCode().getValue();
        if (!successStr.contains("Success")) {
            logger.error("登录成功标志校验失败,successStr={}", response.getStatus().getStatusCode().getValue());
            return null;
        }
        //检验登录时间
        DateTime notBefore = assertion.getConditions().getNotBefore();
        DateTime notOnOrAfter = assertion.getConditions().getNotOnOrAfter();
        DateTime now = new DateTime(DateTimeZone.UTC);
        logger.error("验证okta返回的时间,notBefore={},notOnOrAfter={},now={}",
                notBefore.toString(pattern), notOnOrAfter.toString(pattern), now.toString(pattern));
        if (now.isBefore(notBefore) || now.isAfter(notOnOrAfter)) {
            logger.error("登录成功时间校验失败,notBefore={},notOnOrAfter={},now={}",
                    notBefore.toString(pattern), notOnOrAfter.toString(pattern), now.toString(pattern));
            return null;
        }
        //返回登录用户名
        return assertion.getSubject().getNameID().getValue();

    } catch (IOException e) {
        logger.error("验证SAMLResponse失败", e);
    } catch (ParserConfigurationException e) {
        logger.error("验证SAMLResponse失败", e);
    } catch (SAXException e) {
        logger.error("验证SAMLResponse失败", e);
    } catch (UnmarshallingException e) {
        logger.error("验证SAMLResponse失败", e);
    } catch (ValidationException e) {
        logger.error("验证SAMLResponse失败", e);
    } catch (ConfigurationException e) {
        logger.error("验证SAMLResponse失败", e);
    } catch (Exception ex) {
        logger.error("验证SAMLResponse失败", ex);
    }

    return null;
}

} ```

点赞
收藏
评论区
推荐文章
Stella981 Stella981
2年前
DISPLAY变量和xhost(原创)
DISPLAY在Linux/Unix类操作系统上,DISPLAY用来设置将图形显示到何处.直接登陆图形界面或者登陆命令行界面后使用startx启动图形,DISPLAY环境变量将自动设置为:0:0,此时可以打开终端,输出图形程序的名称(比如xclock)来启动程序,图形将显示在本地窗口上,在终端上输入printenv查看当前环境变量,
Stella981 Stella981
2年前
Linux服务器ssh远程管理
SSH远程管理SSH(SecureShell)是一种安全通道协议,主要用来实现字符界面的远程登陆,远程复制等功能。SSH协议对通信双方的数据传输进行了加密处理,其中包括用户登陆时输入的用户口令,与早期的telnet(远程管理),rsh(RemoteShell,远程执行命令),rcp(远程复制文件)等应用相比,SSH协议提供了更好的安全性
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Stella981 Stella981
2年前
Linux 远程登录命令telnet
一、telnet简介:  telnet命令通常用来远程登录。telnet程序是基于TELNET协议的远程登录客户端程序。Telnet协议是TCP/IP协议族中的一员,是Internet远程登陆服务的标准协议和主要方式。它为用户提供了在本地计算机上完成远程主机工作的 能力。在终端使用者的电脑上使用telnet程序,用它连接到服务器。终端使用者可以在teln
Stella981 Stella981
2年前
Shibboleth
背景Shibboleth是一个支持SAML2.0的开源IdP服务器。SAML2.0是一个联邦式认证的标准,简单来说就是能够让应用方——也就是资源提供者(ServiceProvider,简称SP)与任意的机构内部认证——也就是身份提供者(IdentityProvider)对接时,能够均采用相同的协议标准。这显然能够简化集成,
Stella981 Stella981
2年前
Linux应急响应(一):SSH暴力破解
0x00前言SSH是目前较可靠,专为远程登录会话和其他网络服务提供安全性的协议,主要用于给远程登录会话数据进行加密,保证数据传输的安全。SSH口令长度太短或者复杂度不够,如仅包含数字,或仅包含字母等,容易被攻击者破解,一旦被攻击者获取,可用来直接登录系统,控制服务器所有权限。0x01应急场景某天,网站
Wesley13 Wesley13
2年前
34.TCP取样器
阅读文本大概需要3分钟。1、TCP取样器的作用   TCP取样器作用就是通过TCP/IP协议来连接服务器,然后发送数据和接收数据。2、TCP取样器详解!(https://oscimg.oschina.net/oscnet/32a9b19ba1db00f321d22a0f33bcfb68a0d.png)TCPClien
Wesley13 Wesley13
2年前
IOS 委托和协议区别和联系 (=)
上一片大致说了一下IOS上面委托和协议的区别和联系,并且举了一个简单的例子,但是例子比较简单,今天做一个用委托模拟button回调的例子。在一个自定义View上面放一个登陆按钮,并且这个LoginView里面有一个实现ILogin的委托对象,在登陆按钮的点击事件中调用需要实现的协议函数。在一个ViewController中实现ILgin协议,并实现log
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
后端码匠 后端码匠
7个月前
【Java】单点登陆
一、简介单点登陆:在多系统中单一位置登录可以实现多系统同时登录的一种技术。常在互联网应用和企业级平台中使用。第三方登陆:在某系统中使用其他系统的用户实现本系统登录的方式。如,在京东中使用微信登录。解决信息孤岛和用户不对等的实现方案。单点登陆需要解决的问题: