springsecurity是一个很早就流行的安全框架,只是后来shiro后来者居上,但sprngsecurity因其与spring的天生绑定关系,还是有大量的用户。本专辑将介绍springsecurity的使用。本节将以配置的方式展示springsecurity的使用。
1、环境约束
- idea2018.1
- maven3.1.6
2、操作步骤
- 基于idea创建一个maven的web工程,假设项目名称为springsecurity-demo-xml,端口为8080
https://www.jianshu.com/p/042073b7710b - pom.xml中加入依赖:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- SpringSecurity标签库依赖 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
- 在springsecurity-demo-xml/src/main/java下创建net.wanho.controller,net.wanho.domain,net.wanho.util三个包
- 在net.wanho.util包下面创建MyPasswordEncoder.java
package net.wanho.util;
import org.springframework.security.crypto.password.PasswordEncoder;
public class MyPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(charSequence.toString());
}
}
- 在net.wanho.damain包下面创建User.java:
package net.wanho.domain;
import java.io.Serializable;
public class User implements Serializable {
private Integer id;
private String username;
private String password;
private String roles;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRoles() {
return roles;
}
public void setRoles(String roles) {
this.roles = roles;
}
}
- 在net.wanho.controller包下面创建LoginController.java:
package net.wanho.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(@RequestParam(value = "error", required = false) String error, Model model) {
if (error != null) {
model.addAttribute("msg", "用户名或密码错误!");
return "login";
}
model.addAttribute("msg", "");
return "login";
}
@RequestMapping("/home")
public String welcome() {
return "home";
}
@RequestMapping("/logoutPage")
public String logoutPage() {
return "logoutPage";
}
@RequestMapping("/timeout")
public String timeout() {
return "timeout";
}
@RequestMapping("/error")
public String error() {
return "error";
}
@RequestMapping("/nopermission")
public String nopermission() {
return "nopermission";
}
}
- 在springsecurity-demo-xml/src/main/resources下创建spring文件夹
- 在springsecurity-demo-xml/src/main/resources/spring文件夹下创建springmvc.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<context:component-scan base-package="net.wanho.controller"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
- 在springsecurity-demo-xml/src/main/resources/spring文件夹下创建spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
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-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<beans:bean name="myPasswordEncoder" class="net.wanho.util.MyPasswordEncoder"/>
<http pattern="/login" security="none"></http>
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/home" access="hasRole('ROLE_USER')"/>
<intercept-url pattern="/secure/**" access="hasRole('ROLE_USER')" requires-channel="https"/>
<intercept-url pattern="/**" access="hasRole('ROLE_USER')" requires-channel="any"/>
<form-login login-page="/login"
login-processing-url="/loginForm"
default-target-url="/home"
authentication-failure-url="/login?error=error"
always-use-default-target="true"
username-parameter="username"
password-parameter="password"/>
<logout invalidate-session="true" logout-url="/logout" logout-success-url="/logoutPage"
delete-cookies="JSESSIONID"/>
<csrf disabled="true"/>
<access-denied-handler error-page="/nopermission"></access-denied-handler>
<session-management invalid-session-url="/timeout"></session-management>
</http>
<authentication-manager>
<authentication-provider>
<password-encoder ref="myPasswordEncoder"/>
<user-service>
<user name="ali" password="ali" authorities="ROLE_ADMIN"/>
<user name="xiaoli" password="xiaoli" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
- 修改web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--导入springmvc配置-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--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>
<!--加载security配置文件-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-*.xml</param-value>
</context-param>
</web-app>
- 在springsecurity-demo-xml/src/main/webapp/WEB-INF文件夹下创建jsp文件夹
- 在jsp文件夹下创建以下文件
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<span style="color: red;">${msg}</span>
<form action="/loginForm" method="post">
用户名:<input type="text" name="username"/> <br/>
密码:<input type="password" name="password"/> <br/>
<input type="submit" value="提交"/> <br/>
</form>
</body>
</html>
home.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
这里是主页
<a href="/logout">注销</a>
</body>
</html>
logoutPage.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
退出后跳转的主页
</body>
</html>
nopermission.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
没权限
</body>
</html>
overtime.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
session超时了
</body>
</html>
- 启动,测试
1,访问http://localhost:8080/abc,跳转到http://localhost:8080/login
2,输入账号密码 ali/ali,提示没权限
3,重新登录,输入xiaoli/xiaoli,跳转到http://localhost:8080/home
4,登陆成功之后,点击“注销”,则重新回到登录页面。
注意,这个例子中没有加入数据库,要加数据库则只需要修改authentication-provider。
以上就是spring与springsecurity通过xml配置整合的例子。