IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Tomcat et TomEE Java Discussion :

[Tomcat 6] FormRealm et auto-authentification


Sujet :

Tomcat et TomEE Java

  1. #1
    Membre averti
    Inscrit en
    Mars 2004
    Messages
    377
    Détails du profil
    Informations forums :
    Inscription : Mars 2004
    Messages : 377
    Points : 356
    Points
    356
    Par défaut [Tomcat 6] FormRealm et auto-authentification
    Bonjour,

    Je suis en train de faire faire une application à un de nos petits jeunes, et je lui ai demandé d'utiliser le realm de Tomcat pour cette application.
    Histoire de ne pas avoir de fenêtre gris pas très jolie, je lui ai proposé d'utiliser donc le Form Realm via le tag <login-config> du web.xml et <auth-method>FORM</auth-method>.
    Lorsqu'il essaie de visualiser les pages, cela lui affiche bien son formulaire.
    En saisissant les logins et mot de passe, cela fonctionne correctement. On retourne sur la page correspondante.
    Jusque là tout va bien.
    Maintenant le problème est que nous aimerions pouvoir passer en paramètre les logins et mot de passe, afin de pouvoir faire du pseudo-SSO.
    Il a tenté de passer les paramètres j_user et j_password directement dans l'url, mais cela ne veut pas fonctionner.
    Après l'avoir laissé chercher 15 jours et n'ayant pas le temps de chercher plus moi même, j'ai regardé du côté des Valves, mais d'après lui cela ne fonctionne pas. J'ai un doute :-)
    Donc ma question est la suivante.
    Quel moyen a t on pour pouvoir faire en sorte d'accéder à une page sécurisé en passant en paramètres le login et le mot de passe d'un utilisateur ?
    Je sais que vous êtes des experts et comme j'ai un boulet de stagiaire :-), je compte sur vous pour l'aider.
    Merci d'avance.

    PS : Je sais que cela peut paraître étrange de passer les paramètres en url, mais c'est pour un projet interne, dont la sécurité n'est pas notre priorité.
    Néanmoins si vous avez une réponse tout de même plus sécurisé, sans rien changer au système de Form Realm qui fonctionne déjà, je suis preneur...

    PSS : N'abandonnez pas ce pauvre stagiaire malheureux qui prendra une claque derrière la tête s'il ne trouve pas !!!

    PSSS : Il attend vos réponses avec impatience.

  2. #2
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 481
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 481
    Points : 48 806
    Points
    48 806
    Par défaut
    on ne peux pas, mieux J2EE garantit qu'on ne pourra pas et que donc l'application est de-facto protégée contre le session hi-jacking


    Plus précisément, l'accès à l'url d'authentification en POST n'est possible QUE sir le forumulaire de login a été présenté en raison d'un accès tenté à une ressource protégée.

    Pour du SSO, il faudra vous tourner vers d'autres solution, comme la single sign on implémenté dans tomcat (propriétaire) ou via des filtre qui font la gestion de sécurité de manière plus souple (et plus dangereuse) que le conteneur http://securityfilter.sourceforge.net/

  3. #3
    Membre averti
    Inscrit en
    Mars 2004
    Messages
    377
    Détails du profil
    Informations forums :
    Inscription : Mars 2004
    Messages : 377
    Points : 356
    Points
    356
    Par défaut
    N'étant pas très doué en sécurité, je vais te croire.
    Bien que j'avoue ne pas comprendre, car à partir du moment, où on connait le login et le mot de passe, je ne vois pas pourquoi on ferait du hi-jacking de session.
    J'ai bien pensé au filtre, néanmoins, je pense que le Realm intervient avant les filtres non ?
    Et le principe des Valve de Tomcat çà te parle ?
    Tu connais çà ?
    http://tomcat.apache.org/tomcat-5.5-...nticator_Valve

  4. #4
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 481
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 481
    Points : 48 806
    Points
    48 806
    Par défaut
    la form valve vous servira a rien.
    Le filter sert quand justement on désactive la sécurité du conteneur pour la faire sois même, voir la doc du lien sus mentionné.

  5. #5
    Membre averti
    Inscrit en
    Mars 2004
    Messages
    377
    Détails du profil
    Informations forums :
    Inscription : Mars 2004
    Messages : 377
    Points : 356
    Points
    356
    Par défaut
    Ok.
    Merci beaucoup.
    Je vais chercher une autre solution alors.

  6. #6
    Membre averti
    Inscrit en
    Mars 2004
    Messages
    377
    Détails du profil
    Informations forums :
    Inscription : Mars 2004
    Messages : 377
    Points : 356
    Points
    356
    Par défaut
    Bon. Alors en fait, je suis désolé de contrarier.
    Mais la solution fonctionne avec les Valves.
    Alors on peut effectivement avoir des doutes pour des raisons de sécurité, néanmoins comme cela marche.
    Je vais donner la solution.
    Les valves interviennent bien avant le Realm, c'est ce qui permet de faire ce que je souhaitais à savoir, utiliser les paramètres d'URL pour auto-authentifier.
    Pour cela, il suffit de développer une classe qui va s'authentifier auprès du realm de Tomcat qui est disponible depuis le context.
    Pour l'exemple, j'ai modifié la classe org.apache.catalina.authenticator.FormAuthenticator dont j'avais parlé.

    Voici le résultat :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    /*
     * Licensed to the Apache Software Foundation (ASF) under one or more
     * contributor license agreements.  See the NOTICE file distributed with
     * this work for additional information regarding copyright ownership.
     * The ASF licenses this file to You under the Apache License, Version 2.0
     * (the "License"); you may not use this file except in compliance with
     * the License.  You may obtain a copy of the License at
     * 
     *      http://www.apache.org/licenses/LICENSE-2.0
     * 
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
     
     
    package org.apache.catalina.authenticator;
     
     
    import java.io.IOException;
    import java.io.InputStream;
    import java.security.Principal;
    import java.util.Enumeration;
    import java.util.Iterator;
    import java.util.Locale;
     
    import javax.servlet.RequestDispatcher;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletResponse;
     
    import org.apache.catalina.Globals;
    import org.apache.catalina.Realm;
    import org.apache.catalina.Session;
    import org.apache.catalina.connector.Request;
    import org.apache.catalina.connector.Response;
    import org.apache.catalina.deploy.LoginConfig;
    import org.apache.coyote.ActionCode;
    import org.apache.juli.logging.Log;
    import org.apache.juli.logging.LogFactory;
    import org.apache.tomcat.util.buf.ByteChunk;
    import org.apache.tomcat.util.buf.CharChunk;
    import org.apache.tomcat.util.buf.MessageBytes;
    import org.apache.tomcat.util.http.MimeHeaders;
     
     
    /**
     * An <b>Authenticator</b> and <b>Valve</b> implementation of FORM BASED
     * Authentication, as described in the Servlet API Specification, Version 2.2.
     *
     * @author Craig R. McClanahan
     * @author Remy Maucherat
     * @version $Revision: 892804 $ $Date: 2009-12-21 13:56:09 +0100 (Mon, 21 Dec 2009) $
     */
     
    public class MyFormAuthenticator
        extends AuthenticatorBase {
     
        private static Log log = LogFactory.getLog(MyFormAuthenticator.class);
     
        // ----------------------------------------------------- Instance Variables
     
     
        /**
         * Descriptive information about this implementation.
         */
        protected static final String info =
            "org.apache.catalina.authenticator.FormAuthenticator/1.0";
     
        /**
         * Character encoding to use to read the username and password parameters
         * from the request. If not set, the encoding of the request body will be
         * used.
         */
        protected String characterEncoding = null;
     
     
        // ------------------------------------------------------------- Properties
     
     
        /**
         * Return descriptive information about this Valve implementation.
         */
        public String getInfo() {
     
            return (info);
     
        }
     
     
        /**
         * Return the character encoding to use to read the username and password.
         */
        public String getCharacterEncoding() {
            return characterEncoding;
        }
     
     
        /**
         * Set the character encoding to be used to read the username and password. 
         */
        public void setCharacterEncoding(String encoding) {
            characterEncoding = encoding;
        }
     
     
        // --------------------------------------------------------- Public Methods
     
     
        /**
         * Authenticate the user making this request, based on the specified
         * login configuration.  Return <code>true</code> if any specified
         * constraint has been satisfied, or <code>false</code> if we have
         * created a response challenge already.
         *
         * @param request Request we are processing
         * @param response Response we are creating
         * @param config    Login configuration describing how authentication
         *              should be performed
         *
         * @exception IOException if an input/output error occurs
         */
        public boolean authenticate(Request request,
                                    Response response,
                                    LoginConfig config)
            throws IOException {
     
     
    		/** DEBUT DE LA MODIFICATION **/
    		String formUser = request.getParameter(Constants.FORM_USERNAME);
    		String formPassword = request.getParameter(Constants.FORM_PASSWORD);
    		String formAuthenticate = request.getParameter("j_authenticate");
    		if(formUser!=null && !formUser.equals("") && formPassword!=null && !formPassword.equals("") && formAuthenticate!=null && formAuthenticate.equals("true")){
     
    		    Session session = request.getSessionInternal(true);
    			Principal principal = null;
     
    			principal = context.getRealm().authenticate(formUser, formPassword);			
                if (principal != null) {
    			   log.debug("Authenticate OK ! Continue");
                   session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
                   if (!matchRequest(request)) {
                      register(request, response, principal, Constants.FORM_METHOD, formUser, formPassword);
                      return (true);
                   }
                } else {
    				log.debug("Go to error page");
    				forwardToErrorPage(request, response, config);
    				return (false);
    			}			
    		}	
    		/** FIN  DE LA MODIFICATION **/
     
    		// References to objects we will need later
    		Session session = null;
     
     
            // Have we already authenticated someone?
            Principal principal = request.getUserPrincipal();
            String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
            if (principal != null) {
                if (log.isDebugEnabled())
                    log.debug("Already authenticated '" +
                        principal.getName() + "'");
                // Associate the session with any existing SSO session
                if (ssoId != null)
                    associate(ssoId, request.getSessionInternal(true));
                return (true);
            }
     
            // Is there an SSO session against which we can try to reauthenticate?
            if (ssoId != null) {
                if (log.isDebugEnabled())
                    log.debug("SSO Id " + ssoId + " set; attempting " +
                              "reauthentication");
                // Try to reauthenticate using data cached by SSO.  If this fails,
                // either the original SSO logon was of DIGEST or SSL (which
                // we can't reauthenticate ourselves because there is no
                // cached username and password), or the realm denied
                // the user's reauthentication for some reason.
                // In either case we have to prompt the user for a logon */
                if (reauthenticateFromSSO(ssoId, request))
                    return true;
            }
     
            // Have we authenticated this user before but have caching disabled?
            if (!cache) {
                session = request.getSessionInternal(true);
                if (log.isDebugEnabled())
                    log.debug("Checking for reauthenticate in session " + session);
                String username =
                    (String) session.getNote(Constants.SESS_USERNAME_NOTE);
                String password =
                    (String) session.getNote(Constants.SESS_PASSWORD_NOTE);
                if ((username != null) && (password != null)) {
                    if (log.isDebugEnabled())
                        log.debug("Reauthenticating username '" + username + "'");
                    principal =
                        context.getRealm().authenticate(username, password);
                    if (principal != null) {
                        session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
                        if (!matchRequest(request)) {
                            register(request, response, principal,
                                     Constants.FORM_METHOD,
                                     username, password);
                            return (true);
                        }
                    }
                    if (log.isDebugEnabled())
                        log.debug("Reauthentication failed, proceed normally");
                }
            }
     
            // Is this the re-submit of the original request URI after successful
            // authentication?  If so, forward the *original* request instead.
            if (matchRequest(request)) {
                session = request.getSessionInternal(true);
                if (log.isDebugEnabled())
                    log.debug("Restore request from session '"
                              + session.getIdInternal() 
                              + "'");
                principal = (Principal)
                    session.getNote(Constants.FORM_PRINCIPAL_NOTE);
                register(request, response, principal, Constants.FORM_METHOD,
                         (String) session.getNote(Constants.SESS_USERNAME_NOTE),
                         (String) session.getNote(Constants.SESS_PASSWORD_NOTE));
                // If we're caching principals we no longer need the username
                // and password in the session, so remove them
                if (cache) {
                    session.removeNote(Constants.SESS_USERNAME_NOTE);
                    session.removeNote(Constants.SESS_PASSWORD_NOTE);
                }
                if (restoreRequest(request, session)) {
                    if (log.isDebugEnabled())
                        log.debug("Proceed to restored request");
                    return (true);
                } else {
                    if (log.isDebugEnabled())
                        log.debug("Restore of original request failed");
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                    return (false);
                }
            }
     
            // Acquire references to objects we will need to evaluate
            MessageBytes uriMB = MessageBytes.newInstance();
            CharChunk uriCC = uriMB.getCharChunk();
            uriCC.setLimit(-1);
            String contextPath = request.getContextPath();
            String requestURI = request.getDecodedRequestURI();
            response.setContext(request.getContext());
     
    		log.debug("contextPath : "+contextPath);
    		log.debug("requestURI : "+requestURI);
    		log.debug("request.getParameter(Constants.FORM_USERNAME) : "+request.getParameter(Constants.FORM_USERNAME));
    		log.debug("request.getParameter(Constants.FORM_PASSWORD) : "+request.getParameter(Constants.FORM_PASSWORD));
     
     
            // Is this the action request from the login page?
            boolean loginAction =
                requestURI.startsWith(contextPath) &&
                requestURI.endsWith(Constants.FORM_ACTION);
     
            // No -- Save this request and redirect to the form login page
            if (!loginAction) {
                session = request.getSessionInternal(true);
                if (log.isDebugEnabled())
                    log.debug("Save request in session '" + session.getIdInternal() + "'");
                try {
                    saveRequest(request, session);
                } catch (IOException ioe) {
                    log.debug("Request body too big to save during authentication");
                    response.sendError(HttpServletResponse.SC_FORBIDDEN,
                            sm.getString("authenticator.requestBodyTooBig"));
                    return (false);
                }
                forwardToLoginPage(request, response, config);
                return (false);
            }
     
            // Yes -- Validate the specified credentials and redirect
            // to the error page if they are not correct
            Realm realm = context.getRealm();
            if (characterEncoding != null) {
                request.setCharacterEncoding(characterEncoding);
            }
            String username = request.getParameter(Constants.FORM_USERNAME);
            String password = request.getParameter(Constants.FORM_PASSWORD);
            if (log.isDebugEnabled())
                log.debug("Authenticating username '" + username + "'");
            principal = realm.authenticate(username, password);
            if (principal == null) {
                forwardToErrorPage(request, response, config);
                return (false);
            }
     
            if (log.isDebugEnabled())
                log.debug("Authentication of '" + username + "' was successful");
     
            if (session == null)
                session = request.getSessionInternal(false);
            if (session == null) {
                if (containerLog.isDebugEnabled())
                    containerLog.debug
                        ("User took so long to log on the session expired");
                response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT,
                                   sm.getString("authenticator.sessionExpired"));
                return (false);
            }
     
            // Save the authenticated Principal in our session
            session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
     
            // Save the username and password as well
            session.setNote(Constants.SESS_USERNAME_NOTE, username);
            session.setNote(Constants.SESS_PASSWORD_NOTE, password);
     
            // Redirect the user to the original request URI (which will cause
            // the original request to be restored)
            requestURI = savedRequestURL(session);
            if (log.isDebugEnabled())
                log.debug("Redirecting to original '" + requestURI + "'");
            if (requestURI == null)
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                                   sm.getString("authenticator.formlogin"));
            else
                response.sendRedirect(response.encodeRedirectURL(requestURI));
            return (false);
     
        }
     
     
        // ------------------------------------------------------ Protected Methods
     
     
        /**
         * Called to forward to the login page
         * 
         * @param request Request we are processing
         * @param response Response we are creating
         * @param config    Login configuration describing how authentication
         *              should be performed
         * @throws IOException  If the forward to the login page fails and the call
         *                      to {@link HttpServletResponse#sendError(int, String)
         *                      throws an {@link IOException}
         */
        protected void forwardToLoginPage(Request request, Response response,
                LoginConfig config) throws IOException {
            RequestDispatcher disp =
                context.getServletContext().getRequestDispatcher
                (config.getLoginPage());
            try {
                disp.forward(request.getRequest(), response.getResponse());
                response.finishResponse();
            } catch (Throwable t) {
                String msg = sm.getString("formAuthenticator.forwardLoginFail");
                log.warn(msg, t);
                request.setAttribute(Globals.EXCEPTION_ATTR, t);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        msg);
            }
        }
     
     
        /**
         * Called to forward to the error page
         * 
         * @param request Request we are processing
         * @param response Response we are creating
         * @param config    Login configuration describing how authentication
         *              should be performed
         * @throws IOException  If the forward to the error page fails and the call
         *                      to {@link HttpServletResponse#sendError(int, String)
         *                      throws an {@link IOException}
         */
        protected void forwardToErrorPage(Request request, Response response,
                LoginConfig config) throws IOException {
            RequestDispatcher disp =
                context.getServletContext().getRequestDispatcher
                (config.getErrorPage());
            try {
                disp.forward(request.getRequest(), response.getResponse());
            } catch (Throwable t) {
                String msg = sm.getString("formAuthenticator.forwardErrorFail");
                log.warn(msg, t);
                request.setAttribute(Globals.EXCEPTION_ATTR, t);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        msg);
            }
        }
     
     
        /**
         * Does this request match the saved one (so that it must be the redirect
         * we signalled after successful authentication?
         *
         * @param request The request to be verified
         */
        protected boolean matchRequest(Request request) {
     
          // Has a session been created?
          Session session = request.getSessionInternal(false);
          if (session == null)
              return (false);
     
          // Is there a saved request?
          SavedRequest sreq = (SavedRequest)
              session.getNote(Constants.FORM_REQUEST_NOTE);
          if (sreq == null)
              return (false);
     
          // Is there a saved principal?
          if (session.getNote(Constants.FORM_PRINCIPAL_NOTE) == null)
              return (false);
     
          // Does the request URI match?
          String requestURI = request.getRequestURI();
          if (requestURI == null)
              return (false);
          return (requestURI.equals(sreq.getRequestURI()));
     
        }
     
     
        /**
         * Restore the original request from information stored in our session.
         * If the original request is no longer present (because the session
         * timed out), return <code>false</code>; otherwise, return
         * <code>true</code>.
         *
         * @param request The request to be restored
         * @param session The session containing the saved information
         */
        protected boolean restoreRequest(Request request, Session session)
            throws IOException {
     
            // Retrieve and remove the SavedRequest object from our session
            SavedRequest saved = (SavedRequest)
                session.getNote(Constants.FORM_REQUEST_NOTE);
            session.removeNote(Constants.FORM_REQUEST_NOTE);
            session.removeNote(Constants.FORM_PRINCIPAL_NOTE);
            if (saved == null)
                return (false);
     
            // Modify our current request to reflect the original one
            request.clearCookies();
            Iterator cookies = saved.getCookies();
            while (cookies.hasNext()) {
                request.addCookie((Cookie) cookies.next());
            }
     
            MimeHeaders rmh = request.getCoyoteRequest().getMimeHeaders();
            rmh.recycle();
            boolean cachable = "GET".equalsIgnoreCase(saved.getMethod()) ||
                               "HEAD".equalsIgnoreCase(saved.getMethod());
            Iterator names = saved.getHeaderNames();
            while (names.hasNext()) {
                String name = (String) names.next();
                // The browser isn't expecting this conditional response now.
                // Assuming that it can quietly recover from an unexpected 412.
                // BZ 43687
                if(!("If-Modified-Since".equalsIgnoreCase(name) ||
                     (cachable && "If-None-Match".equalsIgnoreCase(name)))) {
                    Iterator values = saved.getHeaderValues(name);
                    while (values.hasNext()) {
                        rmh.addValue(name).setString( (String)values.next() );
                    }
                }
            }
     
            request.clearLocales();
            Iterator locales = saved.getLocales();
            while (locales.hasNext()) {
                request.addLocale((Locale) locales.next());
            }
     
            request.getCoyoteRequest().getParameters().recycle();
            request.getCoyoteRequest().getParameters().setQueryStringEncoding(
                    request.getConnector().getURIEncoding());
     
            if ("POST".equalsIgnoreCase(saved.getMethod())) {
                ByteChunk body = saved.getBody();
     
                if (body != null) {
                    request.getCoyoteRequest().action
                        (ActionCode.ACTION_REQ_SET_BODY_REPLAY, body);
     
                    // Set content type
                    MessageBytes contentType = MessageBytes.newInstance();
     
                    //If no content type specified, use default for POST
                    String savedContentType = saved.getContentType();
                    if (savedContentType == null) {
                        savedContentType = "application/x-www-form-urlencoded";
                    }
     
                    contentType.setString(savedContentType);
                    request.getCoyoteRequest().setContentType(contentType);
                }
            }
            request.getCoyoteRequest().method().setString(saved.getMethod());
     
            request.getCoyoteRequest().queryString().setString
                (saved.getQueryString());
     
            request.getCoyoteRequest().requestURI().setString
                (saved.getRequestURI());
            return (true);
     
        }
     
     
        /**
         * Save the original request information into our session.
         *
         * @param request The request to be saved
         * @param session The session to contain the saved information
         * @throws IOException
         */
        protected void saveRequest(Request request, Session session)
            throws IOException {
     
            // Create and populate a SavedRequest object for this request
            SavedRequest saved = new SavedRequest();
            Cookie cookies[] = request.getCookies();
            if (cookies != null) {
                for (int i = 0; i < cookies.length; i++)
                    saved.addCookie(cookies[i]);
            }
            Enumeration names = request.getHeaderNames();
            while (names.hasMoreElements()) {
                String name = (String) names.nextElement();
                Enumeration values = request.getHeaders(name);
                while (values.hasMoreElements()) {
                    String value = (String) values.nextElement();
                    saved.addHeader(name, value);
                }
            }
            Enumeration locales = request.getLocales();
            while (locales.hasMoreElements()) {
                Locale locale = (Locale) locales.nextElement();
                saved.addLocale(locale);
            }
     
            if ("POST".equalsIgnoreCase(request.getMethod())) {
                ByteChunk body = new ByteChunk();
                body.setLimit(request.getConnector().getMaxSavePostSize());
     
                byte[] buffer = new byte[4096];
                int bytesRead;
                InputStream is = request.getInputStream();
     
                while ( (bytesRead = is.read(buffer) ) >= 0) {
                    body.append(buffer, 0, bytesRead);
                }
                saved.setContentType(request.getContentType());
                saved.setBody(body);
            }
     
            saved.setMethod(request.getMethod());
            saved.setQueryString(request.getQueryString());
            saved.setRequestURI(request.getRequestURI());
     
            // Stash the SavedRequest in our session for later use
            session.setNote(Constants.FORM_REQUEST_NOTE, saved);
     
        }
     
     
        /**
         * Return the request URI (with the corresponding query string, if any)
         * from the saved request so that we can redirect to it.
         *
         * @param session Our current session
         */
        protected String savedRequestURL(Session session) {
     
            SavedRequest saved =
                (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
            if (saved == null)
                return (null);
            StringBuffer sb = new StringBuffer(saved.getRequestURI());
            if (saved.getQueryString() != null) {
                sb.append('?');
                sb.append(saved.getQueryString());
            }
            return (sb.toString());
     
        }
     
     
    }
    La partie modifiée se situe au début de la méthode authenticate.
    Donc celle-ci j'ai ajouté la nécessité d'avoir un paramètre j_authenticate à true pour que l'authentification se fasse de manière automatique.

    Pour l'utiliser, deux choses sont nécessaires :
    1- Créer un JAR que l'on va mettre dans le répertoire "lib" de Tomcat 6
    2- Utiliser dans la déclaration du contexte le tag suivant :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    <Valve className="org.apache.catalina.authenticator.MyFormAuthenticator"/>
    Une fois tout cela fait normalement cela fonctionne correctement.

    Pour information également, j'ai regardé la version 1.6 de JEE et il se trouve que dans les specs 3.0 des servlets, la classe HttpServletRequest contient une méthode login(username, password) permettant d'authentifier un utilisateur. Cela doit donc être plus simple encore avec Tomcat 7 en utilisant un filtre par exemple.

    http://download.oracle.com/javaee/6/...etRequest.html

    Voilà tout !

  7. #7
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 481
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 481
    Points : 48 806
    Points
    48 806
    Par défaut
    Citation Envoyé par ZeKiD Voir le message
    Bon. Alors en fait, je suis désolé de contrarier.
    Mais la solution fonctionne avec les Valves.
    Vous ne contrariez pas et je n'ai pas dis le contraire, d'ailleurs il existe bien la singelsignon valve par défaut en tomcat.

    J'ai jsute dit que la formvalve ne vous servirais pas, car celle-ci est destinée à afficher le formulaire de login

  8. #8
    Membre averti
    Inscrit en
    Mars 2004
    Messages
    377
    Détails du profil
    Informations forums :
    Inscription : Mars 2004
    Messages : 377
    Points : 356
    Points
    356
    Par défaut
    Au temps pour moi alors !!
    J'ai mal lu.
    L'essentiel est que çà marche en tout cas !!

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Tomcat et certificat SSL auto-signé
    Par fats1 dans le forum Tomcat et TomEE
    Réponses: 2
    Dernier message: 20/02/2015, 17h24
  2. [Authentification] Tomcat 5.5
    Par SEMPERE Benjamin dans le forum Tomcat et TomEE
    Réponses: 11
    Dernier message: 22/10/2007, 12h21
  3. Realm Tomcat Action & Authentification
    Par zekey dans le forum Tomcat et TomEE
    Réponses: 2
    Dernier message: 21/12/2005, 10h46
  4. Authentification Windows via TOMCAT
    Par Spi25 dans le forum Tomcat et TomEE
    Réponses: 5
    Dernier message: 21/07/2004, 10h03

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo