spring security4.1.3配置以及踩过的坑
https://blog.csdn.net/honghailiang888/article/details/53520557
spring security完全可以作为一个专门的专题来说,有一个专题写的不错http://www.iteye.com/blogs/subjects/spring_security,我这里主要是针对4.1.3进行配置说明
一、所需的库文件
-
//spring-security
-
compile 'org.springframework.security:spring-security-web:4.1.3.RELEASE'
-
compile 'org.springframework.security:spring-security-config:4.1.3.RELEASE'
-
compile 'org.springframework.security:spring-security-taglibs:4.1.3.RELEASE'
二、web配置
从4以后security就只吃java配置了,具体可以看下《spring in action第四版》,我这里还是使用xml配置
过滤器配置,security是基于过滤器的,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>
需要注意的是,如果配置了sitemesh装饰器,如果在装饰器页面中用到了security,比如标签,那么security过滤器需要配置在sitemesh之前,否则装饰器页中的<sec:authorize>标签可能不起作用
-
<!-- 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>
-
-
<!--sitemesh装饰器放在spring security过来器的后面,以免装饰器页中的security不起作用-->
-
<filter>
-
<filter-name>sitemesh</filter-name>
-
<filter-class>
-
org.sitemesh.config.ConfigurableSiteMeshFilter
-
</filter-class>
-
<init-param>
-
<param-name>ignore</param-name>
-
<param-value>true</param-value>
-
</init-param>
-
<init-param>
-
<param-name>encoding</param-name>
-
<param-value>UTF-8</param-value>
-
</init-param>
-
</filter>
-
<filter-mapping>
-
<filter-name>sitemesh</filter-name>
-
<url-pattern>/*</url-pattern>
-
</filter-mapping>
装饰器页面中的使用
-
<sec:authorize access="!hasRole('ROLE_USER')">
-
<li>你好,欢迎来到Mango!<a href="<c:url value='/login'/>" class="current">登录</a></li>
-
</sec:authorize>
-
<sec:authorize access="hasRole('ROLE_USER')">
-
<li><sec:authentication property="principal.username"/>欢迎光临Mango!<a href="<c:url value='/logout'/>" class="current">退出</a></li>
-
</sec:authorize>
三、security配置文件配置
applicationContext-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.xsd
-
http://www.springframework.org/schema/security
-
http://www.springframework.org/schema/security/spring-security.xsd">
-
-
<http auto-config="true" use-expressions="true" >
-
<form-login
-
login-page="/login"
-
authentication-failure-url="/login?error"
-
login-processing-url="/login"
-
always-use-default-target="false"
-
authentication-success-handler-ref="myAuthenticationSuccessHandler" />
-
<!-- 认证成功用自定义类myAuthenticationSuccessHandler处理 -->
-
-
<logout logout-url="/logout"
-
logout-success-url="/"
-
invalidate-session="true"
-
delete-cookies="JSESSIONID"/>
-
-
<csrf disabled="true" />
-
<intercept-url pattern="/order/*" access="hasRole('ROLE_USER')"/>
-
</http>
-
-
<!-- 使用自定义类myUserDetailsService从数据库获取用户信息 -->
-
<authentication-manager>
-
<authentication-provider user-service-ref="myUserDetailsService">
-
<!-- 加密 -->
-
<password-encoder hash="md5">
-
</password-encoder>
-
</authentication-provider>
-
</authentication-manager>
-
-
</beans:beans>
这里配置了自定义登录界面/login,还需要配置控制器条撞到login.jsp页面,如果字段使用默认值为username和password,当然也可以用 form-login标签中的属性username-parameter="username"password-parameter="password"进行设置,这里的值要和登录页面中的字段一致。login.jsp
-
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
-
<%@ include file="../includes/taglibs.jsp"%>
-
-
<html>
-
<head>
-
<title>Mango-Login</title>
-
<meta name="menu" content="home" />
-
</head>
-
-
<body>
-
-
<h1>请登录!</h1>
-
-
<div style="text-align:center">
-
<form action="<c:url value='/login' />" method="post">
-
<c:if test="${not empty error}">
-
<p style="color:red">${error}</p>
-
</c:if>
-
<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>
-
</div>
-
-
</body>
-
</html>
其中,form action的值要和配置文件中login-process-url的值一致,提交后UsernamePasswordAuthenticationFilter才能对其进行授权认证。
另外认证是采用的自定义myUserDetailsService获取用户信息方式,由于该项目中集成的是Hibernate,所以自己定义了,security系统中是支持jdbc进行获取的
-
package com.mango.jtt.springSecurity;
-
-
import org.springframework.beans.factory.annotation.Autowired;
-
import org.springframework.security.core.authority.AuthorityUtils;
-
import org.springframework.security.core.userdetails.User;
-
import org.springframework.security.core.userdetails.UserDetails;
-
import org.springframework.security.core.userdetails.UserDetailsService;
-
import org.springframework.security.core.userdetails.UsernameNotFoundException;
-
import org.springframework.stereotype.Service;
-
-
import com.mango.jtt.po.MangoUser;
-
import com.mango.jtt.service.IUserService;
-
-
/**
-
* 从数据库中获取信息的自定义类
-
*
-
* @author HHL
-
*
-
*/
-
-
public class MyUserDetailsService implements UserDetailsService {
-
-
-
private IUserService userService;
-
-
/**
-
* 获取用户信息,设置角色
-
*/
-
-
public UserDetails loadUserByUsername(String username)
-
throws UsernameNotFoundException {
-
// 获取用户信息
-
MangoUser mangoUser = userService.getUserByName(username);
-
if (mangoUser != null) {
-
// 设置角色
-
return new User(mangoUser.getUserName(), mangoUser.getPassword(),
-
AuthorityUtils.createAuthorityList(mangoUser.getRole()));
-
}
-
-
throw new UsernameNotFoundException("User '" + username
-
+ "' not found.");
-
}
-
-
}
认证成功之后也是自定义了处理类myAuthenticationSuccessHandler,该处理类继承了SavedRequestAwareAuthenticationSuccessHandler,实现了保存请求信息的操作,如果不配置,默认的也是交给SavedRequestAwareAuthenticationSuccessHandler处理,因为在解析security配置文件时,如果没有配置会将此设置为默认值。
-
package com.mango.jtt.springSecurity;
-
-
import java.io.IOException;
-
-
import javax.servlet.ServletException;
-
import javax.servlet.http.HttpServletRequest;
-
import javax.servlet.http.HttpServletResponse;
-
-
import org.springframework.beans.factory.annotation.Autowired;
-
import org.springframework.security.core.Authentication;
-
import org.springframework.security.core.userdetails.UserDetails;
-
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
-
import org.springframework.stereotype.Component;
-
-
import com.mango.jtt.po.MangoUser;
-
import com.mango.jtt.service.IUserService;
-
-
/**
-
* 登录后操作
-
*
-
* @author HHL
-
* @date
-
*
-
*/
-
-
public class MyAuthenticationSuccessHandler extends
-
SavedRequestAwareAuthenticationSuccessHandler {
-
-
-
private IUserService userService;
-
-
-
public void onAuthenticationSuccess(HttpServletRequest request,
-
HttpServletResponse response, Authentication authentication)
-
throws IOException, ServletException {
-
-
// 认证成功后,获取用户信息并添加到session中
-
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
-
MangoUser user = userService.getUserByName(userDetails.getUsername());
-
request.getSession().setAttribute("user", user);
-
-
super.onAuthenticationSuccess(request, response, authentication);
-
-
}
-
-
-
}
认证失败则回到登录页,只不过多了error,配置为authentication-failure-url="/login?error" 控制类会对其进行处理
-
/**
-
*
-
*/
-
package com.mango.jtt.controller;
-
-
import org.springframework.stereotype.Controller;
-
import org.springframework.ui.Model;
-
import org.springframework.web.bind.annotation.RequestMapping;
-
import org.springframework.web.bind.annotation.RequestParam;
-
-
/**
-
* @author HHL
-
*
-
* @date 2016年12月8日
-
*
-
* 用户控制类
-
*/
-
-
public class UserController {
-
-
/**
-
* 显示登录页面用,主要是显示错误信息
-
*
-
* @param model
-
* @param error
-
* @return
-
*/
-
-
public String login(Model model,
-
@RequestParam(value = "error", required = false) String error) {
-
if (error != null) {
-
model.addAttribute("error", "用户名或密码错误");
-
}
-
return "login";
-
}
-
}
另外,从spring security3.2开始,默认就会启用csrf保护,本次将csrf保护功能禁用<csrf disabled="true" />,防止页面中没有配置crsf而报错“Could not verify the provided CSRF token because your session was not found.”,如果启用csrf功能的话需要将login和logout以及上传功能等都需要进行相应的设置,因此这里先禁用csrf保护功能具体可参考spring-security4.1.3官方文档
四,后面会对认证过程,以及如何认证的进行详细说明。
完整代码:http://download.csdn.net/detail/honghailiang888/9705858
或 https://github.com/honghailiang/SpringMango
Spring安全权限管理(Spring Security)
1.spring Security简要介绍
Spring Security以前叫做acegi,是后来才成为Spring的一个子项目,也是目前最为流行的一个安全权限管理框架,它与Spring紧密结合在一起。
Spring Security关注的重点是在企业应用安全层为您提供服务,你将发现业务问题领域存在着各式各样的需求。银行系统跟电子商务应用就有很大的不同。电子商务系统与企业销售自动化工具又有很大不同。这些客户化需求让应用安全显得有趣,富有挑战性而且物有所值。Spring Security为基于J2EE的企业应用软件提供了一套全面的安全解决方案。
2.为Spring Security配置过滤器和其他参数
要使用Spring Security,首先就是在web.xml中为它配置过滤器, 其次因为我的spring配置文件是放在WEB-INF下的,因此还要配置上下文的参数,最后添加spring的监听器:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5" xmlns="http://<a href="http://lib.csdn.net/base/17" class='replace_word' title="Java EE知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Java</a>.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <!-- 配置上下文参数,指定spring配置文件的位置 -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/spring-*.xml</param-value>
- </context-param>
- <!-- 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>
- <listener>
- <listener-class>
- org.springframework.web.context.ContextLoaderListener
- </listener-class>
- </listener>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <login-config>
- <auth-method>BASIC</auth-method>
- </login-config>
- </web-app>
3.配置security(spring-security.xml)
- <?xml version="1.0" encoding="UTF-8"?>
- <!-- 这里必须使用security的命名空间,提供了beans这个假名 -->
- <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-2.0.xsd
- http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">
- <!-- Spring Security采用就近原则,有多个约束时,从上至下只要找到第一条满足就返回,因此因该将最严格的约束放在最前面,而将最宽松的约束放在最后面.auto-config属性可以让spring security为我们自动配置几种常用的权限控制机制,包括form,anonymous, rememberMe等。当然你也可以手工配置。-->
- <http auto-config="true">
- <!-- 我们利用intercept-url来判断用户需要具有何种权限才能访问对应的url资源,可以在pattern中指定一个特定的url资源,也可以使用通配符指定一组类似的url资源。例子中定义的两个intercepter-url,第一个用来控制对/security/**的访问,第二个使用了通配符/**,说明它将控制对系统中所有url资源的访问。 -->
- <intercept-url pattern="/security/**" access="ROLE_ADMIN" />
- <intercept-url pattern="/**" access="ROLE_ADMIN,ROLE_USER" />
- <intercept-url pattern="/login.jsp*" filters="none" />
- <logout logout-url="/logout.jsp"
- logout-success-url="/j_spring_security_check" />
- </http>
- <!-- 使用内存权限管理的配置信息, 在tomcat启动时,会加载这个文件并一直保存在内存中,知道应用程序重启,所以也叫内存权限管理
- <authentication-provider>
- <user-service>
- <user name="admin" password="tomcat" authorities="ROLE_ADMIN"/>
- <user name="liky" password="redhat" authorities="ROLE_USER"/>
- </user-service>
- </authentication-provider>
- -->
- <!-- 使用<a href="http://lib.csdn.net/base/14" class='replace_word' title="MySQL知识库" target='_blank' style='color:#df3434; font-weight:bold;'>数据库</a>作为权限管理的来源,data-source-ref指定了数据源,所指定的数据源必须包含users, authorities表,并符合security的定义规范 -->
- <authentication-provider>
- <jdbc-user-service data-source-ref="dataSource" />
- </authentication-provider>
- </beans:beans>
4.数据源的配置(spring-common.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"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
- <!-- 定义数据源 -->
- <bean id="dataSource"
- class="org.apache.commons.dbcp.BasicDataSource">
- <property name="driverClassName"
- value="com.<a href="http://lib.csdn.net/base/14" class='replace_word' title="MySQL知识库" target='_blank' style='color:#df3434; font-weight:bold;'>MySQL</a>.jdbc.Driver">
- </property>
- <property name="url" value="jdbc:mysql://localhost:3306/csu"></property>
- <property name="username" value="root"></property>
- <property name="password" value="redhat"></property>
- <property name="maxActive" value="100"></property>
- <property name="maxIdle" value="30"></property>
- <property name="maxWait" value="300"></property>
- <property name="defaultAutoCommit" value="true"></property>
- </bean>
- </beans>
5.项目的目录结构
6. 数据库脚本
- /-- 注意这里的脚本是MYSQL的,因此在你演示这个实例的时候,要加入MySQL的驱动包 --/
- create table users
- (
- username varchar(50) primary key,
- password varchar(50),
- enabled tinyint(1)
- );
- create table authorities
- (
- id int auto_increment primary key,
- username varchar(50),
- authority varchar(50),
- constraint fk_authorities_users foreign key(username) references users(username)
- );
- create unique index ix_auth_username on authorities (username,authority);
7.部署和配置的要点说明
这是一个Spring Security的数据库认证实例,要注意以下几点:
(1)请自行加入Spring必须的包,Spring security的包和MySQL的驱动包,当然你也可以换成其他的数据库,但是你要相应的修改spring-common.xml中的dataSource部分
(2)数据库中的两个表users,authorites必须完全按照脚本所示来定义,也就是说表的名字不能修改.
(3)users表必须包含username,password,enabled字段,这三个字段是绝对不能少的,也不能修改类型.另外enabled一定要为1才能登录
(4)authorities表必须包含username字段,这个字段引用users的username作为外键,authority字段就是角色的名字,角色名字必须满足ROLE_XXX的格式(例如:ROLE_ADMIN,ROLE_USER,ROLE_MAMAGER)
(5)如果一个用户有多个角色,不要将多个角色放在一起用逗号隔开.而是每个角色定义一条记录(例如:abu有ROLE_ADMIN,ROLE_USER两个角色,那么应该定义两条记录: 一条为abu, ROLE_USER,另一条为abu, ROLE_ADMIN.而不是只有一条:abu, ROLE_ADMIN,ROLE_USER)
(6)你可以给authorities表添加一个id字段作为主键.
java新手自学群 626070845
java/springboot/hadoop/JVM 群 4915800
Hadoop/mongodb(搭建/开发/运维)Q群481975850
GOLang Q1群:6848027
GOLang Q2群:450509103
GOLang Q3群:436173132
GOLang Q4群:141984758
GOLang Q5群:215535604
C/C++/QT群 1414577
单片机嵌入式/电子电路入门群群 306312845
MUD/LIB/交流群 391486684
Electron/koa/Nodejs/express 214737701
大前端群vue/js/ts 165150391
操作系统研发群:15375777
汇编/辅助/破解新手群:755783453
大数据 elasticsearch 群 481975850
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!