天天看點

Spring Boot 2.X(十八):內建 Spring Security-登入認證和權限控制

前言

在企業項目開發中,對系統的安全和權限控制往往是必需的,常見的安全架構有 Spring Security、Apache Shiro 等。本文主要簡單介紹一下 Spring Security,再通過 Spring Boot 內建開一個簡單的示例。

Spring Security

什麼是 Spring Security?

Spring Security 是一種基于 Spring AOP 和 Servlet 過濾器 Filter 的安全架構,它提供了全面的安全解決方案,提供在 Web 請求和方法調用級别的使用者鑒權和權限控制。

Web 應用的安全性通常包括兩方面:使用者認證(Authentication)和使用者授權(Authorization)。

使用者認證指的是驗證某個使用者是否為系統合法使用者,也就是說使用者能否通路該系統。使用者認證一般要求使用者提供使用者名和密碼,系統通過校驗使用者名和密碼來完成認證。

使用者授權指的是驗證某個使用者是否有權限執行某個操作。

2.原理

Spring Security 功能的實作主要是靠一系列的過濾器鍊互相配合來完成的。以下是項目啟動時列印的預設安全過濾器鍊(內建5.2.0):

[
    org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@5054e546,
    org.springframework.security.web.context.SecurityContextPersistenceFilter@7b0c69a6,
    org.springframework.security.web.header.HeaderWriterFilter@4fefa770,
    org.springframework.security.web.csrf.CsrfFilter@6346aba8,
    org.springframework.security.web.authentication.logout.LogoutFilter@677ac054,
    org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@51430781,
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter@4203d678,
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@625e20e6,
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter@19628fc2,
    org.springframework.security.web.session.SessionManagementFilter@471f8a70,
    org.springframework.security.web.access.ExceptionTranslationFilter@3e1eb569,
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor@3089ab62
]           
  • WebAsyncManagerIntegrationFilter
  • SecurityContextPersistenceFilter
  • HeaderWriterFilter
  • CsrfFilter
  • LogoutFilter
  • UsernamePasswordAuthenticationFilter
  • RequestCacheAwareFilter
  • SecurityContextHolderAwareRequestFilter
  • AnonymousAuthenticationFilter
  • SessionManagementFilter
  • ExceptionTranslationFilter
  • FilterSecurityInterceptor

詳細解讀可以參考:

https://blog.csdn.net/dushiwodecuo/article/details/78913113

3.核心元件

SecurityContextHolder

用于存儲應用程式安全上下文(Spring Context)的詳細資訊,如目前操作的使用者對象資訊、認證狀态、角色權限資訊等。預設情況下,

SecurityContextHolder

會使用

ThreadLocal

來存儲這些資訊,意味着安全上下文始終可用于同一執行線程中的方法。

擷取有關目前使用者的資訊

因為身份資訊與線程是綁定的,是以可以在程式的任何地方使用靜态方法擷取使用者資訊。例如擷取目前經過身份驗證的使用者的名稱,代碼如下:

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
    String username = ((UserDetails)principal).getUsername();
} else {
    String username = principal.toString();
}           

其中,

getAuthentication()

傳回認證資訊,

getPrincipal()

傳回身份資訊,

UserDetails

是對使用者資訊的封裝類。

Authentication

認證資訊接口,內建了

Principal

類。該接口中方法如下:

接口方法 功能說明
getAuthorities() 擷取權限資訊清單,預設是

GrantedAuthority

接口的一些實作類,通常是代表權限資訊的一系列字元串
getCredentials() 擷取使用者送出的密碼憑證,使用者輸入的密碼字元竄,在認證過後通常會被移除,用于保障安全
getDetails() 擷取使用者詳細資訊,用于記錄 ip、sessionid、證書序列号等值
getPrincipal() 擷取使用者身份資訊,大部分情況下傳回的是

UserDetails

接口的實作類,是架構中最常用的接口之一

AuthenticationManager

認證管理器,負責驗證。認證成功後,

AuthenticationManager

傳回一個填充了使用者認證資訊(包括權限資訊、身份資訊、詳細資訊等,但密碼通常會被移除)的

Authentication

執行個體。然後再将

Authentication

設定到

SecurityContextHolder

容器中。

AuthenticationManager

接口是認證相關的核心接口,也是發起認證的入口。但它一般不直接認證,其常用實作類

ProviderManager

内部會維護一個

List<AuthenticationProvider>

清單,存放裡多種認證方式,預設情況下,隻需要通過一個

AuthenticationProvider

的認證,就可被認為是登入成功。

UserDetailsService

負責從特定的地方加載使用者資訊,通常是通過

JdbcDaoImpl

從資料庫加載實作,也可以通過記憶體映射

InMemoryDaoImpl

實作。

UserDetails

該接口代表了最詳細的使用者資訊。該接口中方法如下:

擷取授予使用者的權限
getPassword() 擷取使用者正确的密碼,這個密碼在驗證時會和

Authentication

中的

getCredentials()

做比對
getUsername() 擷取用于驗證的使用者名
isAccountNonExpired() 訓示使用者的帳戶是否已過期,無法驗證過期的使用者
isAccountNonLocked() 訓示使用者的賬号是否被鎖定,無法驗證被鎖定的使用者
isCredentialsNonExpired() 訓示使用者的憑據(密碼)是否已過期,無法驗證憑證過期的使用者
isEnabled() 訓示使用者是否被啟用,無法驗證被禁用的使用者

Spring Security 實戰

1.系統設計

本文主要使用 Spring Security 來實作系統頁面的權限控制和安全認證,本示例不做詳細的資料增删改查,sql 可以在完整代碼裡下載下傳,主要是基于資料庫對頁面 和 ajax 請求做權限控制。

1.1 技術棧

  • 程式設計語言:Java
  • 程式設計架構:Spring、Spring MVC、Spring Boot
  • ORM 架構:MyBatis
  • 視圖模闆引擎:Thymeleaf
  • 安全架構:Spring Security(5.2.0)
  • 資料庫:MySQL
  • 前端:Layui、JQuery

1.2 功能設計

  1. 實作登入、退出
  2. 實作菜單 url 跳轉的權限控制
  3. 實作按鈕 ajax 請求的權限控制
  4. 防止跨站請求僞造(CSRF)攻擊

1.3 資料庫層設計

t_user 使用者表

字段 類型 長度 是否為空 說明
id int 8 主鍵,自增長
username varchar 20 使用者名
password 255 密碼

t_role 角色表

role_name 角色名稱

t_menu 菜單表

menu_name 菜單名稱
menu_url 50 菜單url(Controller 請求路徑)

t_user_roles 使用者權限表

user_id 使用者表id
role_id 角色表id

t_role_menus 權限菜單表

menu_id 菜單表id

實體類這裡不詳細列了。

2.代碼實作

2.0 相關依賴

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- 熱部署子產品 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional> <!-- 這個需要為 true 熱部署才有效 -->
        </dependency>
        
            <!-- mysql 資料庫驅動. -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- mybaits -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        
        <!-- thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        
        <!-- alibaba fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
        <!-- spring security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    </dependencies>           

2.1 繼承 WebSecurityConfigurerAdapter 自定義 Spring Security 配置

/**
prePostEnabled :決定Spring Security的前注解是否可用 [@PreAuthorize,@PostAuthorize,..]
secureEnabled : 決定是否Spring Security的保障注解 [@Secured] 是否可用
jsr250Enabled :決定 JSR-250 annotations 注解[@RolesAllowed..] 是否可用.
 */
@Configurable
@EnableWebSecurity
//開啟 Spring Security 方法級安全注解 @EnableGlobalMethodSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true,jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private CustomAccessDeniedHandler customAccessDeniedHandler;
    @Autowired
    private UserDetailsService userDetailsService;
    
    /**
     * 靜态資源設定
     */
    @Override
    public void configure(WebSecurity webSecurity) {
        //不攔截靜态資源,所有使用者均可通路的資源
        webSecurity.ignoring().antMatchers(
                "/",
                "/css/**",
                "/js/**",
                "/images/**",
                "/layui/**"
                );
    }
    /**
     * http請求設定
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //http.csrf().disable(); //注釋就是使用 csrf 功能        
        http.headers().frameOptions().disable();//解決 in a frame because it set 'X-Frame-Options' to 'DENY' 問題            
        //http.anonymous().disable();
        http.authorizeRequests()
            .antMatchers("/login/**","/initUserData")//不攔截登入相關方法        
            .permitAll()        
            //.antMatchers("/user").hasRole("ADMIN")  // user接口隻有ADMIN角色的可以通路
//            .anyRequest()
//            .authenticated()// 任何尚未比對的URL隻需要驗證使用者即可通路
            .anyRequest()
            .access("@rbacPermission.hasPermission(request, authentication)")//根據賬号權限通路            
            .and()
            .formLogin()
            .loginPage("/")
            .loginPage("/login")   //登入請求頁
            .loginProcessingUrl("/login")  //登入POST請求路徑
            .usernameParameter("username") //登入使用者名參數
            .passwordParameter("password") //登入密碼參數
            .defaultSuccessUrl("/main")   //預設登入成功頁面
            .and()
            .exceptionHandling()
            .accessDeniedHandler(customAccessDeniedHandler) //無權限處理器
            .and()
            .logout()
            .logoutSuccessUrl("/login?logout");  //登出成功URL
            
    }
    /**
     * 自定義擷取使用者資訊接口
     */
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
    
    /**
     * 密碼加密算法
     * @return
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
 
    }
}           

2.2 自定義實作 UserDetails 接口,擴充屬性

public class UserEntity implements UserDetails {

    /**
     * 
     */
    private static final long serialVersionUID = -9005214545793249372L;

    private Long id;// 使用者id
    private String username;// 使用者名
    private String password;// 密碼
    private List<Role> userRoles;// 使用者權限集合
    private List<Menu> roleMenus;// 角色菜單集合

    private Collection<? extends GrantedAuthority> authorities;
    public UserEntity() {
        
    }
    
    public UserEntity(String username, String password, Collection<? extends GrantedAuthority> authorities,
            List<Menu> roleMenus) {
        this.username = username;
        this.password = password;
        this.authorities = authorities;
        this.roleMenus = roleMenus;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<Role> getUserRoles() {
        return userRoles;
    }

    public void setUserRoles(List<Role> userRoles) {
        this.userRoles = userRoles;
    }

    public List<Menu> getRoleMenus() {
        return roleMenus;
    }

    public void setRoleMenus(List<Menu> roleMenus) {
        this.roleMenus = roleMenus;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}           

2.3 自定義實作 UserDetailsService 接口

/**
 * 擷取使用者相關資訊
 * @author charlie
 *
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    private Logger log = LoggerFactory.getLogger(UserDetailServiceImpl.class);

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private MenuDao menuDao;

    @Override
    public UserEntity loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根據使用者名查找使用者
        UserEntity user = userDao.getUserByUsername(username);
        System.out.println(user);
        if (user != null) {
            System.out.println("UserDetailsService");
            //根據使用者id擷取使用者角色
            List<Role> roles = roleDao.getUserRoleByUserId(user.getId());
            // 填充權限
            Collection<SimpleGrantedAuthority> authorities = new HashSet<SimpleGrantedAuthority>();
            for (Role role : roles) {
                authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
            }
            //填充權限菜單
            List<Menu> menus=menuDao.getRoleMenuByRoles(roles);
            return new UserEntity(username,user.getPassword(),authorities,menus);
        } else {
            System.out.println(username +" not found");
            throw new UsernameNotFoundException(username +" not found");
        }        
    }

}           

2.4 自定義實作 URL 權限控制

/**
 * RBAC資料模型控制權限
 * @author charlie
 *
 */
@Component("rbacPermission")
public class RbacPermission{

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        boolean hasPermission = false;
        if (principal instanceof UserEntity) {
            // 讀取使用者所擁有的權限菜單
            List<Menu> menus = ((UserEntity) principal).getRoleMenus();
            System.out.println(menus.size());
            for (Menu menu : menus) {
                if (antPathMatcher.match(menu.getMenuUrl(), request.getRequestURI())) {
                    hasPermission = true;
                    break;
                }
            }
        }
        return hasPermission;
    }
}           

2.5 實作 AccessDeniedHandler

自定義處理無權請求

/**
 * 處理無權請求
 * @author charlie
 *
 */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    private Logger log = LoggerFactory.getLogger(CustomAccessDeniedHandler.class);

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
            AccessDeniedException accessDeniedException) throws IOException, ServletException {
        boolean isAjax = ControllerTools.isAjaxRequest(request);
        System.out.println("CustomAccessDeniedHandler handle");
        if (!response.isCommitted()) {
            if (isAjax) {
                String msg = accessDeniedException.getMessage();
                log.info("accessDeniedException.message:" + msg);
                String accessDenyMsg = "{\"code\":\"403\",\"msg\":\"沒有權限\"}";
                ControllerTools.print(response, accessDenyMsg);
            } else {
                request.setAttribute(WebAttributes.ACCESS_DENIED_403, accessDeniedException);
                response.setStatus(HttpStatus.FORBIDDEN.value());
                RequestDispatcher dispatcher = request.getRequestDispatcher("/403");
                dispatcher.forward(request, response);
            }
        }

    }

    public static class ControllerTools {
        public static boolean isAjaxRequest(HttpServletRequest request) {
            return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
        }

        public static void print(HttpServletResponse response, String msg) throws IOException {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(msg);
            writer.flush();
            writer.close();
        }
    }

}           

2.6 相關 Controller

登入/退出跳轉

/**
 * 登入/退出跳轉
 * @author charlie
 *
 */
@Controller
public class LoginController {
    @GetMapping("/login")
    public ModelAndView login(@RequestParam(value = "error", required = false) String error,
            @RequestParam(value = "logout", required = false) String logout) {
        ModelAndView mav = new ModelAndView();
        if (error != null) {
            mav.addObject("error", "使用者名或者密碼不正确");
        }
        if (logout != null) {
            mav.addObject("msg", "退出成功");
        }
        mav.setViewName("login");
        return mav;
    }
}           

登入成功跳轉

@Controller
public class MainController {

    @GetMapping("/main")
    public ModelAndView toMainPage() {
        //擷取登入的使用者名
        Object principal= SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username=null;
        if(principal instanceof UserDetails) {
            username=((UserDetails)principal).getUsername();
        }else {
            username=principal.toString();
        }
        ModelAndView mav = new ModelAndView();
        mav.setViewName("main");
        mav.addObject("username", username);
        return mav;
    }
    
}           

用于不同權限頁面通路測試

/**
 * 用于不同權限頁面通路測試
 * @author charlie
 *
 */
@Controller
public class ResourceController {

    @GetMapping("/publicResource")
    public String toPublicResource() {
        return "resource/public";
    }
    
    @GetMapping("/vipResource")
    public String toVipResource() {
        return "resource/vip";
    }
}           

用于不同權限ajax請求測試

/**
 * 用于不同權限ajax請求測試
 * @author charlie
 *
 */
@RestController
@RequestMapping("/test")
public class HttptestController {

    @PostMapping("/public")
    public JSONObject doPublicHandler(Long id) {
        JSONObject json = new JSONObject();
        json.put("code", 200);
        json.put("msg", "請求成功" + id);
        return json;
    }

    @PostMapping("/vip")
    public JSONObject doVipHandler(Long id) {
        JSONObject json = new JSONObject();
        json.put("code", 200);
        json.put("msg", "請求成功" + id);
        return json;
    }
}           

2.7 相關 html 頁面

登入頁面

<form class="layui-form" action="/login" method="post">
            <div class="layui-input-inline">
                <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
                <input type="text" name="username" required
                    placeholder="使用者名" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-input-inline">
                <input type="password" name="password" required  placeholder="密碼" autocomplete="off"
                    class="layui-input">
            </div>
            <div class="layui-input-inline login-btn">
                <button id="btnLogin" lay-submit lay-filter="*" class="layui-btn">登入</button>
            </div>
            <div class="form-message">
                <label th:text="${error}"></label>
                <label th:text="${msg}"></label>
            </div>
        </form>           

退出系統

<form id="logoutForm" action="/logout" method="post"
                                style="display: none;">
                                <input type="hidden" th:name="${_csrf.parameterName}"
                                    th:value="${_csrf.token}">
                            </form>
                            <a
                                href="javascript:document.getElementById('logoutForm').submit();">退出系統</a>           

ajax 請求頁面

<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" id="hidCSRF">
<button class="layui-btn" id="btnPublic">公共權限請求按鈕</button>
<br>
<br>
<button class="layui-btn" id="btnVip">VIP權限請求按鈕</button>
<script type="text/javascript" th:src="@{/js/jquery-1.8.3.min.js}"></script>
<script type="text/javascript" th:src="@{/layui/layui.js}"></script>
<script type="text/javascript">
        layui.use('form', function() {
            var form = layui.form;
            $("#btnPublic").click(function(){
                $.ajax({
                    url:"/test/public",
                    type:"POST",
                    data:{id:1},
                    beforeSend:function(xhr){
                        xhr.setRequestHeader('X-CSRF-TOKEN',$("#hidCSRF").val());    
                    },
                    success:function(res){
                        alert(res.code+":"+res.msg);
                
                    }    
                });
            });
            $("#btnVip").click(function(){
                $.ajax({
                    url:"/test/vip",
                    type:"POST",
                    data:{id:2},
                    beforeSend:function(xhr){
                        xhr.setRequestHeader('X-CSRF-TOKEN',$("#hidCSRF").val());    
                    },
                    success:function(res){
                        alert(res.code+":"+res.msg);
                        
                    }
                });
            });
        });
    </script>           

2.8 測試

測試提供兩個賬号:user 和 admin (密碼與賬号一樣)

由于 admin 作為管理者權限,設定了全部的通路權限,這裡隻展示 user 的測試結果。

Spring Boot 2.X(十八):內建 Spring Security-登入認證和權限控制
Spring Boot 2.X(十八):內建 Spring Security-登入認證和權限控制
Spring Boot 2.X(十八):內建 Spring Security-登入認證和權限控制
Spring Boot 2.X(十八):內建 Spring Security-登入認證和權限控制

完整代碼

github 碼雲

非特殊說明,本文版權歸

朝霧輕寒

所有,轉載請注明出處.

原文标題:Spring Boot 2.X(十八):內建 Spring Security-登入認證和權限控制

原文位址:

https://www.zwqh.top/article/info/27

如果文章有不足的地方,歡迎提點,後續會完善。

如果文章對您有幫助,請給我點個贊,請掃碼關注下我的公衆号,文章持續更新中...

Spring Boot 2.X(十八):內建 Spring Security-登入認證和權限控制