KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > util > HttpAuth


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9  */

10 package org.mmbase.util;
11
12 /**
13  * @javadoc
14  * @author vpro
15  * @application SCAN - used for authentication by JamesServlet
16  * @deprecated should be done by implementing and using the MMBase security Authorization
17  * @version $Id: HttpAuth.java,v 1.22 2004/10/11 11:16:45 pierre Exp $
18  */

19 public class HttpAuth {
20     private static org.mmbase.util.logging.Logger log = org.mmbase.util.logging.Logging.getLoggerInstance(HttpAuth.class.getName());
21
22     private static org.mmbase.module.core.MMBase mmbase = (org.mmbase.module.core.MMBase) org.mmbase.module.core.MMBase.getMMBase();
23
24     private static String JavaDoc remoteAuthenticationHost = null;
25     private static String JavaDoc remoteAuthenticationPage = null;
26     private static int remoteAuthenticationPort = 80;
27
28     // Initializes HttpAuth by reading AUTH401URL from the mmbaseroot.xml file.
29
static {
30         String JavaDoc tmp = mmbase.getInitParameter("AUTH401URL");
31         if (tmp != null && !tmp.equals("")) {
32             HttpAuth.setLocalCheckUrl(tmp);
33         }
34     }
35
36     /**
37      * With a given mimeline, the username and password will be retrieved, and with it
38      * there will be looked if it is an valid login. If it is a valid login, with a rank higher
39      * or equals as Rank::BASICUSER, it will return a userid, otherwise null.
40      * @param mimeline The mimeline of the request
41      * @return a userid for the given user, of <code>null</code> when something goes wrong
42      */

43     public static String JavaDoc checkUser(String JavaDoc mimeline) {
44         String JavaDoc user_password = org.mmbase.util.Encode.decode("BASE64", mimeline.substring(6));
45         java.util.HashMap JavaDoc userInfo = new java.util.HashMap JavaDoc();
46         java.util.StringTokenizer JavaDoc t = new java.util.StringTokenizer JavaDoc(user_password, ":");
47         if (t.countTokens() == 2) {
48             userInfo.put("username", t.nextToken());
49             userInfo.put("password", t.nextToken());
50         }
51         org.mmbase.security.UserContext user = null;
52         try {
53             user = mmbase.getMMBaseCop().getAuthentication().login("name/password", userInfo, null);
54         }
55         catch(org.mmbase.security.SecurityException se) {
56             log.warn("user login of name: '" + userInfo.get("username") + "' failed("+se+")");
57             return null;
58         }
59         // when login failed, or when it was an anonymous user, it will not work...
60
if (user == null || user.getRank().getInt() < org.mmbase.security.Rank.BASICUSER_INT) {
61             log.warn("user login of name: '" + userInfo.get("username") + "' failed(invalid)");
62             return null;
63         }
64         return user.getIdentifier();
65     }
66
67     /**
68      * Authenticates a user, If the user cannot be authenticated a login-popup will appear
69      * @todo remove logging on using remoteAuthenticationHost - this should be moved to the security
70      * layer
71      * @param server server-account. (for exameple 'film' or 'www')
72      * @param level loginlevel. (for example 'Basic' or 'MD5')
73      * @return username foan exception will be thrown.
74      * @exception AuthorizationException if the authorization fails.
75      * @exception NotLoggedInException if the user hasn't logged in yet.
76      */

77     public static String JavaDoc getAuthorization(javax.servlet.http.HttpServletRequest JavaDoc req, javax.servlet.http.HttpServletResponse JavaDoc res,String JavaDoc server, String JavaDoc level) throws AuthorizationException, NotLoggedInException {
78         if (log.isDebugEnabled()) {
79             log.debug("server: " + server + ", level: " + level);
80         }
81         String JavaDoc mimeline = getMimeline(req);
82         if (mimeline == null) {
83             log.info("page " + req.getRequestURI() + " is secure, and user not yet authenticated");
84             res.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
85             res.setHeader("WWW-Authenticate","Basic realm=\""+server+"\"");
86             throw new NotLoggedInException("Not logged in Exception");
87         }
88         if(remoteAuthenticationHost == null) {
89             // use local validating
90
String JavaDoc username = checkUser(mimeline);
91             if (username == null) {
92                 log.service("Logging in of user failed");
93                 res.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
94                 res.setHeader("WWW-Authenticate","Basic realm=\""+server+"\"");
95                 throw new AuthorizationException("User authorization failed");
96             } else {
97                 log.debug("User " + username + " succesfully logged in");
98                 return username;
99             }
100         }
101         else {
102             try {
103                 // use remote validation
104
java.util.StringTokenizer JavaDoc t = new java.util.StringTokenizer JavaDoc(org.mmbase.util.Encode.decode("BASE64", mimeline.substring(6)), ":");
105                 String JavaDoc username = t.nextToken();
106                 String JavaDoc password = t.nextToken();
107
108                 java.net.Socket JavaDoc socket = new java.net.Socket JavaDoc(remoteAuthenticationHost, remoteAuthenticationPort);
109                 java.io.BufferedInputStream JavaDoc instream = new java.io.BufferedInputStream JavaDoc(socket.getInputStream());
110                 java.io.BufferedOutputStream JavaDoc outstream = new java.io.BufferedOutputStream JavaDoc(socket.getOutputStream());
111
112                 // vpro???
113
write(outstream,"GET "+remoteAuthenticationPage+" HTTP/1.0\nContent-Type: vpro/ballyhoo\nUser-Agent: VPRO/James remote password check\nAuthorization: "+password+"\n\n");
114                 String JavaDoc result = read(instream);
115                 if (result.indexOf("401") < 0) {
116                     // 401 not found, thus granted..
117
return username;
118                 }
119                 else {
120                     // was not granted...
121
String JavaDoc msg = "User authorization failed(server "+remoteAuthenticationHost+":"+remoteAuthenticationPort+remoteAuthenticationPage+")";
122                     throw new AuthorizationException(msg);
123                 }
124             }
125             catch(java.net.UnknownHostException JavaDoc uhe) {
126                 String JavaDoc msg = "host not found " + uhe;
127                 log.error(msg);
128                 throw new AuthorizationException(msg);
129             }
130             catch(java.io.IOException JavaDoc ioe) {
131                 String JavaDoc msg = "communication failure " + ioe;
132                 log.error(msg);
133                 throw new AuthorizationException(msg);
134             }
135         }
136     }
137
138     /**
139      * getRemoteUser
140      * @param req
141      * @return the remote user
142      */

143     public static String JavaDoc getRemoteUser(javax.servlet.http.HttpServletRequest JavaDoc req) {
144         return checkUser(getMimeline(req));
145     }
146
147     /**
148      * getRemoteUser
149      * @param sp
150      * @return the remote user
151      */

152     public static String JavaDoc getRemoteUser(scanpage sp) {
153         return getRemoteUser(sp.req);
154     }
155
156
157     /**
158      * Sets the url on which an authentication has to be checked.
159      * @param url
160      */

161     public static void setLocalCheckUrl(String JavaDoc url) {
162         if (remoteAuthenticationHost != null) {
163             log.error("check url was already set ('" + remoteAuthenticationHost + "')");
164             return;
165         }
166         int pos=url.indexOf('/');
167         if (pos!=-1) {
168             remoteAuthenticationHost = url.substring(0,pos);
169             remoteAuthenticationPage = url.substring(pos);
170         }
171         else {
172             remoteAuthenticationHost = url;
173             remoteAuthenticationPage = "/";
174         }
175         pos = remoteAuthenticationHost.indexOf(':');
176         if (pos!=-1) {
177             try {
178                 remoteAuthenticationPort = Integer.parseInt(remoteAuthenticationHost.substring(pos+1));
179             }
180             catch (Exception JavaDoc e) {
181                 log.error(e.toString());
182             }
183             remoteAuthenticationHost = remoteAuthenticationHost.substring(0,pos);
184         }
185     }
186
187     private static String JavaDoc getMimeline(javax.servlet.http.HttpServletRequest JavaDoc req) {
188         return ((String JavaDoc)req.getHeader("Authorization"));
189     }
190
191     private static int write(java.io.BufferedOutputStream JavaDoc out,String JavaDoc line) {
192         try {
193             out.write(line.getBytes());
194             out.flush();
195         } catch(java.io.IOException JavaDoc e) {
196             return -1;
197         }
198         return line.length();
199     }
200
201     private static String JavaDoc read(java.io.BufferedInputStream JavaDoc in) {
202         StringBuffer JavaDoc str=new StringBuffer JavaDoc();
203         int rtn=0;
204         do {
205             try {
206                 rtn=in.read();
207             }
208             catch(java.io.IOException JavaDoc e) {
209                 return null;
210             }
211             if (rtn==-1) {
212                 return null;
213             }
214             str.append((char)rtn);
215         }
216         while(rtn!='\n');
217         return str.toString();
218     }
219 }
220
Popular Tags