001
014
015 package com.liferay.portal.security.auth;
016
017 import com.liferay.portal.NoSuchUserException;
018 import com.liferay.portal.kernel.log.Log;
019 import com.liferay.portal.kernel.log.LogFactoryUtil;
020 import com.liferay.portal.kernel.util.Base64;
021 import com.liferay.portal.kernel.util.CharPool;
022 import com.liferay.portal.kernel.util.GetterUtil;
023 import com.liferay.portal.service.UserLocalServiceUtil;
024
025 import java.util.StringTokenizer;
026
027 import javax.servlet.http.HttpServletRequest;
028 import javax.servlet.http.HttpServletResponse;
029
030
062 public class BasicAuthHeaderAutoLogin implements AutoLogin {
063
064 public String[] login(
065 HttpServletRequest request, HttpServletResponse response)
066 throws AutoLoginException {
067
068 try {
069 String[] credentials = null;
070
071
072
073 String authorization = request.getHeader("Authorization");
074
075 if (authorization == null) {
076 return credentials;
077 }
078
079 StringTokenizer st = new StringTokenizer(authorization);
080
081 if (!st.hasMoreTokens()) {
082 return credentials;
083 }
084
085 String basic = st.nextToken();
086
087
088
089 if (!basic.equalsIgnoreCase(HttpServletRequest.BASIC_AUTH)) {
090 return credentials;
091 }
092
093 String encodedCredentials = st.nextToken();
094
095 if (_log.isDebugEnabled()) {
096 _log.debug("Encoded credentials are " + encodedCredentials);
097 }
098
099 String decodedCredentials = new String(
100 Base64.decode(encodedCredentials));
101
102 if (_log.isDebugEnabled()) {
103 _log.debug("Decoded credentials are " + decodedCredentials);
104 }
105
106 int pos = decodedCredentials.indexOf(CharPool.COLON);
107
108 if (pos == -1) {
109 return credentials;
110 }
111
112 long userId = GetterUtil.getLong(
113 decodedCredentials.substring(0, pos));
114 String password = decodedCredentials.substring(pos + 1);
115
116 try {
117 UserLocalServiceUtil.getUserById(userId);
118
119 credentials = new String[3];
120
121 credentials[0] = String.valueOf(userId);
122 credentials[1] = password;
123 credentials[2] = Boolean.TRUE.toString();
124 }
125 catch (NoSuchUserException nsue) {
126 if (_log.isWarnEnabled()) {
127 _log.warn(userId + " is not a valid user id");
128 }
129 }
130
131 return credentials;
132 }
133 catch (Exception e) {
134 throw new AutoLoginException(e);
135 }
136 }
137
138 private static Log _log = LogFactoryUtil.getLog(
139 BasicAuthHeaderAutoLogin.class);
140
141 }