如何在url上实现spring security

Posted

技术标签:

【中文标题】如何在url上实现spring security【英文标题】:How to implement spring security on the url 【发布时间】:2018-11-28 22:52:26 【问题描述】:

我想为这个应用程序实现spring security,这样用户只需更改url就可以访问管理页面。我还没有找到一个适合这个应用程序结构的好例子。

这是我的用户控制器页面

import com.phonebook.command.LoginCommand;
import com.phonebook.command.UserCommand;
import com.phonebook.domain.User;
import com.phonebook.exception.UserBlockedException;
import com.phonebook.service.UserService;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController 

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/", "/index")
    public String index(Model m) 
        m.addAttribute("command", new LoginCommand());
        return "index"; //jsp - /WEB-INF/view/index.jsp
    

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String handleLogin(@ModelAttribute("command") LoginCommand cmd, Model m, HttpSession session) 
        try 
            User loggedInUser = userService.login(cmd.getLoginName(), cmd.getPassword());
            if (loggedInUser == null) 
                m.addAttribute("err", "Login Failed! Enter valid credentials.");
                return "index";
             else 
                if (loggedInUser.getRole().equals(UserService.ROLE_ADMIN)) 
                    addUserInSession(loggedInUser, session);
                    return "redirect:admin/dashboard";
                 else if (loggedInUser.getRole().equals(UserService.ROLE_USER)) 
                    addUserInSession(loggedInUser, session);
                    return "redirect:user/dashboard";
                 else 
                    m.addAttribute("err", "Invalid User ROLE");
                    return "index";
                
            
         catch (UserBlockedException ex) 
            m.addAttribute("err", ex.getMessage());
            return "index";
        
    

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) 
        session.invalidate();
        return "redirect:index?act=lo";
    

    @RequestMapping(value = "/user/dashboard")
    public String userDashboard() 
        return "dashboard_user";
    

    @RequestMapping(value = "/admin/dashboard")
    public String adminDashboard() 
        return "dashboard_admin";
    

    @RequestMapping(value = "/admin/users")
    public String getUserList(Model m) 
        m.addAttribute("userList", userService.getUserList());
        return "users";
    

    @RequestMapping(value = "/reg_form")
    public String registrationForm(Model m) 
        UserCommand cmd = new UserCommand();
        m.addAttribute("command", cmd);
        return "reg_form";
    

    @RequestMapping(value = "/register")
    public String registerUser(@ModelAttribute("command") UserCommand cmd, Model m) 
        try 
            User user = cmd.getUser();
            user.setRole(UserService.ROLE_USER);
            user.setLoginStatus(UserService.LOGIN_STATUS_ACTIVE);
            userService.register(user);
            return "redirect:index?act=reg";
         catch (DuplicateKeyException e) 
            e.printStackTrace();
            m.addAttribute("err", "Username is already registered. Please select another username.");
            return "reg_form";
        
    

    private void addUserInSession(User u, HttpSession session) 
        session.setAttribute("user", u);
        session.setAttribute("userId", u.getUserId());
        session.setAttribute("role", u.getRole());
    

    @RequestMapping(value = "/admin/change_status")
    @ResponseBody
    public String changeLoginStatus(@RequestParam Integer userId, @RequestParam Integer loginStatus) 
        try 
            userService.changeLoginStatus(userId, loginStatus);
            return "SUCCESS: Status Changed";
         catch (Exception e) 
            e.printStackTrace();
            return "ERROR: Unable to Change Status";
        
    

    @RequestMapping(value = "/check_avail")
    @ResponseBody
    public String checkAvailability(@RequestParam String username) 
        if (userService.isUsernameExist(username)) 
            return "This username is already taken. Choose another name";
         else 
            return "Yes! You can take this";
        
    


您可以在 GitHub 上通过此链接找到整个应用程序。 https://github.com/VikramThakur8/SpringContactApp

【问题讨论】:

【参考方案1】:

我认为,你应该为整个应用程序实现 Spring Security。好的开始是Baeldungs tutorial series.。阅读有关配置、身份验证和授权的信息,@Secured 注释。 通过配置,您可以指定谁可以访问特定的 url 模式。

【讨论】:

以上是关于如何在url上实现spring security的主要内容,如果未能解决你的问题,请参考以下文章

如何使用新的 Spring Authorization Server 在资源服务器上实现基于角色的授权

如何将 Spring Security 与我现有的 REST Web 服务集成

在 Spring Security 中检查现有的 HttpSession

我如何通过 Spring Security 创建 oauth 2 用户名密码流

Spring Security - 通过 URL 进行身份验证

如何在 localhost 和 Web 服务器上实现绝对 URL?