首页 > 代码库 > 初识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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。