How to redirect to the homepage if the user accesses the login page after being logged in?

后端 未结 6 1361
一生所求
一生所求 2020-11-28 13:16

Here is my spring security config:




        
6条回答
  •  星月不相逢
    2020-11-28 14:19

    You can keep it simple flow by access-denied-page attribute in http element or as dtrunk said to write handler for access denied as well as. the config would be like

    
     
     
     
     
     ...
    
    

    in controller for /403

    @RequestMapping(value = "/403", method = RequestMethod.GET)
    public String accessDenied() { //simple impl
        return "redirect:/home";
    }
    

    and for /home

    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public String home(Authentication authentication) {
     // map as many home urls with Role
        Map dashBoardUrls = new HashMap();
        dashBoardUrls.put("ROLE_USER", "/user/dashboard");
        dashBoardUrls.put("ROLE_ADMIN", "/admin/dashboard");
    
        String url = null;
    
        Collection grants = authentication
                .getAuthorities();
     // for one role per user
        for (GrantedAuthority grantedAuthority : grants) {
            url = dashBoardUrls.get(grantedAuthority.getAuthority());
        }
        if (url == null)
            return "/errors/default_access_denied.jsp";
    
        return "redirect:" + url;
    }
    

    and when you make request for /admin/dashboard without logged in, it will redirect /login automatically by security

提交回复
热议问题