SAML2发送断言

 

已经认证的用户,直接向应用发送断言

 

package com.xxx;

 

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.joda.time.DateTime;
import org.opensaml.Configuration;
import org.opensaml.saml2.core.*;
import org.opensaml.saml2.core.impl.AssertionBuilder;
import org.opensaml.saml2.core.impl.ResponseBuilder;
import org.opensaml.saml2.metadata.AssertionConsumerService;
import org.opensaml.saml2.metadata.Endpoint;
import org.opensaml.xml.XMLObjectBuilderFactory;
import org.opensaml.xml.security.CriteriaSet;
import org.opensaml.xml.security.credential.Credential;
import org.opensaml.xml.security.credential.CredentialResolver;
import org.opensaml.xml.security.credential.UsageType;
import org.opensaml.xml.security.criteria.EntityIDCriteria;
import org.opensaml.xml.security.criteria.UsageCriteria;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

 

import com.xxx.saml.idp.BindingAdapter;
import com.xxx.saml.idp.IdpConfiguration;
import com.xxx.saml.idp.UIASAttributeStatementGenerator;
import com.xxx.saml.util.IDService;
import com.xxx.saml.util.TimeService;
import com.xxx.saml.xml.AttributeStatementGenerator;
import com.xxx.saml.xml.AuthnStatementGenerator;
import com.xxx.saml.xml.EndpointGenerator;
import com.xxx.saml.xml.IssuerGenerator;
import com.xxx.saml.xml.StatusGenerator;
import com.xxx.saml.xml.SubjectGenerator;
import com.xxx.uias.userInfo.pojo.Privilege;

 

public class TestServlet extends HttpServlet {
 private static final long serialVersionUID = 2572744487603163969L;

 private final XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
 private TimeService timeService = new TimeService();
 private IDService idService = new IDService();
 
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  this.doPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  try {
   request.setCharacterEncoding("utf-8");  //设置编码
   response.setContentType("text/html; charset=utf-8");
   
   String appCode = "demo333";
   String issuingEntityName = "UIAS";
   
   String acURL = "http://172.16.15.109:5050/aaa/samlsp/acService";
   int validForInSeconds = 300;
   String username = "testccc";
   String ip = "172.16.15.109";
   String inResponseTo = "";
   
   DateTime authnInstant = new DateTime(System.currentTimeMillis());
   
   AuthnStatementGenerator authnStatementGenerator = new AuthnStatementGenerator();
   AttributeStatementGenerator attributeStatementGenerator = new AttributeStatementGenerator();
   
   IssuerGenerator issuerGenerator = new IssuerGenerator(issuingEntityName);
   SubjectGenerator subjectGenerator = new SubjectGenerator(timeService);
   StatusGenerator statusGenerator = new StatusGenerator();
   
   
   //1.生成authResponse
   EndpointGenerator endpointGenerator = new EndpointGenerator();
   Endpoint endpoint = endpointGenerator.generateEndpoint(AssertionConsumerService.DEFAULT_ELEMENT_NAME, acURL, null);
   
   
   //2.
   ResponseBuilder responseBuilder = (ResponseBuilder) builderFactory.getBuilder(Response.DEFAULT_ELEMENT_NAME);
   Response authResponse = responseBuilder.buildObject();
   Issuer responseIssuer = issuerGenerator.generateIssuer();
   
   AssertionBuilder assertionBuilder = (AssertionBuilder)builderFactory.getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
   Assertion assertion = assertionBuilder.buildObject();
   
   Subject subject = subjectGenerator.generateSubject(acURL, validForInSeconds, username, inResponseTo, ip);
   
   Issuer issuer = issuerGenerator.generateIssuer();
   
   AuthnStatement authnStatement = authnStatementGenerator.generateAuthnStatement(authnInstant);
   
   assertion.setIssuer(issuer);
   assertion.setSubject(subject);
   assertion.setID(idService.generateID());
   assertion.setIssueInstant(timeService.getCurrentDateTime());
   assertion.getAuthnStatements().add(authnStatement);
   
   //权限
         Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();;
         for(Privilege p: Privilege.values()){
          authorities.add(new SimpleGrantedAuthority("ROLE_" + p.name()));
   }
   assertion.getAttributeStatements().add(attributeStatementGenerator.generateAttributeStatement(authorities));
   
   //其他属性
   UIASAttributeStatementGenerator attrState = new UIASAttributeStatementGenerator();
   Map<String, String> attrMap = new HashMap<String, String>();
   attrMap.put("appCode", appCode);
   attrMap.put("name", "张三");
   assertion.getAttributeStatements().add(attrState.generateAttributeStatement(attrMap));
   
   
   authResponse.getAssertions().add(assertion);
   authResponse.setIssuer(responseIssuer);
   authResponse.setID(idService.generateID());
   authResponse.setIssueInstant(timeService.getCurrentDateTime());
   authResponse.setInResponseTo(inResponseTo);
   authResponse.setDestination(acURL);
   authResponse.setStatus(statusGenerator.generateStatus(StatusCode.SUCCESS_URI));
   
   //JKS
   CriteriaSet criteriaSet = new CriteriaSet();
   criteriaSet.add(new EntityIDCriteria(issuingEntityName));
   criteriaSet.add(new UsageCriteria(UsageType.SIGNING));
   CredentialResolver credentialResolver = IdpConfiguration.buildJKSCredentialResolver();
   Credential signingCredential = credentialResolver.resolveSingle(criteriaSet);
   
   
   BindingAdapter adapter = IdpConfiguration.buildBindingAdapter();
   adapter.sendSAMLMessage(authResponse, endpoint, signingCredential, response);
   
   
   
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 
 

}

 

 

 

 

 

该发送类为参考:

import java.io.PrintWriter;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import java.util.List;

import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.X509EncodedKeySpec;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.opensaml.common.binding.BasicSAMLMessageContext;
import org.opensaml.saml2.binding.decoding.HTTPPostDecoder;
import org.opensaml.ws.message.MessageContext;
import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
import org.opensaml.saml2.core.Assertion;
import org.opensaml.saml2.core.Attribute;
import org.opensaml.saml2.core.AttributeStatement;
import org.opensaml.saml2.core.Response;
import org.opensaml.saml2.encryption.Decrypter;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.encryption.DecryptionException;
import org.opensaml.xml.encryption.InlineEncryptedKeyResolver;
import org.opensaml.xml.security.keyinfo.StaticKeyInfoCredentialResolver;
import org.opensaml.xml.security.x509.BasicX509Credential;
import org.opensaml.xml.signature.Signature;
import org.opensaml.xml.signature.SignatureValidator;
import org.opensaml.xml.validation.ValidationException;


public class ProcessSAML extends HttpServlet {
  
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        File signatureVerificationPublicKeyFile = new File("C:/IdPSigningCert.cer");
        File decryptionPrivateKeyFile = new File("C:/SPEncryptionCert.jks");
        String decryptionPrivateKeyName = "test";
        String decryptionPrivateKeyPassword = "test";

        try
        {
            //bootstrap the opensaml stuff
            org.opensaml.DefaultBootstrap.bootstrap();

            // get the message context
            MessageContext messageContext = new BasicSAMLMessageContext();
            messageContext.setInboundMessageTransport(new HttpServletRequestAdapter(request));
            HTTPPostDecoder samlMessageDecoder = new HTTPPostDecoder();
            samlMessageDecoder.decode(messageContext);

            // get the SAML Response
            Response samlResponse = (Response)messageContext.getInboundMessage();

            //get the certificate from the file
            InputStream inputStream2 = new FileInputStream(signatureVerificationPublicKeyFile);
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            X509Certificate certificate = (X509Certificate)certificateFactory.generateCertificate(inputStream2);
            inputStream2.close();

            //pull out the public key part of the certificate into a KeySpec
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(certificate.getPublicKey().getEncoded());

            //get KeyFactory object that creates key objects, specifying RSA
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            //generate public key to validate signatures
            PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

            //create credentials
            BasicX509Credential publicCredential = new BasicX509Credential();

            //add public key value
            publicCredential.setPublicKey(publicKey);

            //create SignatureValidator
            SignatureValidator signatureValidator = new SignatureValidator(publicCredential);

            //get the signature to validate from the response object
            Signature signature = samlResponse.getSignature();

            //try to validate
            try
            {
                signatureValidator.validate(signature);
            }
            catch (ValidationException ve)
            {
                out.println("Signature is not valid.");
                out.println(ve.getMessage());
                return;
            }

            //no validation exception was thrown
            out.println("Signature is valid.");

            //start decryption of assertion

            //load up a KeyStore
            KeyStore keyStore = KeyStore.getInstance("JKS");
            keyStore.load(new FileInputStream(decryptionPrivateKeyFile), decryptionPrivateKeyPassword.toCharArray());

            RSAPrivateKey privateKey = (RSAPrivateKey) keyStore.getKey(decryptionPrivateKeyName, decryptionPrivateKeyPassword.toCharArray());

            //create the credential
            BasicX509Credential decryptionCredential = new BasicX509Credential();
            decryptionCredential.setPrivateKey(privateKey);

            StaticKeyInfoCredentialResolver skicr = new StaticKeyInfoCredentialResolver(decryptionCredential);

            //create a decrypter
            Decrypter decrypter = new Decrypter(null, skicr, new InlineEncryptedKeyResolver());

            //decrypt the first (and only) assertion
            Assertion decryptedAssertion;

            try
            {
                decryptedAssertion = decrypter.decrypt(samlResponse.getEncryptedAssertions().get(0));
            }
            catch (DecryptionException de)
            {
                out.println("Assertion decryption failed.");
                out.println(de.getMessage());
                return;
            }

            out.println("Assertion decryption succeeded.");

            //loop through the nodes to get the Attributes
            //this is where you would do something with these elements
            //to tie this user with your environment
            List attributeStatements = decryptedAssertion.getAttributeStatements();
            for (int i = 0; i < attributeStatements.size(); i++)
            {
                List attributes = attributeStatements.get(i).getAttributes();
                for (int x = 0; x < attributes.size(); x++)
                {
                    String strAttributeName = attributes.get(x).getDOM().getAttribute("Name");

                    List attributeValues = attributes.get(x).getAttributeValues();
                    for (int y = 0; y < attributeValues.size(); y++)
                    {
                        String strAttributeValue = attributeValues.get(y).getDOM().getTextContent();
                        out.println(strAttributeName + ": " + strAttributeValue + " ");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

    }

   
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

   
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

   
    @Override
    public String getServletInfo() {
        return "This servlet processes a SAML 2.0 Response.  It verifies the signature, " +
                "decrypts an assertion, and parses out the data in the attribute statements.  " +
                "If you use this code as a base for your implementation please leave the @author comment intact.  " +
                "You should add your own name in addition.";
    }

}

 

 

 

 

 

 

 

 

【SAML2.0】概念盲扫 saml概念盲扫,idp与sp的区别分析,saml的优势 阅读详情

相关推荐

SAML2.0协议中文翻译与详解

安全断言标记语言(SAML)2.0是一种基于XML的标准,旨在实现Web浏览器或其他基于HTTP的客户端之间的身份验证和授权数据交换。SAML通过提供一个框架,允许身份提供者(IdP)和服务提供者(SP)之间共享认证和授权信息,从而简化用户在多个系统间的登录过程。

weixin_42360846的博客 932

SAML2.0 笔记(二)

针对SAML2 的实际操作内容流程讲解

CoffeeAndIce的博客 5879

Xilinx Vivado LDPC IP core,TSN IP core. 各种IP core

Xilinx Vivado LDPC IP core,TSN IP core. 各种IP core

qq_1432825237的博客 3991

帮我用java写一段saml的idp程序

好的,我会尽力帮助你。 SAML(Security Assertion Markup Language)是一种常用的用于在不同组织之间交换身份验证和授权信息的XML-based标准。SAML IDP(Identify Provider)是提供身份验证服务的服务器,它可以向SAML SP(Service Provider)提供身份验证信息,使SP能够确定用户的身份。 在Java中实现SAML IDP...

weixin_35756892的博客 712

iTunes登录协议全解析:从抓包到签名验证(含HTTPDebugger避坑指南)

本文深入解析了iTunes登录协议的核心流程,包括sign-sap-setup-cert和sign-sap-setup-buffer等关键请求,并提供了使用HTTPDebugger等工具进行抓包分析时绕过反调试检测的实战技巧与避坑指南。文章详细拆解了PLIST编解码、请求签名验证机制及密码加密逻辑,为网络安全研究和协议逆向提供了完整的技术路径。

weixin_29224309的博客 331

基于FISCO BCOS 部署可升级的 Solidity存证智能合约

本文介绍了基于FISCOBCOS平台的可升级Solidity存证智能合约实现方案。采用透明代理模式,包含逻辑合约、代理合约和管理合约三部分,支持业务逻辑升级而不影响存储数据。详细阐述了合约架构设计、Solidity代码实现、Go SDK交互流程以及完整的部署升级步骤。方案具有数据持久性、版本兼容性和生产就绪等特点,提供了权限控制、输入验证等安全机制,并包含监控管理工具。该实现为企业级区块链存证应用提供了可靠的基础架构,支持后续功能扩展和定制化开发。

分享AI、区块链技术及应用,未来已来 1514

SAML单点登录-spring-security-saml 整合使用

springboot security saml2

LuckyTHP 8497

LVGL 实战:倒计时翻页钟

环境:LVGL 9.x + PC 模拟器。每个数字做成上下两半的卡片,秒变时用绕中缝翻页:上半旧页折叠下去、下半新页展开上来,配合阴影遮罩做出立体感。从 02:00 倒计时到 0,闪一下再重置。界面文案用英文(默认字体无中文)。

摸鱼专家 213

基于SAML的单点登录介绍

一、背景知识: SAML即安全断言标记语言,英文全称是Security Assertion Markup Language。它是一个基于XML的标准,用于在不同的安全域(security domain)之间交换认证和授权数据。在SAML标准定义了身份提供者(identity provider)和服务提供者(service provider),这两者构成了前面所说的不同的安全域。 SA...

weixin_34198453的博客 1857

B07:AI 时代怎么考核团队?我把 KPI 改了 5 版才找到答案

最后说一句掏心窝的话。绩效考核不是"管人"的工具,是"引导团队行为"的工具。你定什么指标,团队就会做什么行为。你定"AI 占比",团队就凑占比你定"效率提升",团队就挑软柿子你定"代码行数",团队就刷行数你定"工具使用率",团队就刷使用只有定"业务价值 + 工程质量 + 能力成长"三个维度的指标,团队才会真正关注长期价值。这套 KPI,我在我带的团队里跑了 6 个月,没有任何一个指标被"刷"出来。考核的是结果,不是过程。永远考核"创造了多少价值",永远不考核"用了多少 AI"。

刘一说的IT专栏 503

YOLOv11改进策略【卷积层】| TIP 2025 MFA 多阶段特征聚合 大核扩感受 + 多梯度融合,强效增强弱小目标特征

红外弱小目标尺寸极小、信噪比低,在特征传递中极易丢失信息;常规卷积感受野单一、梯度源不足,难以同时捕捉局部细节与全局上下文,导致小目标特征表达弱、检测漏检。因此提出多阶段特征聚合 MFA,用大核卷积+多分支+通道注意力强化小目标特征提取。

Limiiiing的博客 585

SAML2协议的讲解与应用

*SAML(Security Assertion Markup Language)**安全断言标记语言,是一个基于XML的、用于实现不同业务实体(即系统或服务)之间,交换安全信息(例如认证信息、授权信息、主体属性信息等)的标准协议。SAML协议是由OASIS组织最早在2002年被提出,已经经历了1.0、1.1、2.0三个版本。

kkkkm1的博客 3712

国科大学习资料--图像处理(彭思龙、杨戈)--2020年期末考试题解析(学长整理分析)

在对20年卷子分析前,先看看19年卷子的解析(后面有20年的变化,由于从核心课调整到了普及课,20年的卷子相对简单,但是还是有很多细节) 解析:(字写的不好别嫌弃!!!!) 20年的卷子 第一题:和19年基本一致,但是加了高斯核计算费用,要算一个节省计算成本比率,所以去多看看PPT 第二题:和19年基本一致,加了证明两个高斯卷积仍然是高斯卷积,相当于19年题2和3结合 第三题:采样定理,和19年基本一致,但要注意加了证明 第四题:考了形态学提取图像边界 第五题:直方图,和19年一

无名何许人的博客 4364

认证和授权系列主题:SAML2.0入门指南

本文转自:登高且赋 SAML,全称为Security Assertion Markup Language,是一种用于安全性断言的标记预压,目前的最新版本是2.0。原文地址 本系列相关文章:OAuth2.0 协议入门指南OpenID Connect 协议入门指南OpenSAML示例 SAML在单点登录中大有用处:在SAML协议中,一旦用户身份被主网站(身份鉴别服务器,Identity Provider,IDP)认证过后,该用户再去访问其他在主站注册过的应用(服务提供者,Service Provider

Larry的博客 3943

(三十九)Flask 多应用架构(Multiple Apps)与 DispatcherMiddleware 实战解析

(三十九)Flask 多应用架构(Multiple Apps)与 DispatcherMiddleware 实战解析

孤寒者的博客 1万+

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

什么是 SAML 断言?

SAML协议的核心功能包括断言,断言语句允许系统进行跨域的交互操作,支持为网站创建单点登录(SSO)和基于属性的用户身份认证等服务。SAMLSSO平衡了用户体验的便捷性和对Web应用的精细化权限控制。

yuzijiang11111的博客 752

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

SAML 流程讲解

SAML(Security Assert Mark Language)常用来实现SSO。 本文主要梳理一下SAML的代码逻辑 术语讲解: IDP: Identity provider 在单点登陆中是指统一身份认证平台。 SP:Service Provider 在单点登陆中是指需要被认证的服务方。 Assert: 断言,是指IDP 认证用户后,发送认证结果给SP的一种形式...

sinat_33822516的博客 1万+

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

SAML2.0 从零到壹最佳实践

前言 SAML协议是一个比较复杂的协议,有很多文章介绍了SAML协议的基础知识,但是如何SAML协议如何实现,如何配置一个SAML的SP服务方,提供一个支持调试的SAML的认证服务(IDP),缺乏一个深入浅出的介绍系统性的介绍。 本博客详细介绍了SAML协议的基础概念,实现,相关的DEMO以及提供调试的IDP。 需要知道的基础概念 首先需要了解几个基本的服务方: IDP:账号认证的服务方,如赛赋I...

eastyy的博客 3127

sso saml_使用签名的SAML断言实现身份提供者发起的SSO

随着越来越多的机构和组织在线提供服务和协作,员工需要访问内部部署和基于云的应用程序来进行日常工作。 这就要求实现单一登录(SSO)基础结构,使用户可以登录一次即可访问所有授权的内部和外部资源及应用程序。 具有大量Salesforce用户群的组织可以利用其现有的SSO基础结构将其实施到Force.com平台,该平台支持由外部SSO身份提供商提供的联合身份管理。 Force.com平台支持SSO的...

cuxiong8996的博客 2875

基于 SAML 2.0 的 WebSphere Application Server SSO 实现

转自:http://www.ibm.com/developerworks/cn/websphere/library/techarticles/1111_luol_sso/1111_luol_sso.html SAML 2.0 简介 SAML(Security Assertion Markup Language) 安全断言标记语言是由标识化组织 OASIS 提出的用于安全互操作的标准。S

jenyzhang的专栏 5079

SuccessFactors OData OAuth with SAP IAS-generated SAML assertion

注意: 这个时候是访问sf的地址,不是iAS的地址, 比如中国就是http://api15preview.sapsf.cn,这个是开发系统,生产环境去掉preview,注意这里的Your SF API endpoint是sf的地址,company_id是sf公司名称,client_id是sf系统的api_key,就是下图中的api_key,access token就是步骤二生成的。:sap有7朵云,那么这7个应用系统是不是可以通过一套系统登录,这7朵云都免密登录,这个idp就是架在7朵云之前的系统。

wl8511的博客 1844

如何理解 SAML2 协议

Authing 带你理解 SAML2 协议。

Authing的博客 1683

SAML- 安全断言标记语言

SAMl、SSO、身份认证和授权、单点登录

weixin_42638711的博客 958

saml2.0 java 例子_saml2.0(主要是idp端开发)

附上大佬文章:https://www.jianshu.com/p/d041935641b4https://www.jianshu.com/p/6f61fa7be0b6https://www.jianshu.com/p/6c72408fa480看了大佬的文章和demo基本能搞出来一套本地可用的saml2.0。在我开发过程中主要是我们作为IDP,做统一登录后发送给第三方SP做免登录。主要就几个过程:1...

weixin_42104366的博客 2789
上一篇: 下载jar包
下一篇: 查看js对象属性及函数
chun521
博客等级 码龄20年 11粉丝 144原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值