【问题标题】:Cant gain acces to url with role ADMIN spring security无法使用角色 ADMIN spring security 访问 url
【发布时间】:2021-01-11 11:54:01
【问题描述】:

我在使用 Spring Security 时遇到问题,因为当我登录网站时,我无法使用角色 admin 访问 url 这是我的安全配置

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder encoder() {
        return new StandardPasswordEncoder("53cr3t");
    }

    public SecurityConfig(UserDetailsServiceImpl userDetailsService) {
        this.userDetailsService = userDetailsService;
    }




    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.headers().disable();

        http.authorizeRequests()

                .antMatchers("/").authenticated()
                .antMatchers("/rentAppPage/*").hasAuthority("ADMIN")
                .antMatchers("/addVehicle").hasRole("ADMIN")
                .antMatchers("/getVehicle").hasAuthority("ADMIN")
                .antMatchers("/removeVehicle").hasAuthority("ROLE_ADMIN")
                .antMatchers("/updateVehicle").hasAuthority("ROLE_ADMIN")
                .antMatchers("/allUser").hasAuthority("ROLE_ADMIN")
                .antMatchers("/resultGet").hasAuthority("ROLE_ADMIN")
                .antMatchers("/addUser").hasAuthority("ROLE_ADMIN")
                .antMatchers("/getUser").hasAuthority("ROLE_ADMIN")
                .antMatchers("/updateUser").hasAuthority("ROLE_ADMIN")
                .antMatchers("/removeUserById").hasAuthority("ROLE_ADMIN")
                .antMatchers("/price").permitAll()
                .antMatchers("/allScooter").permitAll()
                .antMatchers("/allCar").permitAll()
                .antMatchers("/allMotorBike").permitAll()
                .antMatchers("/allBike").permitAll()
                .antMatchers("/distance").permitAll()
                .antMatchers("/user").permitAll()
                .antMatchers("/rent").permitAll()
                .antMatchers("/rent2").permitAll()
                .antMatchers("/buy").permitAll()
                .antMatchers("/buy2").permitAll()
                .antMatchers("/thanks").permitAll()
                .antMatchers("/rentAppPage").hasAnyAuthority( "ROLE_ADMIN", "ROLE_USER")
                .and()
                .formLogin()
                .loginPage("/login").permitAll()
                .defaultSuccessUrl("/", true);
        ;

        http.sessionManagement()
                //.expiredUrl("/sessionExpired.html")
                .invalidSessionUrl("/login.html");
    }
}

我尝试使用 hasRole、hasAuthority、hasAnyAuthority 但不起作用,只能工作 permittAll 但我不想访问具有角色 user 的用户的某些 url
这是我的登录控制器

@Controller
public class LoginController {
    @Resource(name = "sessionObject")
    SessionObject sessionObject;

    @Autowired
    IAuthenticationService authenticationService;

    public LoginController(){

    }


    @RequestMapping(value = "",method = RequestMethod.GET)
    public String mainSite(){
        return "redirect:login";
    }

@RequestMapping(value = "/login",method = RequestMethod.GET)
    public String showLoginForm(Model model){
        model.addAttribute("userModel",new User());
        model.addAttribute("errorMessage","");
        return "login";
    }

    @RequestMapping(value = "/authenticate",method = RequestMethod.POST)
    public  String authenticateUser(@ModelAttribute("userModel")User user,Model model){
        boolean authResult = this.authenticationService.authenticationUser(user);
        if(authResult){
            System.out.println("logged  !!");
            this.sessionObject.setUser(user);
            return "rentAppPage";
        }else{
            model.addAttribute("errorMessage","error data!!!");
            model.addAttribute("userModel",new User());
            return "login";
        }
    }

    @RequestMapping(value = "/rentAppPage", method = RequestMethod.GET)
    public String page(Model model) {
        if(this.sessionObject.getUser() == null) {
            return "redirect:/login";
        }

        model.addAttribute("username", this.sessionObject.getUser().getUsername());
        System.out.println(this.sessionObject.getUser().getUsername());
        return "rentAppPage";
    }

@RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(){
        this.sessionObject.setUser(null);
        return "redirect:login";
    }

我在数据库中有两个用户,一个具有 Admin 角色,第二个具有 USER 角色,但这不起作用 有人能解释一下为什么吗?

https://github.com/Conrado1212/Electrical-Rent-App这是我的完整代码

【问题讨论】:

  • 您能告诉我们数据库中的角色究竟是如何存储的吗??
  • 我现在编辑你可以看到我尝试 ROLE_ADMIN 但不起作用,我更改为 ADMIN
  • 你应该存储在数据库 ROLE_ADMIN 而不是 ADMIN
  • 好的,我更改为 ROLE_ADMIN 并更改了 antMatchers("/addVehicle/*").hasRole("ADMIN") 但我不知道为什么我总是返回登录
  • 我必须使用生成密码登录才能使用 Spring Security?

标签: java html spring spring-security


【解决方案1】:

确定下面的配置是错误的

antMatchers("/rentAppPage/*").hasAuthority("ADMIN")

应该是

antMatchers("/rentAppPage/*").hasRole("ADMIN")

另外,作为建议,请尽量保持一致,当两者具有相同含义时,您将在配置中混合使用 hasAuthority("ROLE_ADMIN") 和 hasRole("ADMIN"),坚持使用一个并使您的代码更清晰。

【讨论】:

  • Spring security 在登录名和密码的意义上提供了它的登录方式,但是我的注册和登录使用我的用户名和密码没有生成,它是否有任何影响 authenticated() ?
  • 我改成.antMatchers("/").authenticated() .antMatchers("/rentAppPage/*").hasRole("ADMIN") .antMatchers("/addVehicle").hasRole("ADMIN") .antMatchers("/getVehicle").hasRole("ADMIN")但不起作用
【解决方案2】:

兄弟,如果您将整个代码发送给我们以更好地理解您的错误,那就更好了。但我可以告诉你另一种选择。您只能在 HTML 中检查角色。例如,您有添加车辆的按钮,您只能根据用户的角色显示和隐藏该按钮。在您的情况下,如果您只想向管理员显示该按钮,那么您可以像这样使用它:

    <% if (Page.User.IsInRole("Admin")){ %>
        //your add vehicle button
    <%}%>

免责声明:这不是一个理想的解决方案,但它会起作用。

如果你使用的是thymeleaf,你可以这样做:-

     <div th:if="${#authorization.expression('hasRole(''ADMIN'')')}">
       <li><a href="/addVehicle">Add Vehicle</a> </li>
     </div>

只有以管理员身份登录才能看到此列表,否则无法看到。如果您想测试它而不是编写列表标记,请使用一些 HTML 文本,例如

      <div th:if="${#authorization.expression('hasRole(''ADMIN'')')}">
       <label>Hey, Admin only you can see me</label>
     </div>

这里只有角色为 admin 的用户才能看到此文本。 让我知道这是否有效

【讨论】:

  • 好的,我看过你的 repo,我看到你正在使用 thymeleaf,所以我将编辑答案以添加 thymeleaf 代码,我还将告诉你它是如何使用 thymeleaf 工作的
  • org.thymeleaf.exceptions.TemplateProcessingException:评估 SpringEL 表达式的异常:“#authorization.expression('hasRole(''ADMIN'')')”(模板:“rentAppPage” - 第 25 行,col 14)当我尝试通过你的标签测试时,我得到了错误
  • 兄弟,这些不是双引号,它们是两个单独的单引号,例如 ' '
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签