学习项目中用到了Spring Security进行权限管理,比较好用,使用到的方式是基于xml配置文件的,相比较java代码配置简洁很多,故作笔记整理共享
首先贴上全部spring security配置文件代码,还是一样,因为我这个是maven项目,所以需要提前在pom文件里写好依赖,以下pom文件内容仅供参考
<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>8080</port>
<!-- 请求路径 -->
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
依赖写好了,包都导好了后,接下来就是要打开web.xml文件进行相关配置了
首先我们应当在<context-param>下配置加载类路径的配置文件,和记载Spring配置文件是一样的
写好这个以后我们就应当写一个过滤器,名字为springSecurityFilterChain,名字切记不可写错,因为Spring-Security底层其实就是将springSecurityFilterChain交给springIOC容器来进行管理。
/*代表所有的都要经过该安全框架认证。
接下来就是该安全框架的具体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的角色" -->
<security:intercept-url pattern="/**" access="ROLE_USER"/>
<!-- 定义跳转的具体的页面 -->
<security:form-login
login-page="/login.jsp"
login-processing-url="/login.do"
default-target-url="/index.jsp"
authentication-failure-url="/failer.jsp"
authentication-success-forward-url="/pages/main.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>
-->
<security:global-method-security secured-annotations="enabled"/>
</beans>
这个文件是我自己后面进行了修改的,入门的话Spring security框架会提供一个默认的登录窗口,丑的要死,此处就直接跳过那个部分了,直接使用自己的页面。
首先我们使用了<security:http pattern/>配置不拦截的静态资源。
<security:intercept-url pattern="/**" access="ROLE_USER" />该配置代表所有路径都要ROLE_USER权限,不要丢了前面的ROLE_,这个非常重要
这个便是自定义的相关页面,相关属性见名知意,不作过多解释
接下来便是用户账号密码相关
该配置代表了使用配置文件里的账户名和密码,此处配置了一个用户名为admin,用户密码为admin,具有角色ROLE_USER,关于中间的{noop},代表了加密方式,noop代表不加密,使用明文密码,这样我们在登录的时候便可以直接使用admin这个密码了,至于{noop}详细的一些内容后续再说,此处先入门再说。
在实际开发中我们当然是需要根据数据库的账户密码来进行验证登录,以下为数据库登录的配置,被注释掉的部分是加密方式,此处先不使用这种方式,具体加密方式我们在java代码中来使用。
配置文件写完后我们该使用java代码来进行登录逻辑的编写了,而在这些开始之前,我们需要了解一个接口,UserDetails.
该接口的作用是用来封装当前认证的用户信息,因为是一个接口所以我们需要实现该接口,我们也可以使用SpringSecurity框架提供的UserDetails的实现类User来完成相关操作,以下是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接口只有一个方法,loadUserByUsername,该方法最终会返回一个UserDetails,而我们则需要实现这个接口,并封装UserDetails所需要的相关参数,最后返回该对象即可。
我们回归到Spring-Security框架配置文件内,因为我这里的登录操作是在service层中的userService里,所以我这里直接使用自定义的登录验证。
实现接口后然后重写loadUserByUsername的方法,返回一个UserDetails。
而在该类里首先要做的就是根据传过来的username参数,去数据库中查询出来相关信息,并封装到实体类中,我这里是一个叫UserInfo的实体类,dao层的数据库查询操作这里就不写了,很简单。
然后再将数据库中查询出来并封装好的UserInfo,封装到User类中,此User类是SpringSeciruty框架的那个,上面有作说明,我这里先贴上源码,具体功能对照上图可以看出来,如下图所示。
public interface UserDetails extends Serializable {
// ~ Methods
// ========================================================================================================
/**
* Returns the authorities granted to the user. Cannot return <code>null</code>.
*
* @return the authorities, sorted by natural key (never <code>null</code>)
*/
Collection<? extends GrantedAuthority> getAuthorities();
/**
* Returns the password used to authenticate the user.
*
* @return the password
*/
String getPassword();
/**
* Returns the username used to authenticate the user. Cannot return <code>null</code>.
*
* @return the username (never <code>null</code>)
*/
String getUsername();
/**
* Indicates whether the user's account has expired. An expired account cannot be
* authenticated.
*
* @return <code>true</code> if the user's account is valid (ie non-expired),
* <code>false</code> if no longer valid (ie expired)
*/
boolean isAccountNonExpired();
/**
* Indicates whether the user is locked or unlocked. A locked user cannot be
* authenticated.
*
* @return <code>true</code> if the user is not locked, <code>false</code> otherwise
*/
boolean isAccountNonLocked();
/**
* Indicates whether the user's credentials (password) has expired. Expired
* credentials prevent authentication.
*
* @return <code>true</code> if the user's credentials are valid (ie non-expired),
* <code>false</code> if no longer valid (ie expired)
*/
boolean isCredentialsNonExpired();
/**
* Indicates whether the user is enabled or disabled. A disabled user cannot be
* authenticated.
*
* @return <code>true</code> if the user is enabled, <code>false</code> otherwise
*/
boolean isEnabled();
}
先看两个最主要的属性,password和username,从UserInfo中取出并封装进去,然后是剩下几个boolean类型的参数,我这里全部选择true,剩下最后一个。
该方法返回一个集合,我们追踪下GrantedAuthority会发现这是个接口,而这个接口里只有一个方法,就是
返回一个String类型的玩意,而getAuthorities是返回一个集合,于是我们自己在Service层实现类中写上一个getAuthority方法,如下所示:
//返回一个角色描述集合
public List<SimpleGrantedAuthority> getAuthority(List<Role> roles){
List<SimpleGrantedAuthority> list = new ArrayList<SimpleGrantedAuthority>();
for (Role role:roles){
list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
}
return list;
}
该方法的作用是返回一个角色描述集合,而该角色是从数据库根据用户获取的,之前有说过ROLE_非常重要,因为我们在数据库中存储的一般都是ADMIN,USER这样的字符串,所以我们需要拼接一个ROLE_在前面,否则会抛异常,最后将该集合返回。
这样一来我们的User类就完成了,完工后的User类应该是写成这样的。
中间灰色的那个是idea的自动参数提示。
ok,到这一步就剩下之前说的那个坑了,也就是User这个类中的密码这个参数,前面拼接了一个{bcrypt},这个其实就是一开始使用配置文件的用户的时候那个{noop},如果我们数据库使用的账户的密码是明文的,比如admin,他的密码是123,那么我们就不能使用{bcrypt}而是应当使用{noop},如果我们保存的密码是加密后的,则应该使用对应的加密方式,所以接下来我们应当使用Spirng-Security的加密来新建一个账户试试,还是一样直接在Service层操作,Controller层从前端获取参数并封装调用Service的代码还请各位自主完成。
我这里新建了一个save方法,controller层调用并传递一个UserInfo过来,因为我们是需要对密码进行加密,所以我这里需要重新setPassword,首先我们需要将BCryptPasswordEncoder对象拿到
这样我们就对密码进行了加密了,加密后的密码大概就长这样,第一个123是我直接从数据库添加的,这个就是明文的密码,而剩余的都是加密后的,需要注意的是即使是不同的账户设置的密码是同一个,经过加密后的字符串都是不一样的。
因为我们使用了BCryptPasswordEncoder进行加密,所以在使用新建的加密密码账户登录的时候,我们应当在密码前面加上{bcrypt},否则登录不上去,而Spring-Security框架不仅仅只有这一个加密方式,还有比如MD5等多种加密方式,具体的后续再说吧,一样的,使用不同的加密方式则需要修改{bcrypt}里面的内容,到此Spring-Security安全框架的基本新建账户和数据库登录功能就到这里,里面还有很多源码没有分析,后续有时间再慢慢整理吧。