0
votes

So I am trying to create a simple login page in Grails and I keep getting a too many redirects error on my browser. I have not yet connected the login details to a database and you are supposed to log in using "admin" and "password", but regardless of whether I enter the correct or incorrect username and password, I get a "too many redirections error" in my browser.

Suggested action of deleting cookies did not work!

User.groovy

package loginmysql

class User {

    String userName
    String password
    String fullName

    String toString(){
        fullName
    }

    static constraints = {
        userName (unique:true)
        password(password:true)
        fullName()
    }
}

UserController.groovy

package loginmysql

class UserController {

    def index() { }

    def login() {
        if (params.username == "admin" && params.password == "password"){
            flash.message="login succeded!!!"
            session.user="admin"    // keep info on who connected
        }else{
            flash.message="login failed!!!"
        }
        redirect(action: "login")   // return to index page again and display login message
    }

    def logout() {
        session.user = null     // no user logged in
        redirect(action: "login")   // go to index page again
    }
}

index.gsp

<%@ page import="loginmysql.User" %>
<!DOCTYPE html>
<html>

<head>
    <meta name="layout" charset="utf-8" content="main"/>
    <title></title>
    <style type="text/css">
    label{
        float: left;
        width: 65px;
    }
    </style>
</head>
<body>
<g:if test="${flash.message}"
<div class="message">
    ${flash.message}
</div>
</g:if>
<g:if test="${session.user}">
    <br/>
    Logged as : ${session.user}  |   <g:link action="logout">Logout</g:link>
</g:if>
<g:else>
    <g:form action="login" style="padding-left:200px">
        <div style="width: 220px">
            <label>Username:</label> <input type="text" name="username"/>
            <label>Password:</label> <input type="password" name="password"/>
            <label>&nbsp;</label> <input type="submit" value="login"/>
        </div>
    </g:form>
</g:else>
</body>

</html>

Error (in Chrome)

This page is not working

Central Computer localhost attempted too many redirections

Try deleting your cookies

ERR_TOO_MANY_REDIRECTS

1
You should strongly consider using a plugin like spring-security for authentication. - doelleri

1 Answers

2
votes

At the end of your login() action you always redirects back to login, no matter what.

redirect(action: "login")

If you get a "successful" login, you should redirect somewhere else to prevent the infinite redirect loop.

if (params.username == "admin" && params.password == "password") {
    flash.message="login succeded!!!"
    session.user="admin"    // keep info on who connected
    redirect(action: "index")
} else {
    flash.message="login failed!!!"
}