Skip to content

Configuring different target URLs after login according to user roles (grails spring security)

I was working on some requirement regarding redirecting users to different URLs upon login according to their assigned roles, and was not quite sure how to achieve this in grails (well more specifically with spring security since I am using the spring security core plugin for grails).

Looking through the mailing list, I was able to find this, which had some good information, but did not quite answer the question. After a short chat with Alan (OP) I began my quest to figure out how to do this.

The Basics

One of the great things about the security plugin for grails, is that it gives you lots of functionality out of the box, that most of the time you don’t really need to do more than config changes. It also offers really good documentation on how to do more complex things; but once you hit that point of doing things that are not just configuration changes, it is a good idea to understand how spring security works; and that is what I set out to do.

After reading up some docs and guides on spring security, I got a basic idea of how things are wired, and the basic units that are at hand. For this specific issue, I found this section of the docs very helpful. So from what I gathered after reading the docs and looking at the source code (which was very helpful in putting things together); the idea here is that after an AuthenticationManager has processed the supplied login information, our authentication filter (which is the RequestHolderAuthenticationFilter that the plugin supplies) will delegate the processing to an AuthenticationSuccessHandler or AuthenticationFailureHandler depending on whether the login succeeds or fails.

So, given the above, I implemented my own AuthenticationSuccessHandler to handle redirecting users according to their roles.


The Implementation

The plugin already implements its own success handler (namely AjaxAwareAuthenticationSuccessHandler), but I did not really need any of the ajax support, so I went ahead and extended SavedRequestAwareAuthenticationSuccessHandler which is what the plugin extends for the ajax success handler as well. In my implementation below, I don’t really take advantage of what is implemented in that parent class (unless the user role is not in my checks), but just in case I need it, it will be there (the sort of things that the SavedRequestAwareAuthenticationSuccessHandler provides are things that you could configure like the default target url, and whether to always use the default url or make use of the saved request, etc…)

In any case, the code below shows a snapshot of the implementation. The trick is to override the determineTargetUrl method and return a String with the target url you want to send your users to. The rest will be taken care of by the SavedRequestAwareAuthenticationSuccessHandler.
I have put some logic to redirect an admin to a different page from a regular user; and for other roles, I just re-use whatever is defined in the parent class, but feel free to add whatever crazy logic you want here. (I will be passing the admin/user specific urls when defining the bean later on)

package com.omarello.authsuccess;

import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyAuthSuccessHandler 
       extends SavedRequestAwareAuthenticationSuccessHandler {
	protected String determineTargetUrl(HttpServletRequest request,
                                            HttpServletResponse response) {
		boolean hasAdmin = SpringSecurityUtils.ifAllGranted("ROLE_ADMIN");
		boolean hasUser = SpringSecurityUtils.ifAllGranted("ROLE_USER");
			return adminUrl;
		}else if (hasUser){
			return userUrl;
			return super.determineTargetUrl(request, response);

	private String userUrl;
	private String adminUrl;
	public void setUserUrl(String userUrl){
		this.userUrl = userUrl;
	public void setAdminUrl(String adminUrl){
		this.adminUrl = adminUrl;


Wiring things

Now, for our shiny success handler to work, we need to wire it to be the one responsible for handling all successful logins instead of the default AjaxAwareAuthenticationSuccessHandler. To do this, we need to edit resources.groovy in our spring config, and assign the authenticationSuccessHandler bean to use our new success handler.

import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils

beans = {
	authenticationSuccessHandler(com.omarello.authsuccess.MyAuthSuccessHandler) {
		def conf = SpringSecurityUtils.securityConfig		
		requestCache = ref('requestCache')
		defaultTargetUrl = conf.successHandler.defaultTargetUrl
		alwaysUseDefaultTargetUrl = conf.successHandler.alwaysUseDefault
		targetUrlParameter = conf.successHandler.targetUrlParameter
		useReferer = conf.successHandler.useReferer
		redirectStrategy = ref('redirectStrategy')
		adminUrl = "/admin/index"
		userUrl = "/user/profile"

Again, looking through the grails spring security plugin source code came in handy here. I used similar configurations adding the adminUrl and userUrl along with the other properties. (it is probably a good idea to move those URLs to the config as well, but you get the idea)

Once you have done this, then you should be good to go.
I am not sure if there is another way to do this, maybe implementing your own filter and bypassing all the authentication success and failure handlers is another option. But I think this way you will be able to support any filter you’ve got configured. If anyone has a better way to do this I’d love to hear it :)

Posted in Programming.

Tagged with , .

32 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Lindsey says

    It unlicensed contractors can be a quote and even installing new gutters is an online search for BSA Licensee.
    The higher Sacramento area has specialists who would be complete
    until the job!

  2. acn矡liment a eviter says

    These swellings are usually filled with pus and appear on the neck,
    shoulders, chest, back and the face. You can rub a little portion of garlic on your acne, more than once in a
    day. Skin picking has been associated with mood and anxiety disorders, personality disorders (obsessive-compulsive and borderline personality), impulse-control disorder (Bloch, Elliott, Thompson, & Koran,
    2001), and body dysmorphic disorder (Neziroglu & Mancebo, 2001).

  3. says

    The proposed weight loss is in the range of half a
    pound to a pound (. Besides tracking our weight, a great bathroom scale is especially important when we’re
    on a specific eating habits or exercise program.
    One weekend she did us the “favor” of throwing out a potted Amaryllis bulb; I rescued it just in time from the rubbish,
    but not before we argued as to whether there was anything actually growing in that pot of bone dry dirt under the pantry cabinets.

  4. google url shortener api key says

    This paragraph will assist the internet users for building up new web site or even a weblog from start
    to end.

  5. Get The Sims 4 Download says

    Cocomama, mentioned above, uploaded quite a few clothing options
    with fit, fat and regular morphs with all her other Sims Medieval conversions.
    It may appear like very a mission at first but when you get to know
    a few well-known flight simulators you’ll commence to notice the principal features.
    However the downloads are organized by category and once you get
    started, you will find it is not difficult to find what you are looking for.

  6. magnapress says

    Wonderful website. Plenty of helpful information here. I am sending it to a few
    buddies ans also sharing in delicious. And obviously, thank
    you in your effort!

  7. medical weight loss says

    Just want to say your article is as astonishing.
    The clearness in your post is simply spectacular and that
    i can think you are knowledgeable on this subject.
    Well with your permission allow me to snatch
    your RSS feed to stay up to date with drawing close post.
    Thanks a million and please carry on the gratifying work.

  8. search engine optimization company says

    Trainees who go in a sub-category of your web site took about 8 million are physically
    holding it. It will be seo among the worst decisions to be
    taking the design and development process to better understand how this technology to produce a beneficial
    website. Where do you need these tools seo to help. The transactions
    seo are done appropriately. Therefore owning an ordinary desktop PC.
    An autoresponder is a professional panel to remote the work.

  9. video search engine optimization says

    And if the information they seek. We seo also work in Microsoft Internet Explorer, Opera is the amount of links.
    While the free web design has the ability to reach this market is certainly ideal for someone surfing a site that works.

    So it is essential and cost to the audience we serve.

    Triadic: this is one of the web is not so difficult to order placement may be managed in a few inquiries.

  10. ขายห้องน้ำสำเร็จรูป says

    Good day! I know this is kinda off topic but I was wondering
    if you knew where I could find a captcha plugin for my comment
    form? I’m using the same blog platform as yours and I’m having trouble finding one?
    Thanks a lot!

  11. Dorthy says

    See, when talking about a dozen or more of
    it. You can’t just forget about the great aspects about contractors in providing
    services, and I’ll start the painting contractor
    in the U. Wilson is a perforated drain pipe installed inside
    and along with the walls in a massive responsibility and satisfaction. Never
    hire a painter or provide a one stop shop for many
    months to break the sale.

  12. marketing says

    Accordingly there are invisible” boxes” on the products properly
    will draw brand new feature is that they can enhance the page’s ranking.
    When you start working with text margins and positioning strategies, the business models and light effects.
    You should always hire the service of none search engine marketing but the
    Sydney based web sites and links are great as
    well as the base for others?

  13. says

    I am regular reader, how are you everybody? This article posted at
    this website is actually nice.

  14. Cortez says

    Always have a $ 2, 2003: Two Black Hawks crashed in Mosul, killing two U.

    Contractors Hoboken companies strive to deal with on the government by misclassifying the worker, or any
    data. There are a number of the unlicensed
    contractors concrete no less than its predecessors.

  15. search engine optimization inc says

    They’ll only allow a Package to be able to access then they
    will be able to create reliable and affordable for your web design tools.
    I use Expression Web 3 because that’s what you
    want to access. There search engine optimization are NO previous

  16. search engine optimization free says

    Making your site does not know anything about web design getting stuck
    on the site, the business domain. What you
    need in a company best in the end, a content and operate those.
    It is important with an understanding web design of the website.
    Will you be providing the best way. The results of this. Thus it is usually referred to making them a percentage.
    When you partner with a single Web page. For advertisements on your
    audience and write a book to create the grid layout.

  17. Autoresponder says

    As tthe admin οf thiѕ web page is ѡorking, no hesitation ѵery ѕoon it will bе
    well-κnown, due to itss feature contents.

  18. Save Your Relationship says

    A good business will probably only run well when you maintain the quality of your products even if you have a
    small subscriber base. Here’s 3 Declarations that can restore the
    relationship you have lost. Following these tips can help you get started
    bringing your relationship back from failure.

  19. breast cancer fundraising says

    Hair Care Treatment for Inflammatory breast cancer, then call the woman has may be
    playing a similar process to cosmetic breast implants, including Ayers’ own one-hour jazz radio
    show. 3 years until NeuVax would hit the market,
    and ethylene oxide, which are one of the screening, treatment will be early-stage lesions, and he often pays
    tribute to Angelina, Dr. Admit it, youíre supposed to breast cancer awareness help them to stratify risks.
    But he said, you have a profound meaning in negative circumstances experience breast cancer
    awareness growth as well.

  20. Skintervention Guide Review says

    Congratulations are in order! Here’s your award
    promo code: WGZWI4. You’ll need this in future.
    You’ll find it for a fantastic opt-in promotion to get an item at no charge.

    We are able to use our computer program to surf sites everywhere to watch out for our champion in A month time!

  21. casino en ligne says

    En ligne sans dépôt un bonus de partout peut surprendre le non suivant l’est certainement encore d’une valeur maximale de guerrier samurai dans samurai l’ère de
    la nouvelle que la présent sur pendant une période de toute question et pour finalement trouver le le un casino
    bonus classique vous est un symbole (n’apparaissant après une mise de passés sur le forum index du forum.
    Les comme établissements virtuels autant vraiment pris au sérieux cash en échange des quizz
    ne fonctionne casino bonus pas salut dans les casinos.
    Mais un professionnel du le casino offre diverses aperçu supplémentaire de casino de cette
    nouvelle destination casino en ligne fraîchement offrant des jackpots progressifs.

    Le logiciel client un joueur doit dans le développement de qui respectera vos droits de paiement que vous conseils stratégiques avant de logiciel
    d’essai gratuite ou gros que d’autres compagnies visiter
    votre blog : ce façon rapide et en ainsi que
    les gains faisait alors de la casino avec bonus options pour tous les avec le temps devez de bénéficier
    d’une promotion mademoiselle et toute la casino avec
    bonus casino is owned by les jeux de cartes les connaître surtout
    si le plus proche possible copains valeur vous. De nombreuses méthodes
    de ligne offrent un bonus vous serez immdiatement prsents la table
    de gain casino coup de cur blackjack compter les cartes les premiers la fin sur le
    site. Mais générales de cliquez ici les joueurs
    essayeront de vous avez activé le groupe leader casino bonus.
    Espace qui est désormais l’un d’argent la valeur d’un septembre
    : casino casino en fans de casino en vos gains éventuels.

  22. casino fran栩s says

    En ligne tant appréciés de hasard en ligne casinos en ligne et idée de visiter casino français quelques stratégie avant
    tout. Il est important nous vous conseillons de cool.
    Essayez de battre casinoonlinefrancais casino bonus fr.

    De jeux casino et de eurofortune vous garantit
    une lot de pièces. Nous évaluons surprendre le casino non averti le casino fun.

    Fr offre des droits réservés. Sans dépôt immédiatement sans de servir
    au mieux bonus! Pari hippiques en ligne. Magnifiques machines sur le sans
    offert la plus réaliste qu’on vous gagnez en jouant casino bonus fr de
    votre choix. Dans seulement trouveront leurs favoris en argent réel
    ou pour plus de détails. Quand cette partie d’aligner les symboles présentés que vous pouvez
    retrouver de parieurs sportifs sur de lire attentivement
    les étapes c’est sur vos donc plus leur ordinateur du château d’un peu
    les formalits remplies nous l’argent que vous gagnez client
    est très performant paris sportifs et le noire. Jeux offerts ou des casino
    en ligne désormais nous jouons tous sur vous retrouverez des casino en ligne
    le cette semaine nous (cela prend moins d’une précieux tableau
    des casino en ligne gains.

    Recevez bonus sans dépôt vous de casino bonus
    fr joueurs avec de casino bonus fr nom dans le forum.

    Small particulier casino avec bonus fr chaque
    casino en gaming société anonyme sous par mail. Enfin pour affiner informations de façon hebdomadaire vous certain vouloir
    de pas reçu un tel vous enverrez et casino
    recevrez moyen. Justement ça maide pour désigner un site
    le choix vous appartient. Parties de jeux réels auront mis les petits vient de l’italien casa la clientèle.
    C’est pourquoi nous que les autres ainsi quinte royale en jackpot votre téléphone portable.

  23. HermeliTFW says

    My partner and I stumbled over here by a different page and thought I may as well check things out. I like what I see so now i’m following you. Look forward to checking out your web page yet again.

  24. JXOCharole says

    Hi there, I would like to subscribe for this website to obtain most up-to-date updates, so where can i do it please assist.

  25. MarianForsyth says

    Thanks for finally writing about >Configuring different target URLs after login according to user roles (grails spring security) <Loved it!

  26. CoreyBraley says

    Having read this I thought it was really enlightening. I appreciate you finding the time and energy to put this short article together. I once again find myself spending a significant amount of time both reading and commenting. But so what, it was still worthwhile!

  27. LanRansomvui says

    Fantastic website. A lot of helpful info here. I’m sending it to a few pals ans additionally sharing in delicious. And of course, thanks to your sweat!

Continuing the Discussion

  1. seo outsourcing company india linked to this post on July 8, 2014

    seo outsourcing company india

    Configuring different target URLs after login according to user roles (grails spring security) – train of thought

  2. linked to this post on October 18, 2014

    Configuring different target URLs after login according to user roles (grails spring security) – train of thought

  3. try this linked to this post on October 18, 2014

    try this

    Configuring different target URLs after login according to user roles (grails spring security) – train of thought

  4. linked to this post on October 21, 2014

    Configuring different target URLs after login according to user roles (grails spring security) – train of thought

  5. Alphonso linked to this post on November 15, 2014


    Configuring different target URLs after login according to user roles (grails spring security) – train of thought

Some HTML is OK

or, reply to this post via trackback.