aboutsummaryrefslogtreecommitdiffstats
path: root/odl-aaa-moon/aaa/aaa-authn-sts/src/main/java/org/opendaylight/aaa/sts/TokenEndpoint.java
blob: a456d7023682ff3a11e9d27e1db0f92e3085cbea (plain)
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/*
 * Copyright (c) 2014, 2015 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

package org.opendaylight.aaa.sts;

import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_CREATED;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import static javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED;
import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.issuer.UUIDValueGenerator;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.apache.oltu.oauth2.common.message.types.TokenType;
import org.opendaylight.aaa.AuthenticationBuilder;
import org.opendaylight.aaa.ClaimBuilder;
import org.opendaylight.aaa.PasswordCredentialBuilder;
import org.opendaylight.aaa.api.Authentication;
import org.opendaylight.aaa.api.AuthenticationException;
import org.opendaylight.aaa.api.Claim;
import org.opendaylight.aaa.api.PasswordCredentials;

/**
 * Secure Token Service (STS) endpoint.
 *
 * @author liemmn
 *
 */
public class TokenEndpoint extends HttpServlet {
    private static final long serialVersionUID = 8272453849539659999L;

    private static final String DOMAIN_SCOPE_REQUIRED = "Domain scope required";
    private static final String NOT_IMPLEMENTED = "not_implemented";
    private static final String UNAUTHORIZED = "unauthorized";

    static final String TOKEN_GRANT_ENDPOINT = "/token";
    static final String TOKEN_REVOKE_ENDPOINT = "/revoke";
    static final String TOKEN_VALIDATE_ENDPOINT = "/validate";

    private transient OAuthIssuer oi;

    @Override
    public void init(ServletConfig config) throws ServletException {
        oi = new OAuthIssuerImpl(new UUIDValueGenerator());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            if (req.getServletPath().equals(TOKEN_GRANT_ENDPOINT)) {
                createAccessToken(req, resp);
            } else if (req.getServletPath().equals(TOKEN_REVOKE_ENDPOINT)) {
                deleteAccessToken(req, resp);
            } else if (req.getServletPath().equals(TOKEN_VALIDATE_ENDPOINT)) {
                validateToken(req, resp);
            }
        } catch (AuthenticationException e) {
            error(resp, SC_UNAUTHORIZED, e.getMessage());
        } catch (OAuthProblemException oe) {
            error(resp, oe);
        } catch (Exception e) {
            error(resp, e);
        }
    }

    private void validateToken(HttpServletRequest req, HttpServletResponse resp)
            throws IOException, OAuthSystemException {
        String token = req.getReader().readLine();
        if (token != null) {
            Authentication authn = ServiceLocator.getInstance().getTokenStore().get(token.trim());
            if (authn == null) {
                throw new AuthenticationException(UNAUTHORIZED);
            } else {
                ServiceLocator.getInstance().getAuthenticationService().set(authn);
                resp.setStatus(SC_OK);
            }
        } else {
            throw new AuthenticationException(UNAUTHORIZED);
        }
    }

    // Delete an access token
    private void deleteAccessToken(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        String token = req.getReader().readLine();
        if (token != null) {
            if (ServiceLocator.getInstance().getTokenStore().delete(token.trim())) {
                resp.setStatus(SC_NO_CONTENT);
            } else {
                throw new AuthenticationException(UNAUTHORIZED);
            }
        } else {
            throw new AuthenticationException(UNAUTHORIZED);
        }
    }

    // Create an access token
    private void createAccessToken(HttpServletRequest req, HttpServletResponse resp)
            throws OAuthSystemException, OAuthProblemException, IOException {
        Claim claim = null;
        String clientId = null;

        OAuthRequest oauthRequest = new OAuthRequest(req);
        // Any client credentials?
        clientId = oauthRequest.getClientId();
        if (clientId != null) {
            ServiceLocator.getInstance().getClientService()
                          .validate(clientId, oauthRequest.getClientSecret());
        }

        // Credential request...
        if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.PASSWORD.toString())) {
            String domain = oauthRequest.getScopes().iterator().next();
            PasswordCredentials pc = new PasswordCredentialBuilder().setUserName(
                    oauthRequest.getUsername()).setPassword(oauthRequest.getPassword())
                                                                    .setDomain(domain).build();
            if (!oauthRequest.getScopes().isEmpty()) {
                claim = ServiceLocator.getInstance().getCredentialAuth().authenticate(pc);
            }
        } else if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(
                GrantType.REFRESH_TOKEN.toString())) {
            // Refresh token...
            String token = oauthRequest.getRefreshToken();
            if (!oauthRequest.getScopes().isEmpty()) {
                String domain = oauthRequest.getScopes().iterator().next();
                // Authenticate...
                Authentication auth = ServiceLocator.getInstance().getTokenStore().get(token);
                if (auth != null && domain != null) {
                    List<String> roles = ServiceLocator.getInstance().getIdmService()
                                                       .listRoles(auth.userId(), domain);
                    if (!roles.isEmpty()) {
                        ClaimBuilder cb = new ClaimBuilder(auth);
                        cb.setDomain(domain); // scope domain
                        // Add roles for the scoped domain
                        for (String role : roles) {
                            cb.addRole(role);
                        }
                        claim = cb.build();
                    }
                }
            } else {
                error(resp, SC_BAD_REQUEST, DOMAIN_SCOPE_REQUIRED);
            }
        } else {
            // Support authorization code later...
            error(resp, SC_NOT_IMPLEMENTED, NOT_IMPLEMENTED);
        }

        // Respond with OAuth token
        oauthAccessTokenResponse(resp, claim, clientId);
    }

    // Build OAuth access token response from the given claim
    private void oauthAccessTokenResponse(HttpServletResponse resp, Claim claim, String clientId)
            throws OAuthSystemException, IOException {
        if (claim == null) {
            throw new AuthenticationException(UNAUTHORIZED);
        }
        String token = oi.accessToken();

        // Cache this token...
        Authentication auth = new AuthenticationBuilder(new ClaimBuilder(claim).setClientId(
                clientId).build()).setExpiration(tokenExpiration()).build();
        ServiceLocator.getInstance().getTokenStore().put(token, auth);

        OAuthResponse r = OAuthASResponse.tokenResponse(SC_CREATED).setAccessToken(token)
                                         .setTokenType(TokenType.BEARER.toString())
                                         .setExpiresIn(Long.toString(auth.expiration()))
                                         .buildJSONMessage();
        write(resp, r);
    }

    // Token expiration
    private long tokenExpiration() {
        return ServiceLocator.getInstance().getTokenStore().tokenExpiration();
    }

    // Emit an error OAuthResponse with the given HTTP code
    private void error(HttpServletResponse resp, int httpCode, String error) {
        try {
            OAuthResponse r = OAuthResponse.errorResponse(httpCode).setError(error)
                                           .buildJSONMessage();
            write(resp, r);
        } catch (Exception e1) {
            // Nothing to do here
        }
    }

    // Emit an error OAuthResponse for the given OAuth-related exception
    private void error(HttpServletResponse resp, OAuthProblemException e) {
        try {
            OAuthResponse r = OAuthResponse.errorResponse(SC_BAD_REQUEST).error(e)
                                           .buildJSONMessage();
            write(resp, r);
        } catch (Exception e1) {
            // Nothing to do here
        }
    }

    // Emit an error OAuthResponse for the given generic exception
    private void error(HttpServletResponse resp, Exception e) {
        try {
            OAuthResponse r = OAuthResponse.errorResponse(SC_INTERNAL_SERVER_ERROR)
                                           .setError(e.getClass().getName())
                                           .setErrorDescription(e.getMessage()).buildJSONMessage();
            write(resp, r);
        } catch (Exception e1) {
            // Nothing to do here
        }
    }

    // Write out an OAuthResponse
    private void write(HttpServletResponse resp, OAuthResponse r) throws IOException {
        resp.setStatus(r.getResponseStatus());
        PrintWriter pw = resp.getWriter();
        pw.print(r.getBody());
        pw.flush();
        pw.close();
    }
}