首页 > 代码库 > 初识Spring security-添加security

初识Spring security-添加security

在pom.xml文件中添加包

<!-- Spring Security -->        <dependency>            <groupId>org.springframework.security</groupId>            <artifactId>spring-security-web</artifactId>            <version>${spring.security.version}</version>        </dependency>        <dependency>            <groupId>org.springframework.security</groupId>            <artifactId>spring-security-config</artifactId>            <version>${spring.security.version}</version>        </dependency>

 

在web.xml文件中添加配置
<!-- 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>
在HelloController文件中添加代码
@RequestMapping(value = "http://www.mamicode.com/admin**", method = RequestMethod.GET)    public ModelAndView adminPage() {        ModelAndView model = new ModelAndView();        model.addObject("title", "Spring Security Hello World");        model.addObject("message", "This is protected page!);        model.setViewName("admin");        return model;    }

添加模板文件admin.html,内容与hello.html一致

关键配置在spring-security.xml文件中
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:security="http://www.springframework.org/schema/security"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">    <security:http auto-config="true">        <security:intercept-url pattern="/admin**" access="hasRole(‘ROLE_USER‘)"/>    </security:http>    <security:authentication-manager>        <security:authentication-provider>            <security:user-service>                <security:user name="hongxf" password="123456" authorities="ROLE_USER" />            </security:user-service>        </security:authentication-provider>    </security:authentication-manager></beans>

 

表明系统中添加一个用户名是hongxf,密码是123456,角色是ROLE_USER的用户,并配置访问/admin路径及其子路径必须含有角色ROLE_USER。
启动应用,访问http://localhost:8080/admin,则会跳转到http://localhost:8080/login,默认登录页
技术分享
 输入错误的用户名和密码,则会显示
技术分享
输入正确的用户名和密码则会跳转到admin.html页面,说明简单的权限控制已经完成
 

初识Spring security-添加security