Springboot整合SpringSecurity(五)——Spring Security使用@PreAuthorize,@PostAuthorize

       我要先吐槽一下,关于这方面的知识,网上很多博客都是直接翻译的官方文档,emmmm,里面有很多翻译不准确的地方,以及没有强调的关键地方,(好多博客都代码不全),导致我实现这个功能花了好多时间,不过还是实现了。下面就一如既往的简单粗暴的施展罗列代码大法。

第一步:准备一个实体类

package com.example.learnsecurity.learnsecurity.entity;

public class User {
    private int Id;
    private String UserName;
    private String PassWord;
    private String Type;

    public int getId() {
        return Id;
    }

    public void setId(int id) {
        Id = id;
    }

    public String getType() {
        return Type;
    }

    public void setType(String type) {
        Type = type;
    }

    public String getUserName() {
        return UserName;
    }

    public void setUserName(String userName) {
        UserName = userName;
    }

    public String getPassWord() {
        return PassWord;
    }

    public void setPassWord(String passWord) {
        PassWord = passWord;
    }
}

第二步:老套路,准备连接数据库的dao,以及service接口和实现类serviceimpl

@Mapper
@Repository
public interface UserDao {
    public User CheckLogin(@Param("UserName") String UserName,@Param("PassWord") String PassWord);
    public User SearchUser(@Param("UserName") String UserName);
    public List findAllUsers();
    public User findById(@Param("Id") int Id);
    public void updateUser();
    public void deleteUser(int id);
}
public interface UserService {
    public boolean ifhaveuser(String username,String password);

    List findAllUsers();

    User findById(int id);

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    void updateUser(User user);

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    void deleteUser(int id);
}
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    public UserDao userDao;

    @Override
    public boolean ifhaveuser(String username, String password) {
        User user=userDao.CheckLogin(username,password);
        if(user==null)
            return false;
        else return true;
    }

    @Override
    public List findAllUsers() {
        return userDao.findAllUsers();
    }

    @Override
    public User findById(int Id) {
        return userDao.findById(Id);
    }

    @Override
    public void updateUser(User user) {

    }

    @Override
    public void deleteUser(int id) {
        userDao.deleteUser(id);
    }
}

第三步:Controller

@Controller
public class HelloWorldController {

    @Autowired
    UserService service;

    @RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
    public String listAllUsers(ModelMap model) {

        List users = service.findAllUsers();
        model.addAttribute("users", users);
        return "allusers";
    }

    @RequestMapping(value = { "/edit-user-{id}" }, method = RequestMethod.GET)
    public String editUser(@PathVariable int id, ModelMap model) {
        User user  = service.findById(id);
        model.addAttribute("user", user);
        model.addAttribute("edit", true);
        return "registration";
    }

    @RequestMapping(value = { "/edit-user-{id}" }, method = RequestMethod.POST)
    public String updateUser(User user, ModelMap model, @PathVariable int id) {
        service.updateUser(user);
        model.addAttribute("success", "User " + user.getUserName()  + " updated successfully");
        return "success";
    }

    @RequestMapping(value = { "/delete-user-{id}" }, method = RequestMethod.GET)
    public String deleteUser(@PathVariable int id) {
        service.deleteUser(id);
        return "redirect:/list";
    }

    @RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
    public String accessDeniedPage(ModelMap model) {
        model.addAttribute("user", getPrincipal());
        return "accessDenied";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginPage() {
        return "login";
    }

    @RequestMapping(value="/logout", method = RequestMethod.GET)
    public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null){
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        return "redirect:/login?logout";
    }

    private String getPrincipal(){
        String userName = null;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (principal instanceof UserDetails) {
            userName = ((UserDetails)principal).getUsername();
        } else {
            userName = principal.toString();
        }
        return userName;
    }

}

第四步:这一步千万别忘了,虽然只有一句话

@EnableGlobalMethodSecurity(prePostEnabled = true)
//加在安全控制中心:public class SecurityConfig extends WebSecurityConfigurerAdapter里

第五步:测试

http://localhost:8081/hello->拦截到登录页面->登录后跳转到success页面->在地址栏改为/list出现下图画面

Springboot整合SpringSecurity(五)——Spring Security使用@PreAuthorize,@PostAuthorize_第1张图片

这里是数据库中所有账号信息的列表,我的库里就放了xiaohua这一个测试用户,可以看到,他的UserType是User所以,点击后面的edit和delete都会被拦截,因为只有管理员有资格这么做。

当我们用管理员身份登录后,点击delete就会删除账号,点击edit出现下图界面:

Springboot整合SpringSecurity(五)——Spring Security使用@PreAuthorize,@PostAuthorize_第2张图片

除了ID是无法修改的,其他三个信息都可以修改,这就是update功能。

 

你可能感兴趣的:(java,SpringSecurity)