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

A*(star)算法原理讲解以及程序实现(基于Python)

本文将以迷宫探索最优路径为例,讲解A *搜索算法原理及其程序实现。在原理讲解部分,首先从为什么要使用A *搜索算法和A *搜索算法的全局最优逻辑出发,讲解A *算法的原理。其次对A *的行动函数g(n)和启发函数h(n)的细节进行了讲解说明,并补充了启发函数的选择对于A *算法的影响。在程序实现部分,首先从程序流程框图出发,解释A *算法的流程。其次按函数的类划分并讲解主要代码,接着展示程序的运行结果,最后对A *算法进行总结分析。

m0_73366745的博客 8282

帮我用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

Vivado2022.2下载安装

链接:https://pan.baidu.com/s/1lyfE2d-VmaWC-_aR8ratCQ提取码:mt09。

weixin_61081689的博客 2万+

MySQL等保三级合规实践:如何安全配置root账户的本地与受信主机登录策略

本文详细介绍了MySQL在等保三级合规框架下如何安全配置root账户的本地与受信主机登录策略。通过分析root账户的特殊保护需求,提供三种安全加固方案,包括限制访问范围、限定登录IP和完全禁止远程登录,并指导创建安全的远程管理账户。文章还涵盖了密码策略强化、日志审计配置和网络层防护等关键合规要求,帮助用户实现MySQL的等保三级全面合规。

weixin_42522964的博客 260

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

springboot security saml2

LuckyTHP 8497

Jetson Nano(1)——笔记本电脑控制

笔记本电脑控制Jetson Nano没有显示屏如何控制Jetson Nano一、使用ssh客户端连接到Jetson Nano的命令端1.将电脑的网线口和jetson nano的网线口通过网线连接2.在控制面版中打开“更改配适器设置”3.查找jetson nano的ip地址4.利用putty链接二、远程桌面配置 没有显示屏如何控制Jetson Nano Jetson Nano相当于一个微型电脑,能快...

weixin_43619070的博客 1万+

基于SAML的单点登录介绍

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

weixin_34198453的博客 1857

从零开始,用Cadence Virtuoso手把手仿真一个1.5V LDO(附完整电路与仿真脚本)

本文详细介绍了如何使用Cadence Virtuoso从零开始仿真一个1.5V LDO,包括环境准备、电路导入、Testbench构建、核心仿真类型分析以及高级调试技巧。通过完整的电路与仿真脚本,帮助读者掌握LDO设计与仿真的关键技术,提升电路设计能力。

weixin_31309419的博客 445

海康Visionmaster-全局脚本:VM 加载方案后自动执行 的方法,如何让VM在方案加载后自动执行流程?

海康Visionmaster-全局脚本:VM 加载方案后自动执行 的方法,如何让VM在方案加载后自动执行流程?

视觉人机器视觉的博客 2037

SAML2协议的讲解与应用

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

kkkkm1的博客 3712

《QGIS快速入门与应用基础》108:CGCS2000对应的投影坐标系

本文详细解析了CGCS2000地理坐标系对应的各类投影坐标系,包括高斯-克吕格3°带/6°带、UTM、地方独立投影和Web墨卡托投影。文章系统阐述了各投影类型的分带规则、参数设置、精度特性及适用场景,并提供了EPSG编码对照表和QGIS操作指南。通过"基准+投影"的绑定机制,这些投影坐标系实现了平面坐标与经纬度的精准转换,满足从大比例尺工程测量到Web地图服务等不同应用需求。内容涵盖投影原理、坐标格式、变形控制等关键技术要点,为GIS开发者和测绘人员提供了实用的参考信息。

LuckyHanMo的博客 543

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

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

Larry的博客 3943

【EB_Tresos专题】-01-EB Tresos导入工程

<--返回「Autosar_BSW高阶配置」总目录--> <--返回「Autosar_BSW高阶配置」专栏主页--> <--返回「个人博客」首页--> <--返回「Autosar_BSW高阶配置」总目录--> <--返回「Autosar_BSW高阶配置」专栏主页--> <--返回「个人博客」首页--> 结尾 ...

「汽车电子助手」的博客 6436

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

什么是 SAML 断言?

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

yuzijiang11111的博客 752

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

SAML 流程讲解

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

sinat_33822516的博客 1万+

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

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、付费专栏及课程。

余额充值