SSM集成SpringSecurity(五)user-service配置實現用戶權限訪問控制

SpringSecurity的主要功能是認證和授權,前面我們分別講了基於httpBasic和formLogin的登錄認證。本節開始,我們講解SpringSecurity的授權。

授權:授予用戶一定的權限。

基於前面章節的代碼,我們假設有這樣一個需求:現在有兩個用戶,xhc1和xhc2,xhc1持有商品顯示和添加的權限,xhc2持有商品修改和刪除的權限。那我們來實現吧。

1: 修改spring-security.xml文件,添加用戶信息

<security:authentication-provider>

<security:user-service>

<security:user name="xhc1" password="123456" authorities="ROLE_USER"/>

<security:user name="xhc2" password="123456" authorities="ROLE_ADMIN"/>

</security:user-service>

</security:authentication-provider>

</security:authentication-manager>

2: 在intercept-url pattern="/userLogin"後面新增攔截的地址

<security:intercept-url pattern="/userLogin" access="permitAll()"/>

 

<security:intercept-url pattern="/goods/add" access="hasRole('ROLE_USER')"/>

<security:intercept-url pattern="/goods/list" access="hasRole('ROLE_USER')"/>

<security:intercept-url pattern="/goods/delete" access="hasRole('ROLE_ADMIN')"/>

<security:intercept-url pattern="/goods/update" access="hasRole('ROLE_ADMIN')"/>

access中的hasRole方法就是判斷是否匹配參數中的的角色。注意:角色一定是以ROLE_開頭,這是springSecurity要求的。

3: 自定義權限不足的頁面。由於權限不足會報出403,所以需要自定義權限不足的頁面。

在jsp目錄下新增一個error.jsp頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

<title>錯誤頁面</title>

</head>

<body>

您沒有權限訪問

</body>

</html>

在MainController中添加

@RequestMapping("/error")

public String error() {

return "error";

}

配置文件中新增access-denied-handler

<security:csrf disabled="true"/>

<!-- 權限不足 -->

<security:access-denied-handler error-page="/error"/>

啓動項目,分別使用xhc1和xhc2進行登錄,如果權限不足,會跳轉到error.jsp頁面進行展示。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章