【问题标题】:Securing URLs Using Spring Security: Multiple Different Roles使用 Spring Security 保护 URL:多个不同的角色
【发布时间】:2021-02-09 01:16:19
【问题描述】:

我已经按照tutorial 设置了一个登录/注册 web 应用程序。现在我想实现它,以便将不同角色的用户带到不同的目录(即/admin/**)。我已经像这样修改了 WebSecurityConfigurerAdapter 的配置:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/resources/**", "/registration").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/sales/**").hasRole("SALES")
                .antMatchers("/production/**").hasRole("PRODUCTION")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .failureUrl("/login.html?error=true")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

我修改了 UserController 并添加了以下内容:

    @Controller
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private SecurityService securityService;

    @Autowired
    private UserValidator userValidator;

    @GetMapping("/registration")
    public String registration(Model model) {
        model.addAttribute("userForm", new User());

        return "registration";
    }

    @PostMapping("/registration")
    public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult) {
        userValidator.validate(userForm, bindingResult);

        if (bindingResult.hasErrors()) {
            return "registration";
        }

        userService.save(userForm);

        securityService.autoLogin(userForm.getUsername(), userForm.getPasswordConfirm());

        return "redirect:/home";
    }

    @GetMapping("/login")
    public String login(Model model, String error, String logout) {
        if (error != null)
            model.addAttribute("error", "Your username and password is invalid.");

        if (logout != null)
            model.addAttribute("message", "You have been logged out successfully.");

        return "login";
    }

    @GetMapping({"/admin/home"})
    public String admin_home(Model model) {
        return "home";
    }
    
    @GetMapping({"/sales/home"})
    public String sales_home(Model model) {
        return "home";
    }
    
    @GetMapping({"/production/home"})
    public String production_home(Model model) {
        return "home";
    }
    
    
}

现在登录后,我得到一个 Whitelabel 错误页面:出现意外错误(类型=未找到,状态=404)。 没有可用的消息。

我在我创建的各个子文件夹中创建了 home.jsp 页面。此外,登录后它仍然会转到“/”而不是“/admin/”。我在哪里可以更改不同角色在登录时将用户带到不同页面的事实?我可以将jsp页面放在webapp的文件夹中吗?我的jsp的位置对吗?当前是(webapp 文件夹): 网页应用

  • 管理员
  • 销售
  • 生产
  • 资源

【问题讨论】:

    标签: spring-boot spring-security


    【解决方案1】:

    我设法通过这样的SuccessHandler 类控制用户在登录时的重定向:

    import java.io.IOException;
    import java.util.Collection;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.web.DefaultRedirectStrategy;
    import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
    import org.springframework.stereotype.Component;
    
    @Component
    public class SuccessHandler implements AuthenticationSuccessHandler {
    
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                Authentication authentication) throws IOException, ServletException {
    
            String redirectUrl = null;
            
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority grantedAuthority : authorities) {
                System.out.println("role " + grantedAuthority.getAuthority());
                if (grantedAuthority.getAuthority().equals("SALES")) {
                    redirectUrl = "/sales/home";
                    break;
                } else if (grantedAuthority.getAuthority().equals("ADMIN")) {
                    redirectUrl = "/admin/home";
                    break;
                } else if (grantedAuthority.getAuthority().equals("PRODUCTION")) {
                    redirectUrl = "/production/home";
                    break;
                }
            }
            System.out.println("redirectUrl " + redirectUrl);
            if (redirectUrl == null) {
                throw new IllegalStateException();
            }
            new DefaultRedirectStrategy().sendRedirect(request, response, redirectUrl);
        }
    }
    
    

    据我所知,我无法将 jsps 放入我在 application.properties 中定义的子文件夹中。

    【讨论】:

      猜你喜欢
      • 2020-04-11
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      • 2014-03-07
      • 2016-01-07
      • 2014-10-19
      • 2017-12-30
      • 2011-08-02
      相关资源
      最近更新 更多