前几天写了一个SpringBoot对拦截器的使用,在实际项目中,对一些情况需要做一些安全验证,比如在没有登录的情况下访问特定的页面应该解释的拦截处理。这一篇介绍使用SpringSecurity来做简单的安全控制,由于SpringSecurity比较复杂,如果有不对的地方可以大家一起学习。

新建项目,前端页面使用thymeleaf,加入security依赖,pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<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>com.dalaoyang</groupId>
<artifactId>springboot_security</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>springboot_security</name>
<description>springboot_security</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.15</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

配置文件本文就是将之前整合thymeleaf的配置拿了过来,代码如下:

##端口号
server.port=8888 ##去除thymeleaf的html严格校验
spring.thymeleaf.mode=LEGACYHTML5 #设定thymeleaf文件路径 默认为src/main/resources/templates
spring.freemarker.template-loader-path=classpath:/templates
#设定静态文件路径,js,css等
spring.mvc.static-path-pattern=/static/**
# 是否开启模板缓存,默认true
# 建议在开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
# 模板编码
spring.freemarker.charset=UTF-8

接下来是这篇文章重要的地方,新建一个SecurityConfig类,继承WebSecurityConfigurerAdapter类,重写configure(HttpSecurity httpSecurity)方法,其中/css/和/index的资源不需要验证,直接可以请求,/user/的资源需要验证,权限是USER,/admin/**的资源需要验证,权限是ADMIN,登录地址是/login,登录失败地址是/login_error,异常重定向到 /401,注销跳转到/logout。

注入AuthenticationManagerBuilder,在内存中创建一个用户dalaoyang,密码123的用户,权限是USER,代码如下:

package com.dalaoyang.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; /**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.config
* @email yangyang@dalaoyang.cn
* @date 2018/4/28
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter { // /css/**和/index的资源不需要验证,直接可以请求
// /user/**的资源需要验证,权限是USER /admin/**的资源需要验证,权限是ADMIN
// 登录地址是/login 登录失败地址是 /login_error
// 异常重定向到 /401
// 注销跳转到 /logout
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception{
httpSecurity
.authorizeRequests()
.antMatchers("/css/**","/index").permitAll()
.antMatchers("/user/**").hasRole("USER")
.antMatchers("/admin/**").hasRole("ADMIN")
.and()
.formLogin().loginPage("/login").failureUrl("/login_error")
.and()
.exceptionHandling().accessDeniedPage("/401"); httpSecurity.logout().logoutSuccessUrl("/logout");
} //内存中创建用户,用户名为dalaoyang,密码123,权限是USER
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("dalaoyang").password("123").roles("USER");
}
}

创建一个TestController负责跳转,代码如下:

package com.dalaoyang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; /**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.controller
* @email yangyang@dalaoyang.cn
* @date 2018/4/28
*/
@Controller
public class TestController { @RequestMapping("/")
public String index(){
return "index";
} @RequestMapping("/index")
public String index2(){
return "index";
} @RequestMapping("/user")
public String user(){
return "user/index";
} @RequestMapping("/admin")
public String admin(){
return "admin/index";
} @RequestMapping("/login")
public String login(){
return "login";
} @RequestMapping("/login_error")
public String login_error(Model model){
model.addAttribute("login_error", "用户名或密码错误");
return "login";
} @RequestMapping("/logout")
public String logout(Model model){
model.addAttribute("login_error", "注销成功");
return "login";
} @RequestMapping("/401")
public String error(){
return "401";
}
}

创建一个user/index.html,用于校验USER权限,没有登录的话不能直接访问,代码如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>user/index</title>
</head>
<body>
user/index <form th:action="@{/logout}" method="post">
<input type="submit" value="注销"/>
</form>
</body>
</html>

创建一个admin/index.html,只允许ADMIN权限访问,代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>admin</title>
</head>
<body>
admin/index
</body>
</html>

401页面,用于没有权限跳转:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>401</title>
</head>
<body>
401
</body>
</html>

index页面,任何权限都能访问

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
index
</body>
</html>

login页面,用于登录

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<h1>login</h1>
<form th:action="@{/login}" method="post">
<span th:text="${login_error}"></span>
<br/>
<input type="text" name="username">用户名<br/>
<input type="password" name="password">密码<br/>
<input type="submit" value="登录">
</form>
</body>
</html>

到这里就全部创建完成了,启动项目,访问http://localhost:8888/,如图,可以直接访问。

访问http://localhost:8888/user被拦截到http://localhost:8888/login,如图

先输入错误的密码,如图

然后输入用户名dalaoyang密码123,点击登录结果如图

访问http://localhost:8888/admin,如图,没有权限

我们在回到http://localhost:8888/user点击注销,如图

源码下载 :大老杨码云

个人网站:https://dalaoyang.cn

使用SpringSecurity的更多相关文章

  1. spring mvc 和spring security配置 spring-servlet.xml和spring-security.xml设置

    spring-servlet.xml配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmln ...

  2. 【JavaWeb】Spring+SpringMVC+MyBatis+SpringSecurity+EhCache+JCaptcha 完整Web基础框架(前言)

    一直希望能够搭建一个完整的,基础Web框架,方便日后接一些外快的时候,能够省时省力,终于花了一周的时间,把这个东西搞定了.特此写下此博客,一来是纪念,二来是希望能够为别人提供方便.顺带说一下,恩,组合 ...

  3. 【JavaWeb】SSM+SpringSecurity+EhCache+JCaptcha 完整Web基础框架(六)

    Showings 我个人的项目,当前不断地在更新. 我希望做成一个好项目,同时,也是在锻炼自己的技术. 在项目中发现问题,学习知识,是比较可取的一条路子. 这样学习到的知识,虽然分散,但是都很实用,而 ...

  4. 【JavaWeb】Spring+SpringMVC+MyBatis+SpringSecurity+EhCache+JCaptcha 完整Web基础框架(五)

    SpringSecurity(2) 好久没有写了,之前只写了一半,我是一边开发一边写Blog一边上班,所以真心没有那么多时间来维护Blog,项目已经开发到编写逻辑及页面部分了,框架基本上已经搭建好不会 ...

  5. 【JavaWeb】Spring+SpringMVC+MyBatis+SpringSecurity+EhCache+JCaptcha 完整Web基础框架(四)

    SpringSecurity(1) 其实啊,这部分我是最不想写的,因为最麻烦的也是这部分,真的是非常非常的麻烦.关于SpringSecurity的配置,让我折腾了好半天,网上的配置方式一大把,但总有一 ...

  6. 【JavaWeb】Spring+SpringMVC+MyBatis+SpringSecurity+EhCache+JCaptcha 完整Web基础框架(一)

    Spring+MyBatis 首先要搭建的是Spring+MyBatis的整合框架,毕竟Spring是整个Web框架的核心部位,而数据库操作是一切测试的基础嘛. 目录结构 ━java ┣ contro ...

  7. SSO单点登录Spring-Security & CAS使用手册

    1.1概述 1.1.1单点登录介绍 单点登录(Single Sign On , 简称 SSO )是目前比较流行的服务于企业业务整合的解决方案之一, SSO 使得在多个应用系统中,用户只需要登录一次就可 ...

  8. spring4.2.3+mybatis+spring-security配置文件

    1.web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi=&qu ...

  9. springmvc+spring-security+mybatis +redis +solar框架抽取

    参考文章:Spring MVC 3 深入总结: 第二章 Spring MVC入门 —— 跟开涛学SpringMVC 参考博客:http://www.cnblogs.com/liukemng/categ ...

  10. 安全框架 SpringSecurity 和 Shiro 对比

    突然再次很想理一下权限的事,但是实在不知道实际情况选哪个框架好,现在整理下网上的资料,做一下对比. 1.Spring-security 对spring 结合较好,如果项目用的springmvc ,使用 ...

随机推荐

  1. LeetCode(100):相同的树

    Easy! 题目描述: 给定两个二叉树,编写一个函数来检验它们是否相同. 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的. 示例 1: 输入: 1 1 / \ / \ 2 3 2 3 ...

  2. Best Free Hacking E-Books 2017 In PDF Format

    1.Best Free Hacking E-Books 2017 In PDF Format: 电子书籍下载地址 后续我会更新在我的百度云资源 上,需要的留言Black Belt Hacking &a ...

  3. java子类对象和成员变量的隐写&方法重写

    1.子类继承的方法只能操作子类继承和隐藏的成员变量名字类新定义的方法可以操作子类继承和子类新生命的成员变量,但是无法操作子类隐藏的成员变量(需要适用super关键字操作子类隐藏的成员变量.) publ ...

  4. 检查URL的可用性脚本

    #!/bin/bash check_url() { HTTP_CODE=$(curl -o /dev/ -s -) ];then echo "Warning: $1 Access failu ...

  5. SpringBoot系列七:SpringBoot 整合 MyBatis(配置 druid 数据源、配置 MyBatis、事务控制、druid 监控)

    1.概念:SpringBoot 整合 MyBatis 2.背景 SpringBoot 得到最终效果是一个简化到极致的 WEB 开发,但是只要牵扯到 WEB 开发,就绝对不可能缺少数据层操作,所有的开发 ...

  6. mysql 去除重复 Select中DISTINCT关键字的用法 在使用mysql时,有时需要查询出某个字段不重复的记录,虽然mysql提供 有distinct这个关键字来过滤掉多余的重复记录只保留一条,但往往只用它来返回不重复记录的条数,而不是用它来返回不重记录的所有值。其原因是 distinct只能返回它的目标字段,而无法返回其它字段,这个问题让我困扰了很久,用distinct不能解决的话,

      在使用mysql时,有时需要查询出某个字段不重复的记录,虽然mysql提供 有distinct这个关键字来过滤掉多余的重复记录只保留一条,但往往只用它来返回不重复记录的条数,而不是用它来返回不重记 ...

  7. IDEA的debug操作

  8. Inflated 3D ConvNet 【I3D】

    Two-Stream Inflated 3D ConvNet (I3D) HMDB-51: 80.9% and UCF-101: 98.0% 在Inception-v1 Kinetics上预训练 Co ...

  9. IDEA 创建Spring MVC项目搭建

    概述 IntelliJ IDEA是一款更加集成智能的开发工具,相对Myeclipse开发而言,使用起来相对更加的方便:初步手动使用IDEA搭建Spring MVC项目,现将操作流程整理记录如下. 环境 ...

  10. c_数据结构_顺序表

    #define OK 1 #define ERROR 0 #define OVERFLOW -2 #define LIST_INIT_SIZE 100 // 线性表存储空间的初始分配量 #define ...