I have index.gsp that presents a page. In that page there is a button to register, and a button to log in. Once you have logged in, if the login is ok, the app drives you again to index.gsp. I need that, if the user is logged in, these buttons disappear, and instead say "Hello, [username]". I've tried with this code, but it doesn't work (it is never logged in):
In the Controller:
def dologin(){
def user=Usuario.findByUsernameAndPassword(params.username,springSecurityService.encodePassword(params.password) )
if(user){
redirect (controller:'usuario', action:'index')
}else{
flash.message=message(code:'default.user.not.found', args:[message(code: 'params.username', default:'Usuario'), params.id])
def userlogged = springSecurityService.getCurrentUser()
render view: 'index', model: [user: user]
}
}
In index.gsp (is not full, only the piece that matters):
<sec:ifNotLoggedIn>
<div id="buttons">
<div id="login">Login
</div>
<div id="register">Registrarse
</div>
</div>
</sec:ifNotLoggedIn>
<sec:ifLoggedIn>
<div id="greet">Hello!</div>
</sec:ifLoggedIn>
Any help would be appreciated.
Thank you.
It looks like you're doing your own authentication, rather than going through the spring security authentication process. The <sec:ifLoggedIn> tag relies on spring security handling the authentication.
The usual way this is handled in a spring security app is by posting the login request to /j_spring_security_check, which, behind the scenes, gets filtered by a UsernamePasswordAuthenticationFilter.
Grails and the spring security plugin make this relatively painless by providing a LoginController and auth.gsp that you can use as a starting point. Run the s2-quickstart script (which also creates User and Role domain objects), or just copy them from the spring-security-core templates directory.
I tried it simply
<sec:ifNotLoggedIn> // DO SOMTHING</sec:ifNotLoggedIn>
<sec:ifLoggedIn> // DO SOMTHING</sec:ifNotLoggedIn>
Finally did it simply
<g:if test="${session.user==null}">
<!-- Display buttons-->
</g:if>
<g:if test=${session.user!=null">
<div id="greet"> Hello, ${session.user.username}!</div>
</g:if>
Easier, i think. But, thank you for your answer, ataylor.
Related
When the user successfully login, i'm storing the username in tempdata so i can use it in my _Layout:
TempData["username"] = model.Email.Split('#')[0];
TempData.Keep("username");
on my _Layout:
<li class="nav-item">
<h5 style="color:white"> Welcome, #TempData["username"]</h5>
</li>
this actually works on the first load, but if I go to another page, the tempdata turns to null and no username is displaying. How can i keep the username on my _layout?
Username displaying
Username not display
Tempdata keep method work only for next request. If you want to store data in over all pages. Use MVC identity principal methodology to persist data overall page. Iprincipal
If you've recently changed your authentication to azure Ad and your application is load balanced. Please make sure, you've updated the load balancer to use sticky session. Without a sticky session, the response can come from any server which can result in null temp data.
TempData is designed to have a life span only in between the current and the next request. You'd have to re-store it on every request (or call .Keep()) to make it available on the subsequent request.
You would be better of using a Session object or retrieving it from your user identity.
However you can "keep" your TempData object, if you call .Keep() after calling it (displaying counts towards calling).
<li class="nav-item">
<h5 style="color:white"> Welcome, #TempData["username"]</h5>
#TempData.Keep("username")
</li>
Yet another way to circumvent this, is to use .Peek():
<li class="nav-item">
<h5 style="color:white"> Welcome, #TempData.Peek("username").ToString()</h5>
</li>
I write the below given code in config.groovy
grails.plugins.springsecurity.providerNames = [
'rememberMeAuthenticationProvider'
]
grails.plugin.springsecurity.rememberMe.cookieName='grails_remember_me'
grails.plugin.springsecurity.rememberMe.alwaysRemember=false
grails.plugin.springsecurity.rememberMe.tokenValiditySeconds=31*24*60*60
grails.plugin.springsecurity.rememberMe.parameter='_spring_security_remember_me'
grails.plugin.springsecurity.rememberMe.key='monitoringApp'
grails.plugin.springsecurity.rememberMe.useSecureCookie=false
grails.plugin.springsecurity.rememberMe.persistent=false
grails.plugin.databasemigration.updateOnStart = true
i write the below given code on my gsp page
<div class="col-xs-7">
<div class="checkbox">
<label>
<input type='checkbox' name='_spring_security_remember_me' id='remember_me'
<g:if test='${hasCookie}'>checked='checked'</g:if>/>
<g:message code="springSecurity.login.remember.me.label"/>
</label>
</div>
</div>
My controller all action are fully authenticated using spring security #Secured(['IS_AUTHENTICATED_FULLY']) But i cannot able to use benefit of spring security remember me functionality.Please help me .
I am using grails version 2.3.0 and spring security :"spring-security-core:2.0-RC2"
The reason why your users, which have used the remember me feature of Spring security are still being prompted to login is because is IS_AUTHENTICATED_REMEMBERED not the same as IS_AUTHENTICATED_FULLY.
IS_AUTHENTICATED_REMEMBERED
requires the user to be authenticated through a remember-me cookie or an explicit login.
IS_AUTHENTICATED_FULLY
requires the user to be fully authenticated with an explicit login.
All of this is outlined in the very well written documentation.
Since you want to allow users to access things either by being remembered or logging in you should strongly consider using IS_AUTHENTICATED_REMEMBERED instead of IS_AUTHENTICATED_FULLY since it supports both cases.
I have an application, that register a user. I get the user through various pages, and everyone takes some data from the user, that info is stored in the session, and only in the last page, the data is stored in the DDBB.
When the first page is fulfilled by the user, he clicks the "next" button:
<div class='btn_sig_pag_uno'>
<!-- <fieldset id="barra">-->
<g:actionSubmit action="registro2"
title="${message(code:'infoPersonal.siguiente') }"
name="siguiente" class="siguiente"
value="${message(code: 'infoPersonal.siguiente', default: 'Siguiente')}"
style="cursor:pointer" />
<!-- </fieldset>-->
</div>
The in the controller, in the action "registro2" the data introduced by the user is validated, and "registro2.gsp" is presented... but the url presented is the same than in the first page. I would like it to be controller/action...and don't know why the url doesn't change.
Any help? Thank you!
What you need to do is to create an action to display registro2.gsp and then do a redirect after having execute registro2 like this:
redirect(action: "showRegistro2")
That way the URL will change.
I think this is the way forms work, and the way Grails deals with the actionSubmit. Form submits are by default POST. And since POSTs are about sending data (and not going somewhere, e.g. like a GET), the URL stays the same.
You can change your form to have method="GET", but I don't think this will get what you want when using Grails' actionSubmit since it still uses same URL (but with ?_action_actionSubmitActionName=param as URL param).
Usually you would just do a redirect to another action your action that receives the form POST:
redirect(action: "registroFinished")
And have a registroFinished.gsp for the end result.
I need to open another site in new tab from code behind in Asp.net MVC.
return Redirect("Url"); is used to open the another site within the same tab.
It doesn't really seem practical for the users, because after authenticating in the second tab, they have to refresh the first tab to see the effects.
The ReturnUrl property of FormsAuthentication seems to do what you want. When the user needs to log in, they are redirected to the login page, and after signing in they are redirected back.
If you are making extensive use of javascript and ajax, and want to keep the javascript variables of the current page but need to log in to do the ajax calls, there might be another solution. If the response of your ajax call is the unauthenticated header, open a lightbox or something like that with a username and password field. Use ajax post to the AccountController to sign in the user again. This way, the user is authenticated again, but you keep the javascript variables.
This can be done using javascript only. Try this.
<%
Response.Write '<script type="text/javascript">
window.open(url);
</script>'
%>
Hope it works.
if you call action from form and use input type of submit you can try
<input type="submit" formtarget="_blank" />
if you use link <a> or AjaxCall you can try
<a target="_blank"></a> or in ajax helper set property #target="_blank"
here is my code
cshtml
#using (Html.BeginForm("PersonsReport", "Reports"))
{
<br />
<div style="text-align: center;">
<input type="submit" formtarget="_blank" class="btn btn-primary" value="GetReport" style="width:100%;" />
</div>
<br />
}
controller.cs
public ActionResult PersonsReport()
{
return Redirect("/PersonsReport.aspx");
}
I have some controllers in my grails application:-
LoginController
LogoutController
SearchableController
cirnele.SearchAllController
com.ten.cirnelle.domain.CustomerController
com.ten.cirnelle.domain.ProjectController
com.ten.cirnelle.domain.PurchaseOrderController
com.ten.cirnelle.domain.QuotationController
com.ten.cirnelle.domain.ResourceController
In Config.groovy, I have provided one of my configration:-
cirnelleControllerExclusions =['Login','Search','Searchable','Resource']
and from main.gsp, I am using:-
<g:each var="c" in="${grailsApplication.controllerClasses.sort { it.fullName } }">
<g:if test="${grailsApplication.config.cirnelleControllerExclusions.contains(c.naturalName.split()[0]) == false}">
<li class="controller"><g:link controller="${c.logicalPropertyName}">${c.naturalName.split()[0]}</g:link></li>
</g:if>
</g:each>
this code is used to provide a menu like structure at the top of every view page and it is excluding 4 cotrollers, that i specified in Config.groovy to be display as a link in view pages.
but i have many users with different roles like
ROLE_PM
ROLE_SALES/BDM
ROLE_TEAMMEMBER
ROLE_ADMIN
and my requirement is that if an user with admin role logins, then he can view all the controllers as a link(except the 4) but if a user with PM role logins, then he cannot view CustomerController link and QuotationCotroller link.
so how can i customized my main.gsp to show menu links based on the role of user.
thnks
Try to use spring security plugin. There are tags for doing exactly what you want.
<sec:ifNotLoggedIn>
<g:link controller="login" action="auth">Login</g:link>
</sec:ifNotLoggedIn>
<sec:ifAllGranted roles="ROLE_USER">
<g:link class="create" controller="post" action="timeline">My Timeline</g:link>
</sec:ifAllGranted>