【问题标题】:Spring security role-based URLSpring Security 基于角色的 URL
【发布时间】:2011-05-28 10:07:42
【问题描述】:

如何让spring-security根据用户的角色在登录后更改重定向页面?

【问题讨论】:

  • 您使用的是哪个版本的 Spring Security?

标签: spring-security


【解决方案1】:

根据 mmounirou 提供的链接,我刚刚复制了该链接的内容,用于设置基于角色的重定向,以防链接失效:

public class RoleBasedAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private Map<String, String> roleUrlMap;

    public void onAuthenticationSuccess(HttpServletRequest request,
            HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {

        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String role = userDetails.getAuthorities().isEmpty() ? null : userDetails.getAuthorities().toArray()[0]
                    .toString();
            response.sendRedirect(request.getContextPath() + roleUrlMap.get(role));
        }
    }

    public void setRoleUrlMap(Map<String, String> roleUrlMap) {
        this.roleUrlMap = roleUrlMap;
    }
}

bean 初始化取决于哪个角色应该重定向到哪里:

<beans:bean id="redirectRoleStrategy" class="dk.amfibia....security.RoleBasedAuthenticationSuccessHandler">
    <beans:property name="roleUrlMap">
        <beans:map>
            <beans:entry key="ROLE_SYSTEM" value="/system/index.htm"/>
            <beans:entry key="ROLE_ADMIN" value="/admin/index.htm"/>
            <beans:entry key="ROLE_USER" value="/index.htm"/>
        </beans:map>
    </beans:property>
</beans:bean>

最后我们需要告诉 spring-security 使用这个 redirectRoleStrategy。在 form-login 标记中,设置此属性: authentication-success-handler-ref=”redirectRoleStrategy”。

【讨论】:

    【解决方案2】:

    【讨论】:

    【解决方案3】:

    给出的是基于角色的 url 示例:

    RoleBasedUrlHandler.java

     @Component
        public class RoleBaseUrlHandler extends SimpleUrlAuthenticationSuccessHandler {
    
        //provide redirection logic
            private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    
            public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
                this.redirectStrategy = redirectStrategy;
            }
    
            protected RedirectStrategy getRedirectStrategy() {
                return redirectStrategy;
            }
    
            /**
             * Invokes the configured RedirectStrategy with the URL returned by the
             * determineTargetUrl method.
             * */
            @Override
            protected void handle(HttpServletRequest request,
                                  HttpServletResponse response, 
                                  Authentication authentication)throws IOException {
    
                String targetUrl = determineTargetUrl(authentication);
    
                if (response.isCommitted()) {
                    return;
                }
                redirectStrategy.sendRedirect(request, response, targetUrl);
            }
    
    
            /**
             * Builds the target URL according to the logic defined
             * This method extracts the roles of currently logged-in user and returns
             * appropriate URL according to his/her role.
             */
            protected String determineTargetUrl(Authentication authentication) {
                String url = "";
    
                Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    
                List<String> roles = new ArrayList<String>();
    
                for (GrantedAuthority a : authorities) {
                    roles.add(a.getAuthority());
                }
    
                if (isUser(roles)) {
                    url = "/user";
                } else if (isAdmin(roles)) {
                    url = "/admin";
                } else {
                    url = "/accessDenied";
                }
    
                return url;
            }
    
            private boolean isUser(List<String> roles) {
                if (roles.contains("ROLE_User")) {
                    return true;
                }
                return false;
            }
    
            private boolean isAdmin(List<String> roles) {
                if (roles.contains("ROLE_Admin")) {
                    return true;
                }
                return false;
            }
    }
    

    SpringSecurityConfig.java

    @EnableWebSecurity
    @Configuration
    public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{
    
        @Autowired
        RoleBaseUrlHandler urlHandler;
    
    
        @Autowired
        public void configAuthentication(AuthenticationManagerBuilder auth)throws Exception {
            auth.inMemoryAuthentication()
                    .withUser("Patel")
                    .password("Patel")
                    .authorities("ROLE_Admin")
                .and()
                    .withUser("Shah")
                    .password("Shah")
                    .authorities("ROLE_User");
        }
    
    
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .antMatchers("/admin").hasRole("Admin")
                    .antMatchers("/user").hasAnyRole("User","Admin")
                    .anyRequest().authenticated()
                .and()
                    .formLogin()
                    .loginPage("/login").successHandler(urlHandler).permitAll()
                    .failureUrl("/login?error")
                    .usernameParameter("username").passwordParameter("password")
                .and()
                    .logout().logoutSuccessUrl("/login?logout")
                .and()
                    .exceptionHandling().accessDeniedPage("/accessDenied")
                .and()
                    .csrf()
                .and()
                    .httpBasic();
    
        }
    
    }
    

    DemoSecurity.java

    @Controller
    public class DemoSecurity {
    
        @RequestMapping(value = "/login", method = RequestMethod.GET)
        public String loginPage(
                @RequestParam(value = "error", required = false) String error,
                @RequestParam(value = "logout", required = false) String logout,
                Model model) {
            if (error != null) {
                model.addAttribute("error", "Invalid Credentials provided.");
            }
            if (logout != null) {
                model.addAttribute("message", "Logged out successfully.");
            }
            return "login";
        }
    
        @RequestMapping(value="/logout", method = RequestMethod.POST)
        public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (auth != null){    
                new SecurityContextLogoutHandler().logout(request, response, auth);
            }
            return "redirect:/login?logout";
        }
    
        @RequestMapping(value = { "/admin" }, method = RequestMethod.GET)
        public String adminPage(Model model) {
            model.addAttribute("user", getPrincipal());
            return "admin";
        }
    
        @RequestMapping(value = { "/user" }, method = RequestMethod.GET)
        public String employeePage(Model model) {
            model.addAttribute("user", getPrincipal());
            return "user";
        }
    
        @RequestMapping(value = { "/accessDenied" }, method = RequestMethod.GET)
        public String accessDenied(Model model) {
            model.addAttribute("user", getPrincipal());
            return "accessDenied";
        }
    
        private String getPrincipal(){
            String userName = null;
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    
            if (principal instanceof UserDetails) {
                userName = ((UserDetails)principal).getUsername();
            } else {
                userName = principal.toString();
            }
            return userName;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-23
      • 2017-10-19
      • 2016-10-14
      • 2020-12-18
      • 2016-07-01
      • 2019-08-08
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多