Spring boot 使用Spring安全保护URL:多个不同的角色

Spring boot 使用Spring安全保护URL:多个不同的角色,spring-boot,spring-security,Spring Boot,Spring Security,我已按照以下步骤设置了登录/注册webapp。现在我想实现它,以便不同角色的用户被带到不同的目录(即/admin/**)。我修改了WebSecurity配置适配器的配置,如下所示: @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers(&qu

我已按照以下步骤设置了登录/注册webapp。现在我想实现它,以便不同角色的用户被带到不同的目录(即/admin/**)。我修改了WebSecurity配置适配器的配置,如下所示:

    @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();
    }
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);
    }
}

我修改了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";
    }
    
    
}
现在在登录之后,我得到了一个白标签错误页面:出现了一个意外错误(type=notfound,status=404)。 没有可用的消息

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

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

我通过一个
SuccessHandler
类控制了用户登录时的重定向,如下所示:

    @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();
    }
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);
    }
}

import java.io.IOException;
导入java.util.Collection;
导入javax.servlet.ServletException;
导入javax.servlet.http.HttpServletRequest;
导入javax.servlet.http.HttpServletResponse;
导入org.springframework.security.core.Authentication;
导入org.springframework.security.core.GrantedAuthority;
导入org.springframework.security.web.DefaultRedirectStrategy;
导入org.springframework.security.web.authentication.AuthenticationSuccessHandler;
导入org.springframework.stereotype.Component;
@组成部分
公共类SuccessHandler实现AuthenticationSuccessHandler{
@凌驾
AuthenticationSuccess(HttpServletRequest请求、HttpServletResponse响应、,
身份验证)引发IOException、ServletException{
字符串重定向URL=null;

Collection我通过一个
SuccessHandler
类控制用户登录时的重定向,如下所示:

    @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();
    }
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);
    }
}

import java.io.IOException;
导入java.util.Collection;
导入javax.servlet.ServletException;
导入javax.servlet.http.HttpServletRequest;
导入javax.servlet.http.HttpServletResponse;
导入org.springframework.security.core.Authentication;
导入org.springframework.security.core.GrantedAuthority;
导入org.springframework.security.web.DefaultRedirectStrategy;
导入org.springframework.security.web.authentication.AuthenticationSuccessHandler;
导入org.springframework.stereotype.Component;
@组成部分
公共类SuccessHandler实现AuthenticationSuccessHandler{
@凌驾
AuthenticationSuccess(HttpServletRequest请求、HttpServletResponse响应、,
身份验证)引发IOException、ServletException{
字符串重定向URL=null;
收集