Remove ServiceLocator
[aaa.git] / aaa-shiro / impl / src / main / java / org / opendaylight / aaa / shiro / tokenauthrealm / auth / HttpBasicAuth.java
1 /*
2  * Copyright (c) 2014, 2017 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.aaa.shiro.tokenauthrealm.auth;
10
11 import java.util.Base64;
12 import java.util.List;
13 import java.util.Map;
14 import org.opendaylight.aaa.api.Authentication;
15 import org.opendaylight.aaa.api.AuthenticationException;
16 import org.opendaylight.aaa.api.Claim;
17 import org.opendaylight.aaa.api.CredentialAuth;
18 import org.opendaylight.aaa.api.PasswordCredentials;
19 import org.opendaylight.aaa.api.TokenAuth;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22
23 /**
24  * An HTTP Basic authenticator. Note that this is provided as a Hydrogen
25  * backward compatible authenticator, but usage of this authenticator or HTTP
26  * Basic Authentication is highly discouraged due to its vulnerability.
27  *
28  * <p>
29  * To obtain a token using the HttpBasicAuth Strategy, add a header to your HTTP
30  * request in the form:
31  * <code>Authorization: Basic BASE_64_ENCODED_CREDENTIALS</code>
32  *
33  * <p>
34  * Where <code>BASE_64_ENCODED_CREDENTIALS</code> is the base 64 encoded value
35  * of the user's credentials in the following form: <code>user:password</code>
36  *
37  * <p>
38  * For example, assuming the user is "admin" and the password is "admin":
39  * <code>Authorization: Basic YWRtaW46YWRtaW4=</code>
40  *
41  * @author liemmn
42  */
43 public class HttpBasicAuth implements TokenAuth {
44
45     public static final String AUTH_HEADER = "Authorization";
46
47     public static final String AUTH_SEP = ":";
48
49     public static final String BASIC_PREFIX = "Basic ";
50
51     // TODO relocate this constant
52     public static final String DEFAULT_DOMAIN = "sdn";
53
54     /**
55      * username and password.
56      */
57     private static final int NUM_HEADER_CREDS = 2;
58
59     /**
60      * username, password and domain.
61      */
62     private static final int NUM_TOKEN_CREDS = 3;
63
64     private static final Logger LOG = LoggerFactory.getLogger(HttpBasicAuth.class);
65
66     private final CredentialAuth<PasswordCredentials> credentialAuth;
67
68     public HttpBasicAuth(CredentialAuth<PasswordCredentials> credentialAuth) {
69         this.credentialAuth = credentialAuth;
70     }
71
72     private static boolean checkAuthHeaderFormat(final String authHeader) {
73         return authHeader != null && authHeader.startsWith(BASIC_PREFIX);
74     }
75
76     private static String extractAuthHeader(final Map<String, List<String>> headers) {
77         return headers.get(AUTH_HEADER).get(0);
78     }
79
80     private static String[] extractCredentialArray(final String authHeader) {
81         return new String(Base64.getDecoder().decode(authHeader.substring(BASIC_PREFIX.length())))
82                 .split(AUTH_SEP);
83     }
84
85     private static boolean verifyCredentialArray(final String[] creds) {
86         return creds != null && creds.length == NUM_HEADER_CREDS;
87     }
88
89     private static String[] addDomainToCredentialArray(final String[] creds) {
90         String[] newCredentialArray = new String[NUM_TOKEN_CREDS];
91         System.arraycopy(creds, 0, newCredentialArray, 0, creds.length);
92         newCredentialArray[2] = DEFAULT_DOMAIN;
93         return newCredentialArray;
94     }
95
96     private static Authentication generateAuthentication(
97             CredentialAuth<PasswordCredentials> credentialAuth, final String[] creds)
98             throws ArrayIndexOutOfBoundsException {
99         final PasswordCredentials pc = new PasswordCredentialBuilder().setUserName(creds[0])
100                 .setPassword(creds[1]).setDomain(creds[2]).build();
101         final Claim claim = credentialAuth.authenticate(pc);
102         return new AuthenticationBuilder(claim).build();
103     }
104
105     @Override
106     public Authentication validate(final Map<String, List<String>> headers)
107             throws AuthenticationException {
108         if (headers.containsKey(AUTH_HEADER)) {
109             final String authHeader = extractAuthHeader(headers);
110             if (checkAuthHeaderFormat(authHeader)) {
111                 // HTTP Basic Auth
112                 String[] creds = extractCredentialArray(authHeader);
113                 // If no domain was supplied then use the default one, which is
114                 // "sdn".
115                 if (verifyCredentialArray(creds)) {
116                     creds = addDomainToCredentialArray(creds);
117                 }
118                 // Assumes correct formatting in form Base64("user:password").
119                 // Throws an exception if an unknown format is used.
120                 try {
121                     return generateAuthentication(this.credentialAuth, creds);
122                 } catch (ArrayIndexOutOfBoundsException e) {
123                     final String message = "Login Attempt in Bad Format."
124                             + " Please provide user:password in Base64 format.";
125                     LOG.info(message);
126                     throw new AuthenticationException(message);
127                 }
128             }
129         }
130         return null;
131     }
132 }