Spring Security教程之Spring Security实现访问控制

在Spring Security中,实现访问控制或权限控制是很是容易实现的,请看下面的代码片断:html

1
2
3
   < http  auto-config = "true" >
     < intercept-url  pattern = "/admin*"  access = "ROLE_ADMIN"  />
   </ http >

它的意思是,只有“ROLE_ADMIN”权限的用户能够容许访问“ /admin*”路径,若是没有权限的用户访问则会提示“http 403 access denied page”错误。java

本次教程中,咱们像你展现只有“ROLE_ADMIN”权限的用户能够访问“/admin*”web

1.项目依赖

访问控制须要Spring Security的核心包,请参考Spring+Spring Security+Maven 实现的一个Hello World例子 列出的jarspring

2.Spring MVC

Spring MVC作控制器并返回一个“hello”视图,这个你应该能够理解的。app

WelcomeController.javaeclipse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package  com.mkyong.common.controller;
  
import  org.springframework.stereotype.Controller;
import  org.springframework.ui.ModelMap;
import  org.springframework.web.bind.annotation.RequestMapping;
import  org.springframework.web.bind.annotation.RequestMethod;
  
@Controller
public  class  WelcomeController {
  
     @RequestMapping (value =  "/admin" , method = RequestMethod.GET)
     public  String welcomeAdmin(ModelMap model) {
  
         model.addAttribute( "message" "Spring Security - ROLE_ADMIN" );
         return  "hello" ;
  
     }
  
}

 hello.jspjsp

1
2
3
4
5
6
7
8
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
< html >
< body >
     < h3 >Message : ${message}</ h3 >
  
     < a  href = "<c:url value=" j_spring_security_logout" />" > Logout</ a >
</ body >
</ html >

3.Spring Security

一下是Sprign Security所有的配置文件,只容许“eclipse”用户能够访问“/hello”页面ide

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
     xmlns:beans = "http://www.springframework.org/schema/beans" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans
  
     < http  auto-config = "true" >
         < intercept-url  pattern = "/admin*"  access = "ROLE_ADMIN"  />
         < logout  logout-success-url = "/admin"  />
     </ http >
  
     < authentication-manager >
       < authentication-provider >
        < user-service >
         < user  name = "it161"  password = "password"  authorities = "ROLE_USER"  />
         < user  name = "eclipse"  password = "password"  authorities = "ROLE_ADMIN"  />
        </ user-service >
       </ authentication-provider >
     </ authentication-manager >
  
</ beans:beans >

4.示例

http://localhost:8080/SpringMVC/adminui

1.默认的登录页面以下所示:url

2.若是用“it161”登录时,就会提示“http 403 is access denied page”,由于it161是“ROLE_USER”权限

3.若是用“eclipse”登录的话,“hello.jsp”就会展现,由于“eclipse”是“ROLE_ADMIN“权限。

默认的403页面很是丑陋,请能够阅读本人自定义你的403页面:Spring Security教程-Spring Security实现访问控制

原创文章,转载请注明出处:http://www.it161.com/article/javaDetail?articleid=140113230945

更多原创内容,请访问:http://www.it161.com/

相关文章
相关标签/搜索