Spring Security入门【基于配置文件和数据库】

一、引言

安全包括两个主要操作。

“认证”,是为用户建立一个他所声明的主体。主题一般指用户,设备或可以在系统中执行动作的其他系统。简单来说,校验账号密码是否正确,就是"认证"的过程。
“授权”,指的是一个用户能否在你的应用中执行某个操作,在到达授权判断之前,身份的主题已经由身份验证过程建立了。简单来说,就是用户是否有权利执行某项操作,而这个授权的过程一般已在数据库约定好了。

对于安全框架,一般是基于数据库的操作,而Spring Security还可以基于配置文件进行认证与授权的操作。

 

二、Spring Security快速入门案例

1. 创建一个webapp项目

2. 导入pom依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
    <groupId>cn.itcats</groupId>
      <artifactId>springsecurity-test</artifactId>
      <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

	<properties>
		<spring.version>5.0.2.RELEASE</spring.version>
		<spring.security.version>5.0.1.RELEASE</spring.security.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<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>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<!-- java编译插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<configuration>
					<!-- 指定端口 -->
					<port>8090</port>
					<!-- 请求路径 -->
					<path>/</path>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

3.  在web.xml中配置filter

需要注意的是:【filter-name中的springSecurityFilterChain不可改变】

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	<display-name>SpringSecurity314</display-name>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-security.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<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>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
</web-app>

4.  默认webapp工程没有java和resources目录,创建并分别设置根路径和资源路径

5.在src/main/resources下创建spring-security.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:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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" use-expressions="false">
        <!-- intercept-url定义一个过滤规则 pattern表示对哪些url进行权限控制,ccess属性表示在请求对应 的URL时需要什么权限,
               默认配置时它应该是一个以逗号分隔的角色列表,请求的用户只需拥有其中的一个角色就能成功访问对应
        的URL -->
        <security:intercept-url pattern="/**" access="ROLE_USER" />
        <!-- auto-config配置后,不需要在配置下面信息 <security:form-login /> 定义登录表单信息
        <security:http-basic
                    /> <security:logout /> -->
    </security:http>
    <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                <security:user name="user" password="{noop}user"
                               authorities="ROLE_USER" />
                <security:user name="admin" password="{noop}admin"
                               authorities="ROLE_ADMIN" />
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>
</beans>

6.  运行工程

在控制台输入    mvn tomcat7: run

7.  访问 http://localhost:8090

实际上springsecurity为我们提供了一个登录界面,归结于在springsecurity.xml中选择了默认配置

<security:http auto-config="true" use-expressions="false">

在访问任意资源时,都会进行拦截

<security:intercept-url pattern="/**" access="ROLE_USER" />

我们在配置的时候设置了user具有ROLE_USER权限,所以在登录时如果使用user登录是可以成功登入系统的,而使用admin登录则显示  HTTP Status 403 - Forbidden 【权限不足】

    <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                <security:user name="user" password="{noop}user"
                               authorities="ROLE_USER" />
                <security:user name="admin" password="{noop}admin"
                               authorities="ROLE_ADMIN" />
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>

以上为springsecurity的快速入门案例,实际开发中我们需要设置自己的登录页面,在登录成功或者登录失败后,实现页面的自定义跳转。

 

三、自定义登录和跳转页面

1. 在webapp目录下创建三个自定义的登录和跳转页面

login.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
    <table>
    <tr>
        <td>用户名:</td>
        <td><input type="text" name="username" /></td>
    </tr>
        <tr> <td>密码:</td>
            <td><input type="password" name="password" /></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="登录" />
                <input type="reset" value="重置" /></td> </tr>
    </table>
</form>
</body>
</html>

success.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>
<body>
success html<br>
<a href="logout">退出</a> </body>
</html>

failer.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"> <title>Insert title here</title> </head>
<body>登录失败
</body>
</html>

2. 在spring-security.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:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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 security="none" pattern="/login.html" />
    <security:http security="none" pattern="/failer.html" />
    <security:http auto-config="true" use-expressions="false">
        <!-- 配置资料连接,表示任意路径都需要ROLE_USER权限 -->
        <security:intercept-url pattern="/**" access="ROLE_USER" />
        <!-- 自定义登陆页面,login-page
            自定义登陆页面 authentication-failure-url 用户权限校验失败之后才会跳转到这个页面,如果数据库中没有这个用户则不会跳转到这个页面。
            default-target-url 登陆成功后跳转的页面。 注:登陆页面用户名固定 username,密码password,action:login
        -->
        <security:form-login login-page="/login.html"
                             login-processing-url="/login" username-parameter="username"
                             password-parameter="password" authentication-failure-url="/failer.html"
                             default-target-url="/success.html"
                             authentication-success-forward-url="/success.html"
        />
        <!-- 登出, invalidate-session 是否删除session logout-url:登出处理链接 logout-success- url:登出成功页面
        注:登出操作 只需要链接到 logout即可登出当前用户 -->
        <security:logout invalidate-session="true" logout-url="/logout"
                         logout-success-url="/login.jsp" />
        <!-- 关闭CSRF,默认是开启的 -->
        <security:csrf disabled="true" />
    </security:http>
    <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                <security:user name="user" password="{noop}user"
                               authorities="ROLE_USER" />
                <security:user name="admin" password="{noop}admin"
                               authorities="ROLE_ADMIN" />
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>
</beans>

3. 控制台执行 mvn tomcat7:run

需要注意的是,使用admin登录仍然跳转到success.html页面,是因为default-target-url="/success.html"  。只要账号密码错误时候,才会触发authentication-failure-url="/failer.html"

 

四、Spring Security使用数据库认证

前面介绍的内容都是基于配置文件的认证和授权操作,在Spring Security中如果想要使用数据进行认证操作,有很多种操作方式,这里我们介绍使用UserDetails、UserDetailsService来完成操作。

UserDetails是一个接口,我们可以认为UserDetails作用是用于封装当前进行认证的用户信息,但由于其是一个接口,所以我们可以对其进行实现,也可以使用Spring Security提供的一个UserDetails的实现类User来完成操作。

UserDetails

 public interface UserDetails extends Serializable {
    Collection<? extends GrantedAuthority> getAuthorities();
    String getPassword();
    String getUsername();
    boolean isAccountNonExpired();
    boolean isAccountNonLocked();
    boolean isCredentialsNonExpired();
    boolean isEnabled();
}

User

public class User implements UserDetails, CredentialsContainer {
    private String password;
    private final String username;
    private final Set<GrantedAuthority> authorities;
    private final boolean accountNonExpired; //帐户是否过期 
    private final boolean accountNonLocked; //帐户是否锁定 
    private final boolean credentialsNonExpired; //认证是否过期 
    private final boolean enabled; //帐户是否可用
}

UserDetailsService也是一个接口,用于规范用户在认证时调用哪一个方法

UserDetailsService

public interface UserDetailsService {
    UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}

执行流程:

注意Dao层返回的应该是数据库users表中对应的实体类UserInfo对象,而在Service层中,需要处理UserInfo对象,以UserDetails对象返回

1. 编写spring-security.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:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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 pattern="/login.jsp" security="none"/>
    <security:http pattern="/failer.jsp" security="none"/>
    <security:http pattern="/css/**" security="none"/>
    <security:http pattern="/img/**" security="none"/>
    <security:http pattern="/plugins/**" security="none"/>

    <!--
    	配置具体的规则
    	auto-config="true"	不用自己编写登录的页面,框架提供默认登录页面
    	use-expressions="false"	是否使用SPEL表达式(没学习过)
    -->
    <security:http auto-config="true" use-expressions="false">
        <!-- 配置具体的拦截的规则 pattern="请求路径的规则" access="访问系统的人,必须有ROLE_USER或ROLE_ADMIN的角色" -->
        <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>

        <!-- 定义跳转的具体的页面,如果页面中默认name="username"或name="password"可以省略配置-->
        <security:form-login
                login-page="/login.jsp"
                login-processing-url="/login.do"
                default-target-url="/index.jsp"
                authentication-failure-url="/failer.jsp"
        />

        <!-- 关闭跨域请求 -->
        <security:csrf disabled="true"/>

        <!-- 退出 -->
        <security:logout invalidate-session="true" logout-url="/logout.do" logout-success-url="/login.jsp" />

    </security:http>

    <!-- 切换成数据库中的用户名和密码 -->
    <security:authentication-manager>
        <security:authentication-provider user-service-ref="userService">
            <!-- 配置加密的方式 -->
            <security:password-encoder ref="passwordEncoder"/>
        </security:authentication-provider>
    </security:authentication-manager>

    <!-- 配置加密类 -->
    <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

    <!-- 提供了入门的方式,在内存中存入用户名和密码
    <security:authentication-manager>
    	<security:authentication-provider>
    		<security:user-service>
    			<security:user name="admin" password="{noop}admin" authorities="ROLE_USER"/>
    		</security:user-service>
    	</security:authentication-provider>
    </security:authentication-manager>
    -->

</beans>

2. 创建自己的Service层并继承UserDetailsService,实现自己的Service层,并在容器中命名为userService【待改造】

public interface IUserService extends UserDetailsService{}
@Service("userService")
@Transactional
public class UserServiceImpl implements IUserService{
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        return null;
    }
}

 3. Dao层

public interface IUserDao {
    //返回数据库users表对应的UserInfo对象
    @Select(select * from users where username = #{username})
    public UserInfo findUserByUsername(String username);
}

4. 处理UserServiceImpl类

IDEA中使用快捷键control + H 查看UserDetails继承关系,其底层有一个User实现类

public User(String username, String password, Collection<? extends GrantedAuthority> authorities) {
        this(username, password, true, true, true, true, authorities);
    }

User类在构造时可以传入用户名、密码、以及该用户所具有的角色。

所以在UserServiceImpl可以通过创建User(org.springframework.security.core.userdetails.User)对象,并返回(因为User是UserDetails的实现类),返回之后spring-security底层就会根据返回的用户名、密码、角色信息进行认证与授权,决定是放行还是拦截。

@Service("userService")
@Transactional
public class UserServiceImpl implements IUserService{
    @Autowired
    private IUserDao iUserDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = iUserDao.findUserByUsername(username);
        //注意,密码需要加入前缀 {noop} 否则会出现500错误 no PasswordEncoder mapped for the id "null"
        User user = new User(userInfo.getUsername(),
                "{noop}"+ userInfo.getPassword(),getAuthority());
        return null;
    }

    //返回一个List集合,集合中装的是用户的角色信息
    public List<SimpleGrantedAuthority> getAuthority(){
        List<SimpleGrantedAuthority> roleList = new ArrayList<>();
        roleList.add(new SimpleGrantedAuthority("ROLE_USER"));
        roleList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        return roleList;
    }
}

以上的getAuthority()方法是自己手动添加的用户角色,实际上应该从数据库查出来,并且包装在UserInfo对象中,再次改造UserServiceImpl类

users表中的字段信息

设计UserInfo实体类时,除了以上字段还设计了StatusStr表示状态,还有List<Role>用户所具有的角色信息

public class UserInfo {
    private String id;
    private String username;
    private String email;
    private String password;
    private String phoneNum;
    private int status;
    private String statusStr;
    private List<Role> roles;
}

Role数据库表信息 

Role实体类信息

public class Role {
    private String id;
    private String roleName;
    private String roleDesc;
    private List<Permission> permissions;
    private List<User> users;
}

一个用户可以拥有多个角色,一个角色又对应多个用户,所以用户与角色之间是多对多关系,我们通过user_role中间表来描述其关联,在实体类中User中存在List,在Role中有List。

CREATE TABLE users_role(
    userId varchar2(32),
    roleId varchar2(32),
    PRIMARY KEY(userId,roleId),
    FOREIGN KEY (userId) REFERENCES users(id),
    FOREIGN KEY (roleId) REFERENCES role(id)
)

改造IUserDao

public interface IUserDao {

    //相当于XML中的ResultMap
    //根据用户column id去
    @Results(id = "findUserByUsername", value = {
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "password", column = "password"),
            @Result(property = "phoneNum", column = "phoneNum"),
            @Result(property = "status", column = "status"),
            @Result(property = "roles", column = "id", javaType = java.util.List.class,
                    many = @Many(select = "cn.itcats.dao.IRoleDao.findRoleListByUserId"))
    })
    //返回数据库users表对应的UserInfo对象
    @Select("select * from users where username = #{username}")
    public UserInfo findUserByUsername(String username);
}

书写IRoleDao

public interface IRoleDao {
    //根据用户id查询出所有对应的权限角色
    @Select("select * from role where id in (select roleId from users_role where userId = #{userId})")
    public List<Role> findRoleListByUserId(String userId);
}

改造后的UserServiceImpl

@Service("userService")
@Transactional
public class UserServiceImpl implements IUserService{
    @Autowired
    private IUserDao iUserDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = iUserDao.findUserByUsername(username);
        //注意,密码需要加入前缀 {noop} 否则会出现500错误 no PasswordEncoder mapped for the id "null"
        //该User构造器忽略了用户是否可用,即用户的state信息,如果不可用,也不能登录
        //需要的话可以使用User的另外一个构造器
//        User user = new User(userInfo.getUsername(),
//                "{noop}"+ userInfo.getPassword(),getAuthority(userInfo.getRoles()));
        User user = new User(userInfo.getUsername(),
                "{noop}"+ userInfo.getPassword(),userInfo.getStatus() == 0 ? false : true,
                true, true, true, getAuthority(userInfo.getRoles()));
        return null;
    }

    //返回一个List集合,集合中装的是用户的权限信息
    public List<SimpleGrantedAuthority> getAuthority(List<Role> roleList){
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        //在数据库中存储的是 ADMIN USER等信息, 需要手动拼接ROLE_
        roleList.stream().map(x -> authorityList.add(new SimpleGrantedAuthority("ROLE_" + x.getRoleName())));
        return authorityList;
    }
}

以上解决的问题:只有在用户账号密码正确、角色信息权限足够、用户账号状态正常时,才可以正常登录。

 

五、实现账号的登出功能

在spring-security.xml配置文件中加入

 <security:logout invalidate-session="true" logout-url="/logout.do" logout-success-
url="/login.jsp" />

只要访问/logout.do,就可以执行logout注销操作,session信息失效,在成功注销后跳转到/login.jsp页面

实际操作过程中只需要在前端页面的"注销/退出登录按钮",修改路径为/logout.do即可

 <a href="${pageContext.request.contextPath}/logout.do" class="btn btn-default btn-flat">注销</a>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值