Securizando the controllers do not work the roles, lets enter without being admin admin

0

I have the Spring Security functionality configured and in the database I have a user role and I define in SecurityConfiguration @PreAuthorize ("hasRole ('ROLE_ADMIN')") so that only the ADMIN role has access to the path @ GetMapping ("/ contactform") which is the form that allows you to make the CRUD of contacts, however, regardless of whether you log in with user that has a user profile, it also allows me to access the functionality of the CRUD, having to display a p [agina in blank and not access to the contact form. If I click on the accept button it creates the record.

Annex link of the repository: link

SecurityConfiguration

package com.udemy.configuration;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled=true)
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Autowired
        @Qualifier("userService")
        private UserDetailsService userService;

        @Autowired
        protected void configureGlobal(AuthenticationManagerBuilder auth )throws Exception {
            auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                .antMatchers("/css/*", "/imgs/*").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login").loginProcessingUrl("/logincheck")
                .usernameParameter("username").passwordParameter("password")
                .defaultSuccessUrl("/loginsuccess").permitAll()
                .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/login?logout")
                .permitAll();
        }

    }

ContactController

package com.udemy.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.udemy.constant.ViewConstant;
import com.udemy.model.ContactModel;
import com.udemy.service.ContactService;

@Controller
@RequestMapping("/contacts")
public class ContactController {

    private static final Log LOGGER = LogFactory.getLog(ContactController.class);

    @Autowired
    @Qualifier("contactServiceImpl")
    private ContactService contactService;

    @GetMapping("/cancel")
    public String cancel() {
        return "redirect:/contacts/showcontacts";

    }

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/contactform")
    private String redirectContactForm(@RequestParam(name="id", required=false) int id,
            Model model) {
        ContactModel contact = new ContactModel();
        if(id != 0) {
            contact = contactService.findContactByIdModel(id);
        }   
        model.addAttribute("contactModel", contact);
        return ViewConstant.CONTACT_FORM;

    }

    @PostMapping("/addcontact")
    public String addContact(@ModelAttribute(name = "contactModel") ContactModel contactModel, Model model) {
        LOGGER.info("METHOD: addContact() -- PARAMS: error =" + contactModel.toString());

        if (null != contactService.addContact(contactModel)) {
            model.addAttribute("result", 1);

        } else {
            model.addAttribute("result", 0);
        }

        return "redirect:/contacts/showcontacts";

    }

    @GetMapping("/showcontacts")
    public ModelAndView showContacts() {
        ModelAndView mav = new ModelAndView(ViewConstant.CONTACTS);
        mav.addObject("contacts", contactService.listAllContacts());
        return mav;
    }

    @GetMapping("/removecontact")
    public ModelAndView removeContact(@RequestParam(name="id", required=true) int id) {
        contactService.removeContact(id);;
        return showContacts();
    }

}

LoginController

package com.udemy.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.udemy.constant.ViewConstant;

@Controller
public class LoginController {

    private static final Log LOGGER =  LogFactory.getLog(LoginController.class);

    @GetMapping("/login")
    public String showLoginForm(Model model,
            @RequestParam(name="error", required=false) String error,
            @RequestParam(name="logout", required=false) String logout) {
        LOGGER.info("METHOD: showLoginForm() -- PARAMS: error =" + error + ", logout: " + logout);
        model.addAttribute("error", error);
        model.addAttribute("logout", logout);
        LOGGER.info("Return to login view");
        return ViewConstant.LOGIN;

    }

    @GetMapping({"/loginsuccess", "/"})
    public String loginCheck() {
        LOGGER.info("METHOD: loginCheck()");
        LOGGER.info("Return to contacts view");
        return "redirect:/contacts/showcontacts";

    }

}
    
asked by García Henry 24.05.2018 в 18:28
source

1 answer

0

The error was caused because the scope was as private in the method:

private String redirectContactForm(@RequestParam(name="id", required=false) int id,, siendo 

how right it was public:

Correction

public String redirectContactForm(@RequestParam(name="id", required=false) int id,
    
answered by 26.05.2018 в 16:31