1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package fr.paris.lutece.plugins.mylutece.modules.saml.authentication.engine;
35
36 import fr.paris.lutece.plugins.mylutece.modules.saml.authentication.config.Constants;
37 import fr.paris.lutece.plugins.mylutece.modules.saml.authentication.exceptions.SAMLTokenExtractorException;
38 import fr.paris.lutece.portal.service.util.AppLogService;
39
40 import org.opensaml.Configuration;
41
42 import org.opensaml.saml2.core.Response;
43
44 import org.opensaml.xml.io.Unmarshaller;
45 import org.opensaml.xml.io.UnmarshallerFactory;
46 import org.opensaml.xml.io.UnmarshallingException;
47 import org.opensaml.xml.parse.BasicParserPool;
48 import org.opensaml.xml.parse.XMLParserException;
49 import org.opensaml.xml.util.Base64;
50
51 import org.w3c.dom.Document;
52 import org.w3c.dom.Element;
53
54 import java.io.StringReader;
55 import java.io.UnsupportedEncodingException;
56
57 import javax.servlet.http.HttpServletRequest;
58
59
60 public class SAMLTokenExtractor implements Constants
61 {
62
63
64
65
66
67
68 public static Response extractSAMLResponse( HttpServletRequest request )
69 throws SAMLTokenExtractorException
70 {
71 Response response = null;
72
73
74 String SAMLResponseB64Str = request.getParameter( SAML_RESPONSE_REQUEST_PARAM );
75
76
77 String SAMLResponseStr = null;
78
79 try
80 {
81 SAMLResponseStr = new String( Base64.decode( SAMLResponseB64Str ), "UTF-8" );
82 }
83 catch ( UnsupportedEncodingException e1 )
84 {
85 String message = "Mauvais encodage de la Response : " + e1.getLocalizedMessage( );
86 AppLogService.info( message );
87 throw new SAMLTokenExtractorException( message );
88 }
89
90
91 BasicParserPool ppMgr = new BasicParserPool( );
92 ppMgr.setNamespaceAware( true );
93
94 Document inCommonMDDoc;
95
96 try
97 {
98 inCommonMDDoc = ppMgr.parse( new StringReader( SAMLResponseStr ) );
99
100 Element ResponseRoot = inCommonMDDoc.getDocumentElement( );
101
102
103 UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory( );
104 Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller( ResponseRoot );
105
106
107
108 response = (Response) unmarshaller.unmarshall( ResponseRoot );
109 }
110 catch ( XMLParserException e )
111 {
112 String message = "Erreur de parsing de la SAMLResponse : " + e.getLocalizedMessage( );
113 AppLogService.info( message );
114 throw new SAMLTokenExtractorException( message );
115 }
116 catch ( UnmarshallingException e )
117 {
118 String message = "Erreur de unmarshalling de la SAMLResponse : " + e.getLocalizedMessage( );
119 AppLogService.info( message );
120 throw new SAMLTokenExtractorException( message );
121 }
122
123 return response;
124 }
125 }