用戶(hù)權(quán)限和認(rèn)證也是一個(gè)非常重要的機(jī)制讼呢,可以看到tomcat在manager環(huán)節(jié)是會(huì)彈出一個(gè)認(rèn)證窗輸入用戶(hù)密碼的拷呆,Dubbo锅劝、Druid也是采取相同的方式進(jìn)行認(rèn)證攒驰,這也吸引了我的注意,一直想知道是怎么實(shí)現(xiàn)故爵,然后自己也整一個(gè)簡(jiǎn)單的實(shí)現(xiàn)。今天終于是搞定了隅津,記錄一下配置過(guò)程诬垂。
我使用的是Springmvc4.3.1發(fā)現(xiàn)使用spring-scurity需要引入另外兩個(gè)jar包,注意版本和springmvc的版本是不一樣的伦仍,最新的security已經(jīng)到5.x了结窘。
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
引入上面兩個(gè)之后,還需要配置spring-security.xml和web.xml中添加配置充蓝,
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.2.xsd">
<!-- use-expressions:Spring 表達(dá)式語(yǔ)言配置訪問(wèn)控制 -->
<security:http auto-config="true" use-expressions="false">
<!-- 配置權(quán)限攔截隧枫,訪問(wèn)所有url喉磁,都需要用戶(hù)登錄,且擁有ROLE_USER權(quán)限 -->
<security:intercept-url pattern="/**" access="ROLE_USER" />
<security:http-basic />
</security:http>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider>
<!-- 配置默認(rèn)用戶(hù)官脓,用戶(hù)名:admin 密碼:123456 擁有權(quán)限:ROLE_USER -->
<security:user-service>
<security:user name="admin" password="123456"
authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>
在web.xml中添加
<!-- Loads Spring Security config file 這一步在springmvc中可以去掉
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:configs/spring-security.xml</param-value>
</context-param>
-->
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在上面的web.xml中注釋了一段xml文件协怒,這里可以再spring-servlet.xml中添加上,
<import resource="classpath:configs/spring-security.xml" />
在spring-security.xml中有一句卑笨,<security:http-basic />
如果不加這一句孕暇,那么使用的就是默認(rèn)的登錄頁(yè),加入這一句后赤兴,就會(huì)如tomcat妖滔、druid、dubbo等方式的瀏覽器彈窗驗(yàn)證桶良。OK~