1
votes

I have a problem with spring security because i dont get a access to url with role admin when i am logged on site this is mine security config

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

i trying with hasRole , hasAuthority ,hasAnyAuthority but dont work , only work permittAll but i dont want to access something url to user with role user
this is mine login controller

@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";
    }

i have in database two users one with role Admin and second with role USER but this dont work can someone explain why ?

enter image description here

https://github.com/Conrado1212/Electrical-Rent-App here is my fulll code

2
Can you show us how are exactly the Roles in Database stored ??Juan BC
i edit now you can see i try ROLE_ADMIN but dont work and i change to ADMINKonrad Krawczyk
you should store in database ROLE_ADMIN instead of ADMINJuan BC
ok i change to ROLE_ADMIN and i change antMatchers("/addVehicle/*").hasRole("ADMIN") but i dont know why i always return to loginKonrad Krawczyk
i must login with generate password for spring security ?Konrad Krawczyk

2 Answers

0
votes

For sure following configuration is wrong

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

it should be

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

Also, as a recommendation, try to be more consistent, you are mixing in your configuration hasAuthority("ROLE_ADMIN") with hasRole("ADMIN") when both have the same meaning, stickt to one and make your code clearer.

0
votes

Bro it would have been much better if you would have send us the whole code to get the better understanding of your error. But I can tell you the alternative. You can check role in HTML only. For example you have button to add vehicle, you can only show and hide that button on the basis of role of user. In your case if you want to show that button to only admin then you can use it like this:

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

Disclaimer: This is not an ideal solution but it will work.

If you are using thymeleaf you can do it this way:-

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

You will only be able to see this list if you are logged in as Admin otherwise not. If you want to test this instead of writing list tag use some HTML text instead like

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

Here only the user whose role is admin will be able to see this text. Let me know if this works