Project

General

Profile

« Previous | Next » 

Revision 59615

service registration with keys enabled

View differences:

modules/dnet-openaire-users/trunk/src/main/java/eu/dnetlib/openaire/usermanagement/RegisteredServicesServlet.java
1 1
package eu.dnetlib.openaire.usermanagement;
2 2

  
3
import com.google.gson.Gson;
4
import com.google.gson.GsonBuilder;
3 5
import eu.dnetlib.openaire.user.pojos.RegisteredService;
4 6
import eu.dnetlib.openaire.usermanagement.utils.RegisteredServicesUtils;
5 7
import eu.dnetlib.openaire.usermanagement.utils.TokenUtils;
......
51 53
        try {
52 54
            registeredServices = registeredServicesUtils.
53 55
                    getRegisteredServiceDao().fetchAllRegisteredServicesByOwner(userId);
56
            System.out.println("LOAD REGISTERED SERVICES. " + registeredServices);
54 57

  
55 58

  
56 59
        } catch (SQLException sqle) {
......
62 65
        }
63 66

  
64 67
        Map<String, ServiceResponse> serviceResponses = new HashMap<>();
68
        Map<String, String> serviceKey = new HashMap<>();
69

  
65 70
        for (RegisteredService registeredService:registeredServices) {
66
            serviceResponses.put(registeredService.getId(),
67
                    TokenUtils.getRegisteredService(registeredService.getAai_id(),authentication.getAccessTokenValue()));
71
            ServiceResponse serviceResponse = TokenUtils.getRegisteredService(registeredService.getAai_id(),authentication.getAccessTokenValue());
72
            serviceResponses.put(registeredService.getId(), serviceResponse);
73
            serviceKey.put(registeredService.getId(), extractPublicKeySet(serviceResponse));
68 74
        }
69 75

  
70 76
        boolean reachedLimit = reachedMaximumNumberOfServices(registeredServices);
71 77
        request.getSession().setAttribute("reachedLimit", reachedLimit);
72 78
        request.getSession().setAttribute("test", "TEST");
79
        System.out.println("REACHED LIMIT??? " + reachedLimit);
73 80

  
81

  
74 82
        request.getSession().setAttribute("services", serviceResponses);
83
        request.getSession().setAttribute("keys", serviceKey);
75 84
        request.getSession().setAttribute("registeredServices", registeredServices);
76 85
        response.setContentType("text/html");
77 86
        request.getRequestDispatcher("./registeredServices.jsp").include(request, response);
78 87
    }
79 88

  
89
    private String extractPublicKeySet(ServiceResponse serviceResponse) {
90
        if (serviceResponse.getJwksUri()!=null && !serviceResponse.getJwksUri().isEmpty())
91
            return serviceResponse.getJwksUri();
92

  
93
        return extractJSONJwk(serviceResponse.getJwks());
94
    }
95

  
96
    private String extractJSONJwk(Jwks jwks) {
97
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
98
        System.out.println(gson.toJson(jwks));
99
        return gson.toJson(jwks);
100
    }
101

  
80 102
    @Override
81 103
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
82 104
        OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.
modules/dnet-openaire-users/trunk/src/main/java/eu/dnetlib/openaire/usermanagement/ServiceRequest.java
148 148

  
149 149
    }
150 150
}
151

  
151 152
class Jwks implements Serializable {
152 153
    Key[] keys = new Key[]{new Key()};
153 154
}
154 155

  
155
class Key  implements Serializable {
156
class Key implements Serializable {
157
 /*   String kty;
158
    String e;
159
    String kid;
160
    String alg;
161
    String n;
162

  
163
    public String getKty() {
164
        return kty;
165
    }
166

  
167
    public void setKty(String kty) {
168
        this.kty = kty;
169
    }
170

  
171
    public String getE() {
172
        return e;
173
    }
174

  
175
    public void setE(String e) {
176
        this.e = e;
177
    }
178

  
179
    public String getKid() {
180
        return kid;
181
    }
182

  
183
    public void setKid(String kid) {
184
        this.kid = kid;
185
    }
186

  
187
    public String getAlg() {
188
        return alg;
189
    }
190

  
191
    public void setAlg(String alg) {
192
        this.alg = alg;
193
    }
194

  
195
    public String getN() {
196
        return n;
197
    }
198

  
199
    public void setN(String n) {
200
        this.n = n;
201
    }
202
*/
203

  
156 204
    String kty = "RSA";
157 205
    String e = "AQAB";
158 206
    String kid = "05794a3c-a6f5-430c-9822-da4e53597ba5";
modules/dnet-openaire-users/trunk/src/main/java/eu/dnetlib/openaire/usermanagement/RegisterServiceServlet.java
1 1
package eu.dnetlib.openaire.usermanagement;
2 2

  
3 3
import com.google.gson.Gson;
4
import com.google.gson.GsonBuilder;
4 5
import eu.dnetlib.openaire.user.pojos.RegisteredService;
5 6
import eu.dnetlib.openaire.usermanagement.utils.RegisteredServicesUtils;
6 7
import eu.dnetlib.openaire.usermanagement.utils.TokenUtils;
8
import org.apache.commons.validator.routines.UrlValidator;
7 9
import org.apache.log4j.Logger;
8 10
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
9 11
import org.springframework.beans.factory.annotation.Autowired;
......
16 18
import javax.servlet.http.HttpServletRequest;
17 19
import javax.servlet.http.HttpServletResponse;
18 20
import java.io.IOException;
21
import java.net.URL;
19 22
import java.sql.SQLException;
20 23

  
21 24

  
......
40 43

  
41 44
    public void doPost(HttpServletRequest request, HttpServletResponse response)
42 45
            throws ServletException, IOException {
46

  
47
        //TODO check user's limit
48

  
43 49
        response.setContentType("text/html");
44 50

  
45 51
        String name = request.getParameter("first_name").trim();
46 52
        String description = request.getParameter("description").trim();
47 53

  
54
        String keyType = request.getParameter("key_radio").trim();
55
        System.out.println("key type " + keyType);
56

  
57
/*
58
        if (keyType.equals("uri")) {
59
            String jwksUri = request.getParameter("uri");
60
            System.out.println("JWKS URI " + jwksUri);
61
            UrlValidator urlValidator = new UrlValidator();
62
            if (!urlValidator.isValid(jwksUri)){
63
                request.getSession().setAttribute("msg_key_uri_error_display", "display:block");
64
            }
65
        } else {
66
            String jwksString = request.getParameter("value");
67
            System.out.println("JWKS String " + jwksString);
68
            Gson gson = new GsonBuilder().registerTypeAdapter(Jwks.class, new ServiceResponseDeserializer()).create();
69
            Jwks jwks = gson.fromJson(jwksString, Jwks.class);
70
            System.out.println(jwks.keys);
71
            System.out.println(jwks.keys.length);
72
        }
73
*/
74

  
48 75
        OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
49 76
        String userid = authentication.getSub();
50 77
        String email = authentication.getUserInfo().getEmail();
modules/dnet-openaire-users/trunk/src/main/java/eu/dnetlib/openaire/usermanagement/utils/TokenUtils.java
16 16
import org.apache.http.impl.client.CloseableHttpClient;
17 17
import org.apache.http.impl.client.HttpClients;
18 18
import org.apache.log4j.Logger;
19
import org.springframework.beans.factory.annotation.Value;
19 20
import org.springframework.http.HttpStatus;
20 21

  
21 22
import javax.xml.ws.Service;
......
23 24
import java.io.UnsupportedEncodingException;
24 25
import java.lang.reflect.Type;
25 26
import java.nio.charset.StandardCharsets;
27
import java.util.Base64;
26 28
import java.util.List;
27 29

  
28 30
public class TokenUtils {
29 31

  
30
    Logger logger = Logger.getLogger(TokenUtils.class);
32
    private Logger logger = Logger.getLogger(TokenUtils.class);
31 33

  
32 34
    public static String registerService(String userId, String name, String description, String email, String accessToken)
33 35
            throws IOException {
modules/dnet-openaire-users/trunk/src/main/java/eu/dnetlib/openaire/usermanagement/PersonalTokenServlet.java
12 12
import org.apache.http.impl.client.HttpClients;
13 13
import org.apache.http.message.BasicNameValuePair;
14 14
import org.apache.log4j.Logger;
15
import org.mitre.openid.connect.client.service.impl.StaticClientConfigurationService;
15 16
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
17
import org.springframework.beans.factory.annotation.Autowired;
16 18
import org.springframework.beans.factory.annotation.Value;
17 19
import org.springframework.security.access.prepost.PreAuthorize;
18 20
import org.springframework.security.core.context.SecurityContextHolder;
......
39 41
    @Value("${oidc.id}")
40 42
    private String id;
41 43

  
44
    @Autowired
45
    private StaticClientConfigurationService staticClientConfigurationService;
46

  
42 47
    private Logger logger = Logger.getLogger(PersonalTokenServlet.class);
43 48

  
44 49
    public void init(ServletConfig config) throws ServletException {
modules/dnet-openaire-users/trunk/src/main/java/eu/dnetlib/openaire/usermanagement/api/Test3Service.java
119 119
        params.add(new BasicNameValuePair("client_secret", secret));
120 120
        params.add(new BasicNameValuePair("grant_type", "refresh_token"));
121 121
        params.add(new BasicNameValuePair("refresh_token", refreshToken));
122
        params.add(new BasicNameValuePair("scope", "openid email profile offline_access"));
122
        params.add(new BasicNameValuePair("scope", "openid"));
123 123

  
124 124
        HttpResponse response = null;
125 125

  
......
166 166
        params.add(new BasicNameValuePair("client_secret", secret));
167 167
        params.add(new BasicNameValuePair("grant_type", "refresh_token"));
168 168
        params.add(new BasicNameValuePair("refresh_token", accessToken));
169
        params.add(new BasicNameValuePair("scope", "openid email profile"));
169
        params.add(new BasicNameValuePair("scope", "openid"));
170 170
        try {
171 171
            httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
172 172
            //Execute and get the response.
modules/dnet-openaire-users/trunk/src/main/webapp/registeredServices.jsp
19 19
    <link rel="icon" type="image/png" sizes="96x96" href="images/favicon//favicon-96x96.png">
20 20
    <link rel="icon" type="image/png" sizes="16x16" href="images/favicon/favicon-16x16.png">
21 21
    <link href="images/favicon/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
22
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
22 23
</head>
23 24
<body class="" style="">
24 25
<div class="uk-offcanvas-content uk-height-viewport">
......
116 117
                        </c:if>
117 118

  
118 119
                        <c:if test="${registeredServices.size() > 0}">
119
                        <!-- REGISTER FORM -->
120

  
120 121
                        <ul class="uk-list">
121 122
                            <li>
122 123
                                <div class="uk-grid uk-child-width-1-3 uk-text-muted">
......
125 126
                                    <div>Actions</div>
126 127
                                </div>
127 128
                            </li>
128
                            >>> ${registeredServices.size()}
129
                            ${services}
130
                            <c:forEach items="${registeredServices}" var="registeredService">
129
                            <c:forEach items="${registeredServices}" var="registeredService" varStatus="loop">
130
                            <c:set var="key" value="${registeredService.id}"/>
131 131
                            <li>
132 132
                                <hr class="uk-margin-remove-top">
133 133
                                <div class="uk-grid uk-child-width-1-3">
134 134
                                    <div ><a uk-toggle="target: #details${registeredService.id}; animation: uk-animation-fade">${registeredService.name} <span uk-icon="icon:info;ratio:0.7"></span></a>
135 135
                                    </div>
136
                                    <div>${registeredService.date}</div>
136
                                    <div><fmt:formatDate value="${registeredService.date}" pattern="dd-MM-yyyy HH:mm" /></div>
137 137
                                    <div>
138 138

  
139 139
                                        <a href="./editRegisteredService?id=${registeredService.id}"><span class="uk-margin-small-right" uk-icon="pencil" ></span>
......
158 158
                            </li>
159 159
                            <li id="details${registeredService.id}" hidden="hidden"  >
160 160
                                <div class="uk-alert">
161
                                    <p>Service Name: </p>
162
                                    <p>Service Description: </p>
163
                                    <p>Service Id:</p>
164
                                    <p>Creation Date:</p>
161
                                    <p><em>Name</em>: ${services[key].clientName}</p>
162
                                    <p><em>Description</em>: ${services[key].clientDescription}</p>
163
                                    <p><em>Scope</em>: openid</p>
164
                                    <p><em>Grant type</em>: client credentials</p>
165
                                    <p><em>Authentication Method</em>: Asymmetrically-signed JWT assertion</p>
166
                                    <p><em>Token Endpoint Authentication Signing Algorithm</em>: RSASSA using SHA-256 hash algorithm</p>
167
                                    <p><em>Public Key Set(*)</em>: <pre><code>${keys[key]}</code></pre></p>
168
                                    <p><em>Creation Date</em>: ${services[key].createdAt}</p>
169
                                    </p>
165 170
                                </div>
166 171
                            </li>
167 172
                            </c:forEach>
......
181 186
                                    </button>
182 187
                                </c:otherwise>
183 188
                            </c:choose>
189
                            <c:remove var="reachedLimit" scope="session"/>
184 190
                        </div>
185 191
                    </div>
186 192

  
modules/dnet-openaire-users/trunk/src/main/webapp/registerService.jsp
17 17
    <title>OpenAIRE - Register</title>
18 18
    <script src="./js/jquery.js"></script>
19 19
    <script src="./js/uikit.js"></script>
20
    <script src="./js/validation.js"></script>
21 20
    <script src="./js/uikit-icons-max.js"></script>
22 21
    <link rel="stylesheet" style="text/css" href="./css/theme.css">
23 22
    <link rel="stylesheet" style="text/css" href="./css/custom.css">
......
95 94
            <!-- CENTER SIDE -->
96 95
            <div class="uk-width-2-3@l uk-width-2-3@m">
97 96
                <h2 class="uk-h2 uk-margin-small-bottom">Add a new service</h2>
98
            <%--<div class="uk-text-meta uk-margin-large-bottom">Use the same credentials for all our services</div>--%>
99
                <h4 class="uk-h4">Please provide the basic information on your new service</h4>
100 97
                <div class="middle-box text-center loginscreen animated fadeInDown ">
101 98
                    <div class="k-width-1-1@m uk-width-1-1@s uk-text-center">
102 99
                        <!-- REGISTER FORM -->
103 100
                        <div id="registerForm">
104
                            <form action="registerService" method="POST" role="form" class="m-t" id="register_form">
101
                            <form action="registerService" method="POST" role="form" class="m-t uk-form-horizontal" id="register_form">
105 102
                                <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
106 103
                                <div class="alert alert-success" aria-hidden="true" style="display: none;"></div>
107 104
                                <div class="alert alert-danger" aria-hidden="true" style="display: none;"></div>
108 105
                                <span id="server_error" class="uk-text-danger uk-text-small uk-float-left">${message}</span>
109 106
                                <c:remove var="message" scope="session" />
110
                                <div class="form-group">
107
                                <h5 class="uk-h5">General</h5>
108
                                <div class="uk-margin">
109
                                    <label class="uk-form-label" for="form-horizontal-text">Name(*)</label>
111 110
                                    <span class="msg_first_name_error uk-text-danger uk-text-small uk-float-left" style='${msg_first_name_error_display}'>Please enter a name for your service.</span>
112
                                    <input id="first_name" name="first_name" type="text" placeholder="Name (*)" class="form-control" value=${first_name}></div>
111
                                    <input id="first_name" name="first_name" type="text" placeholder="Name (*)" class="form-control" value=${first_name}>
113 112
                                    <c:remove var="msg_first_name_error_display" scope="session" />
114 113
                                    <c:remove var="first_name" scope="session" />
115
                                <div class="form-group">
114
                                </div>
115
                                <div class="uk-margin">
116
                                    <label class="uk-form-label" for="form-horizontal-text">Description</label>
116 117
                                    <textarea id="description" name="description" type="textarea" placeholder="Description:" class="form-control uk-textarea" rows="3" value=${description}></textarea>
117 118
                                    <c:remove var="organization" scope="session" />
118
                                    <div class="uk-width-1-1 uk-grid-margin uk-first-column">
119
                                        <a type="submit" class="uk-button uk-button-default" href="./registeredServices">Cancel</a>
120
                                        <button type="submit" class="uk-button uk-button-primary" onclick="return validate();">Add new service</button>
119
                                </div>
120
                                <hr class="uk-margin-remove-top">
121
                                <h5 class="uk-h5">Access</h5>
122
                                <div class="uk-margin">
123
                                       <label class="uk-form-label" for="form-horizontal-text">Scope</label>
124
                                       <input disabled value="openid" class="uk-input"></input>
125
                                </div>
126
                                <div class="uk-margin">
127
                                       <label class="uk-form-label" for="form-horizontal-text">Grant Types</label>
128
                                       <input disabled value="client credentials" class="uk-input"></input>
129
                                </div>
130
                                <hr class="uk-margin-remove-top">
131
                                <h5 class="uk-h5">Credentials</h5>
132
                                <div class="uk-margin">
133
                                       <label class="uk-form-label" for="form-horizontal-text">Authentication Method</label>
134
                                       <input disabled value="Asymmetrically-signed JWT assertion" class="uk-input"></input>
135
                                </div>
136
                                <div class="uk-margin">
137
                                       <label class="uk-form-label" for="form-horizontal-text">Token Endpoint Authentication Signing Algorithm</label>
138
                                       <input disabled value="RSASSA using SHA-256 hash algorithm" class="uk-input"></input>
139
                                </div>
140
                                <div class="uk-margin">
141
                                    <label class="uk-form-label" for="form-horizontal-text">Public Key Set</label>
142

  
143
                                    <label><input class="uk-radio" type="radio" name="key_radio" value="value" checked>By Value</label>
144
                                    <label><input class="uk-radio" type="radio" name="key_radio" value="uri">By URI</label><br>
145

  
146
                                    <div id="value_input">
147
                                        <span class="msg_key_value_error uk-text-danger uk-text-small uk-float-left" style='${msg_key_value_error_display}'>Please provide a valid JSON.</span>
148
                                        <textarea id="value" name="value" type="textarea" placeholder='{"keys":[]}' class="form-control uk-textarea" rows="10"></textarea>
121 149
                                    </div>
150
                                    <div id="uri_input" style="display:none;">
151
                                        <span class="msg_key_uri_error uk-text-danger uk-text-small uk-float-left" style='${msg_key_uri_error_display}'>Please provide a valid URI.</span>
152
                                        <input id="uri" name="uri" type="text" placeholder="https://" class="form-control" value="${jwksUri}">
153
                                    </div>
122 154
                                </div>
155
                                <hr class="uk-margin-remove-top">
156
                                <div class="uk-width-1-1 uk-grid-margin uk-first-column">
157
                                    <a type="submit" class="uk-button uk-button-default" href="./registeredServices">Cancel</a>
158
                                    <button type="submit" class="uk-button uk-button-primary" onclick="return validate();">Add new service</button>
159
                                </div>
123 160
                            </form>
124 161
                        </div>
125 162
                        <!-- END OF REGISTER FORM -->
126 163
                        <script>
164
                            $('input[type=radio][name=key_radio]').change(function() {
165
                                if (this.value == 'uri') {
166
                                   $("#uri_input").show();
167
                                   $("#value_input").hide();
168

  
169
                                } else if (this.value == 'value') {
170
                                     $("#uri_input").hide();
171
                                     $("#value_input").show();
172
                                }
173
                            });
174

  
127 175
                            function validate() {
128
                                // Check if name is filled
176
                                var isValid = false;
129 177
                                if($("#first_name").val() != undefined) {
130 178
                                    if($.trim($("#first_name").val()).length <= 0) {
131 179
                                        $("#first_name").addClass('uk-input aai-form-danger');
......
135 183
                                        $(".msg_first_name_error").hide();
136 184
                                        $("#first_name").removeClass('aai-form-danger');
137 185
                                    }
138
                                    return true;
139 186
                                }
187

  
188
                                if ($('input[type=radio][name=key_radio]:checked').val()==='value') {
189
                                    isValid = validateJSON();
190
                                    if (!isValid) {
191
                                        $("#value_input").addClass('uk-input aai-form-danger');
192
                                        $(".msg_key_value_error_display").show();
193
                                        return false;
194
                                    }
195
                                }
196

  
197
                                if ($('input[type=radio][name=key_radio]:checked').val()==='uri') {
198
                                    isValid = validateURI();
199
                                    if (!isValid) {
200
                                        $("#uri_input").addClass('uk-input aai-form-danger');
201
                                        $(".msg_key_uri_error_display").show();
202
                                        return false;
203
                                    }
204
                                }
205

  
140 206
                            }
207

  
208
                            function validateJSON() {
209
                                if ($("#value").val() != undefined && $("#value").val()!=="") {
210
                                    if (/^[\],:{}\s]*$/.test($("#value").val().replace(/\\["\\\/bfnrtu]/g, '@').
211
                                        replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
212
                                        replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
213
                                            return true;
214

  
215
                                    } else {
216
                                        return false;
217
                                    }
218
                                }
219
                                return false;
220
                            }
221

  
222
                            function validateURI() {
223
                                if ($("#uri").val() != undefined && $("#uri").val()!=="") {
224
                                  var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
225
                                    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
226
                                    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
227
                                    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
228
                                    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
229
                                    '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
230
                                  return !!pattern.test($("#uri").val());
231
                                }
232
                                return false;
233
                            }
234

  
141 235
                            $("#first_name").focusin(function () {
142 236
                                $(this).removeClass('aai-form-danger');
143 237
                                $(".msg_first_name_error").fadeOut();
144 238
                            });
239

  
240
                            $("#value_input").focusin(function () {
241
                                $(this).removeClass('aai-form-danger');
242
                                $(".msg_key_value_error").fadeOut();
243
                            });
244

  
245
                            $("#uri_input").focusin(function () {
246
                                $(this).removeClass('aai-form-danger');
247
                                $(".msg_key_uri_error").fadeOut();
248
                            });
145 249
                        </script>
146 250
                    </div>
147 251
                    </ul>

Also available in: Unified diff