• 导入SpringSecurity坐标

  • 在web.xml中配置过滤器

  • 编写spring-securiy配置文件

  • 编写自定义认证提供者

  • 用户新增时加密密码

  • 配置页面的login和logout

  • 获取登录用户的信息


一.SpringSecurity简介

  Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。

如果要对Web资源进行保护,最好的办法莫过于Filter,要想对方法调用进行保护,最好的办法莫过于AOP。Spring security对Web资源的保护,就是靠Filter实现的。

二.SpringSecurity的使用

1.导入SpringSecurity的坐标

<!-- SpringSecurity相关坐标 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>

2.在web.xml中配置过滤器

<?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">
<!-- 1.解决post乱码 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- 2.配置SpringMVC的前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定加载的配置文件 ,通过参数contextConfigLocation加载-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping> <!-- 3.配置SpringSecurity的过滤器(以一当十) -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/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>
</web-app>

3.编写SpringSecurity的配置文件(spring-security.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
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://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd"> <!-- 1.配置页面的放行规则(不需要登录验证的资源) -->
<http pattern="/*.html" security="none"></http>
<http pattern="/css/**" security="none"></http>
<http pattern="/img/**" security="none"></http>
<http pattern="/js/**" security="none"></http>
<http pattern="/plugins/**" security="none"></http>
<http pattern="/seller/add.do" security="none"></http> <!-- 2.页面的拦截规则 -->
<http use-expressions="false">
<!-- 2.1当前用户必须有ROLE_USER的角色 才可以访问根目录及所属子目录的资源 -->
<intercept-url pattern="/**" access="ROLE_USER"/>
<!-- 2.2表单登陆,默认用户名和密码的name属性为:username和password,也可在这里配置 -->
<form-login login-page="/shoplogin.html"
default-target-url="/admin/index.html"
authentication-failure-url="/shoplogin.html"
always-use-default-target="true"/>
<!-- 2.3关闭跨域攻击 -->
<csrf disabled="true"/> <!-- 2.4为了解决frame框架访问问题默认是deny不允许访问,改成同一域下可以进行访问-->
<headers>
<frame-options policy="SAMEORIGIN"/>
</headers>
<!-- 2.5配置登出功能(页面注销连接到“/logout"即可完成退出到指定页面) -->
<logout logout-success-url="/login.html"></logout>
</http> <!-- 3.认证管理器 -->
<authentication-manager>
<!-- 3.1认证提供者:这里是写成固定的,也可以自定义 -->
<authentication-provider>
<user-service>
<!-- 配置当前系统的用户 authorities该用户属于哪个角色:这里写成固定的 -->
<user name="admin" password="123456" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
<!-- 3.1认证提供者:这里是写成固定的,也可以自定义 -->
<!-- ======================================================== -->
<!-- 3.2通过自定义认证提供者,实现动态认证 -->
<authentication-provider user-service-ref="userDetailService">
<!-- 认证时,先对用户输入的密码加密再和数据库的对比 -->
<password-encoder ref="bcryptEncoder"></password-encoder>
</authentication-provider>
<!-- 3.2通过自定义认证提供者,实现动态认证 -->
</authentication-manager> <!-- 4.认证类:配置的方式进行注入 -->
<beans:bean id="userDetailService" class="cn.dintalk.service.UserDetailsServiceImpl">
<beans:property name="sellerService" ref="sellerService"></beans:property>
</beans:bean> <!-- 5.引用dubbo 服务 -->
<dubbo:application name="dintalk-shop-web" />
<dubbo:registry address="zookeeper://192.168.88.130:2181"/>
<!-- 5.1配置的方式注入sellerService -->
<dubbo:reference id="sellerService" interface=
"cn.dintalk.sellergoods.service.SellerService"></dubbo:reference> <!-- 6.配置密码加密方式 -->
<beans:bean id="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></beans:bean>
</beans:beans>

4.编写自定义认证提供者(如需自定义)

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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;
/**
* 用户的登录认证
* @author Mr.song
* @date 2019/06/06 12:26
*/
public class UserDetailsServiceImpl implements UserDetailsService { /**
* 提供set方法以注入sellerService
*/
private SellerService sellerService;
public void setSellerService(SellerService sellerService) {
this.sellerService = sellerService;
} @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//1.根据用户名查询数据库
TbSeller seller = sellerService.findOne(username);
//2.判断用户是否存在
if (seller != null){
//3.定义集合,封装用户的角色(这里角色少,写死.也可以从数据库查询)
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
if (seller.getStatus().equals("1")){//用户处于可以登录的状态
return new User(username,seller.getPassword(),grantedAuthorities);
}
}
//3.用户不存在,认证失败
return null;
}
}

5.用户新增时加密密码(如需加密)

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* 增加
* @param seller
* @return
*/
@RequestMapping("/add")
public Result add(@RequestBody TbSeller seller){
try {
//添加时进行密码的加密,登录时配置同样的加密器即可
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String newPws = passwordEncoder.encode(seller.getPassword());
seller.setPassword(newPws);
sellerService.add(seller);
return new Result(true, "增加成功");
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "增加失败");
}
}

6.配置页面的login和logout

<!-- 1.login的配置要点:默认,登录框的name属性分别为username和password(也可在配置中修改)
登录表单提交方式为post,登录链接为:/login-->
<form method="post" id="loginform" action="/login">
<input name="username" type="text" placeholder="邮箱/用户名/手机号">
<input name="password" type="password" placeholder="请输入密码">
<a onclick="document:loginform.submit()" target="_blank">登&nbsp;&nbsp;录</a>
</form> <!-- 2.logout的配置要点:默认,退出链接为:/logout即可 -->
<a href="/logout" >注销</a>

7.获取登录用户的信息

import org.springframework.security.core.context.SecurityContextHolder;
...
/**
* 获取用户登录名进行展示
* @return
*/
@RequestMapping("/showName")
public Map showName(){
//1.从认证处取得登录信息(除了username还可获取其他信息)
String name = SecurityContextHolder.getContext().getAuthentication().getName();
//2.构建Map并返回
HashMap<String, String> map = new HashMap<>();
map.put("name",name);
return map;
}

关注微信公众号,随时随地学习

SpringSecurity的简单使用的更多相关文章

  1. SpringSecurity的简单应用(一)

    java项目首先要提的就是jar包了,Springsecurity的jar下载地址:http://static.springsource.org/spring-security/site/downlo ...

  2. SpringSecurity配置,简单梳理

    生活加油:摘一句子: “我希望自己能写这样的诗.我希望自己也是一颗星星.如果我会发光,就不必害怕黑暗.如果我自己是那么美好,那么一切恐惧就可以烟消云散.于是我开始存下了一点希望—如果我能做到,那么我就 ...

  3. SpringSecurity:简单入门

    SpringSecurity能做什么 SpringSecurity是一个安全框架,使用它可以让我们的系统变得安全一点,它可以对登陆系统的用户进行验证和授权 一个安全的系统需要做的事情很多,比如:防SQ ...

  4. SpringSecurity的简单入门

    以下是大体思路 1.导入坐标 <properties> <spring.version>4.2.4.RELEASE</spring.version> </pr ...

  5. SpringBoot整合SpringSecurity简单实现登入登出从零搭建

    技术栈 : SpringBoot + SpringSecurity + jpa + freemark ,完整项目地址 : https://github.com/EalenXie/spring-secu ...

  6. web项目学习之spring-security

    转自<http://liukai.iteye.com/blog/982088> spring security功能点总结: 1. 登录控制 2. 权限控制(用户菜单的显示,功能点访问控制) ...

  7. springSecurity自定义认证配置

    上一篇讲了springSecurity的简单入门的小demo,认证用户是在xml中写死的.今天来说一下自定义认证,读取数据库来实现认证.当然,也是非常简单的,因为仅仅是读取数据库,权限是写死的,因为相 ...

  8. spring-boot-learning-spring Security

    SpringSecurity的简单原理: 一旦启用了Spring Security,Spring IoC容器就会为你创建一个名称为springSecurityFilterChain 的Spring B ...

  9. Java-Springboot-集成spring-security简单示例(Version-springboot-2-1-3-RELEASE

    使用Idea的Spring Initializr或者SpringBoot官网下载quickstart 添加依赖 1234 <dependency><groupId>org.sp ...

随机推荐

  1. oracle--Windows不能在本地计算机启动OracleDBConsoleorcl .错误代码1

    安装完数据库后能够启动,重新启动电脑后,手动启动就会报错. 现象: Windows 不能在 本地计算机 启动 OracleDBConsoleorcl.有关很多其它信息.查阅系统事件日志.假设这是非 M ...

  2. Coding Ninja 修炼笔记 (1)

    大家好啊~我又回来了. 这次主要是给大家带来一些提升 Coding 效率的建议. 效率都是一点一滴优化出来的,虽然每一条建议给你带来的提升可能都不大,但是积累起来,仍然是一股不可忽视的力量. 第一条 ...

  3. Xcode中使用git

    项目中添加git 也可在开始新建项目时勾选git,这是针对开始没有勾选git的情况 打开终端 cd 项目文件目录 //初始化一个代码仓库, git init //将当前目录及子目录中的文件标记为要添加 ...

  4. VMware一些使用心得

    这段时间VMware workstation用得较多,装了好几个虚拟机,有win2003,win2008,win7,还分32位,64位.装了这么多,要么是用于安装一些软件,比如oracle12c,因为 ...

  5. 变量的命名和if语句

    1. 计算机是什么 基本组成: cpu: 主频, 核数(16) 内存:大小(8G, 16G, 32G) 型号: DDR3, DDR4, DDR5,  主频(海盗船,玩家国度) 显卡: 显存.型号(N- ...

  6. (2)MyEclipse怎么关联本地Tomcat服务器

    1,在MyEclipse中点击服务器按钮: 2,选择“Configure Server” 3,在弹出面板中选择 [Servers]-[Tomcat]-[对应版本的服务器] 5,看上图,先选择Enabl ...

  7. mongodb09----replicattion set--健壮性

    replication set复制集 replicattion set 多台服务器维护相同的数据副本,提高服务器的可用性.一台是服务器出问题了另外2台还可以接收干,secondary平时保持只读状态, ...

  8. YTU 1006: Hero In Maze

    1006: Hero In Maze 时间限制: 1000 Sec  内存限制: 64 MB 提交: 72  解决: 22 题目描述 500年前,Jesse是我国最卓越的剑客.他英俊潇洒,而且机智过人 ...

  9. 删除oracle数据库用户的dba权限(当出现同一用户DBA可以登录,normal不能登录)“无法对SYS拥有的对象创建触发器”

    系统报错:“无法对SYS拥有的对象创建触发器”,搞不懂是什么原因了,到底这触发器要用什么用户才能建立啊? ORA-04089: 无法对 SYS 拥有的对象创建触发器 第一种方式: 首先,用sys用户a ...

  10. 3.ExtJs常用布局--layout详解(含实例)

    转自:https://blog.csdn.net/fifteen718/article/details/51482826