互联网项目中,安全与权限控制是不可回避的问题,为了解决这一些列问题,许多安全框架应运而生了。这些框架旨在帮我们解决公用的安全问题,让我们的程序更加健壮,从而让程序员全身心投入到业务开发当中。那么SpringSecurity出自于大名鼎鼎的Spring家族,同时能与SpringBoot,SpringCloud无缝集成,它也是业界流行的安全框架之一。

一、SpringSecurity的准备工作

注意:本示例是基于注解的springmvc构建,SpringBoot的版本对应的是2.0.3.REALEASE。Spring版本5.0.7REALEASE,SpringSecurity的版本是5.0.5

首先添加SpringSecurity的依赖:

compile('org.springframework.boot:spring-boot-starter-security')

紧接着按照如下目录规范创建

app包下主要为Root WebApplicationContext提供配置,而web包下主要是为servlet WebApplicationContext提供相关配置,这种方式更符合WebApplicationContext的层次化规范,同时也方便管理配置

二、实现app包下的配置

2.1、WebSecurityInitializer

package com.bdqn.lyrk.security.study.app.config;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

/**
* 这个类可以在添加springSecurity核心过滤器之前或之后做一些我们需要的操作
*
* @author chen.nie
* @date 2018/6/8
**/
public class WebSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}

2.2、WebSecurityConfig

package com.bdqn.lyrk.security.study.app.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
import org.springframework.security.core.userdetails.User; /**
* spring-security的相关配置
*
* @author chen.nie
* @date 2018/6/7
**/
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override
protected void configure(HttpSecurity http) throws Exception {
/*
1.配置静态资源不进行授权验证
2.登录地址及跳转过后的成功页不需要验证
3.其余均进行授权验证
*/
http.
authorizeRequests().antMatchers("/static/**").permitAll().
and().authorizeRequests().anyRequest().authenticated().
and().formLogin().loginPage("/login").successForwardUrl("/toIndex").permitAll();
} @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
/*
在内存中创建用户
*/
User.UserBuilder users = User.withDefaultPasswordEncoder();
auth.inMemoryAuthentication().withUser(users.username("admin").password("123").roles("ADMIN"));
}
}

  该类主要是设置安全配置注意使用@EnableWebSecruity注解,我们可以在这里设置Http的安全配置和最基本的认证配置等,其中在该代码里设置静态资源 登录页 和登录成功需要跳转的页面不用认证,另外基于内存设置了用户admin

  另外:loginPage()里的值即为跳转页面的路径又为处理登录验证的路径。当get请求时为前者而post请求时为后者

2.3、WebAppConfig

package com.bdqn.lyrk.security.study.app;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; /**
* 主配置类
*
* @author chen.nie
* @date 2018/6/8
**/
@Configuration
@ComponentScan
@PropertySource("classpath:application.properties")
public class WebAppConfig { @Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}

三、实现WebMvc的配置

3.1、初始化DispatcherServlet配置

WebStartupInitializer:

package com.bdqn.lyrk.security.study.web;

import com.bdqn.lyrk.security.study.app.WebAppConfig;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class WebStartupInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{WebAppConfig.class};
} @Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebMvcConfig.class};
} @Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}

在这里注意配置RootConfigClass为WebAppConfig,ServletConfigClass为WebMvcConfig

3.2、创建WebMvcConfig

package com.bdqn.lyrk.security.study.web;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView; @Configuration
@ComponentScan
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer { /**
* 创建视图解析器
* @return
*/
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
} /**
* 处理静态资源
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/").setCachePeriod(60 * 2);
}
}

3.3、创建Controller

package com.bdqn.lyrk.security.study.web.controller;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; @Controller
public class LoginController { @PostMapping("/toIndex")
public String index(ModelMap modelMap) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
modelMap.put("user", user);
return "main/index";
} @GetMapping("/login")
public String login() { return "login";
}
}

四、页面设置

4.1、登录页

login.jsp:

<%--
Created by IntelliJ IDEA.
User: chen.nie
Date: 2018/6/8
Time: 上午9:49
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!doctype html>
<html> <head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Amaze UI Admin index Examples</title>
<meta name="description" content="这是一个 index 页面">
<meta name="keywords" content="index">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="renderer" content="webkit">
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link rel="icon" type="image/png" href="assets/i/favicon.png">
<link rel="apple-touch-icon-precomposed" href="assets/i/app-icon72x72@2x.png">
<meta name="apple-mobile-web-app-title" content="Amaze UI" />
<link rel="stylesheet" href="${request.contextPath}/static/assets/css/amazeui.min.css" />
<link rel="stylesheet" href="${request.contextPath}/static/assets/css/admin.css">
<link rel="stylesheet" href="${request.contextPath}/static/assets/css/app.css">
</head> <body data-type="login"> <div class="am-g myapp-login">
<div class="myapp-login-logo-block tpl-login-max">
<div class="myapp-login-logo-text">
<div class="myapp-login-logo-text">
Amaze UI<span> Login</span> <i class="am-icon-skyatlas"></i> </div>
</div> <div class="login-font">
<i>Log In </i> or <span> Sign Up</span>
</div>
<div class="am-u-sm-10 login-am-center">
<form class="am-form" action="/login" method="post">
<fieldset>
<div class="am-form-group">
<input name="username" type="text" class="" id="doc-ipt-email-1" placeholder="输入登录名">
</div>
<div class="am-form-group">
<input name="password" type="password" class="" id="doc-ipt-pwd-1" placeholder="设置个密码吧">
</div>
<p><button type="submit" class="am-btn am-btn-default">登录</button></p> </fieldset>
<input type="hidden" name="_csrf" value="${_csrf.token}" />
</form>
</div>
</div>
</div> <script src="${request.contextPath}/static/assets/js/jquery.min.js"></script>
<script src="${request.contextPath}/static/assets/js/amazeui.min.js"></script>
<script src="${request.contextPath}/static/assets/js/app.js"></script>
</body>

注意:1)表单属性action为httpSecurity的loginPage()配置地址

   2)表单为post方式提交

   3)input的name属性分别为username,password代表用户名,密码

   4)必须设置隐藏表单_csrf 如果不设置请http.csrf().ignoringAntMatchers()方法进行排除

4.2、 登录成功页

<%--
Created by IntelliJ IDEA.
User: chen.nie
Date: 2018/6/8
Time: 上午9:56
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
欢迎:${user.username}
</body>
</html>

  在成功页时打印出认证成功的用户.

随即当我们访问http://localhost:8080/toIndex时跳转至登录页:

登录成功时:

在实际应用中登录页可能要复杂的多,可能包括验证码或者其他业务。另外用户不可能都存在内存当中,关于更详细的验证问题,我们会在下篇讨论。

SpringSecurity学习之快速上手的更多相关文章

  1. 从0开始的Python学习001快速上手手册

    假设大家已经安装好python的环境了. Windows检查是否可以运行python脚本 Ctrl+R 输入 cmd 在命令行中输入python 如果出现下面结果,我们就可以开始python的学习了. ...

  2. 如何快速上手一个新技术之vue学习经验

    碰到紧急项目挪别人的vue项目过来直接改,但是vue是18年初看过一遍,18年底再来用,早就忘到九霄云外了,结果丢脸的从打开vue开始学,虽然之前在有道云笔记做了很多记录,然后没有系统整理.所以借这次 ...

  3. 新手学习Linux之快速上手分析

    一.起步 首先,应该为自己创造一个学习linux的环境--在电脑上装一个linux或unix 问题1:版本的选择 北美用redhat,欧洲用SuSE,桌面mandrake较多,而debian是技术最先 ...

  4. WebAPI调用笔记 ASP.NET CORE 学习之自定义异常处理 MySQL数据库查询优化建议 .NET操作XML文件之泛型集合的序列化与反序列化 Asp.Net Core 轻松学-多线程之Task快速上手 Asp.Net Core 轻松学-多线程之Task(补充)

    WebAPI调用笔记   前言 即时通信项目中初次调用OA接口遇到了一些问题,因为本人从业后几乎一直做CS端项目,一个简单的WebAPI调用居然浪费了不少时间,特此记录. 接口描述 首先说明一下,基于 ...

  5. 学习Git---20分钟git快速上手

    学习Git-----20分钟git快速上手  在Git如日中天的今天,不懂git都不好意思跟人说自己是程序猿.你是不是早就跃跃欲试了,只是苦于没有借口(契机). 好吧,机会就在今天. 给我20分钟,是 ...

  6. 如何比较Keras, TensorLayer, TFLearn ?——如果只是想玩玩深度学习,想快速上手 -- Keras 如果工作中需要解决内部问题,想快速见效果 -- TFLearn 或者 Tensorlayer 如果正式发布的产品和业务,自己设计网络模型,需要持续开发和维护 -- Tensorlayer

    转自:https://www.zhihu.com/question/50030898/answer/235137938 如何比较Keras, TensorLayer, TFLearn ? 这三个库主要 ...

  7. 学习Keras:《Keras快速上手基于Python的深度学习实战》PDF代码+mobi

    有一定Python和TensorFlow基础的人看应该很容易,各领域的应用,但比较广泛,不深刻,讲硬件的部分可以作为入门人的参考. <Keras快速上手基于Python的深度学习实战>系统 ...

  8. 【学习总结】快速上手Linux玩转典型应用-第7章-WebServer安装和配置讲解

    课程目录链接 快速上手Linux玩转典型应用-目录 目录 1. Apache的安装 2. Apache的虚拟主机配置及伪静态操作 3. Nginx的基本操作 4. Nginx伪静态的实现 5. 实例演 ...

  9. 【学习总结】快速上手Linux玩转典型应用-第6章-linux常用命令讲解

    课程目录链接 快速上手Linux玩转典型应用-目录 目录 1. 软件操作命令 2. 服务器硬件资源信息 3. 文件操作命令 4. Linux文本编辑神器vim与其他常用命令 5. 系统用户操作命令 6 ...

随机推荐

  1. php 16进制颜色代码转换为rgba,rgb格式

    <?php $rgb = hex2rgba('#FFFFFF', false, true); echo 'rgb: '.$rgb[0].','; echo $rgb[1].','; echo $ ...

  2. 学以致用十六-----Centos7.2编译安装mysql5.6.22

    一.系统环境 二.卸载系统自带的mariadb rpm -qa | grep db rpm -e --nodeps mariadb-libs-5.5.60 rpm -e --nodeps mariad ...

  3. 微信小程序两种滑动方式

    竖向滑动: <scroll-view scroll-y="true" style="height: 200rpx;"> <view style ...

  4. Write Markdown Syntax Online Document with Sphinx and Pandoc

    There is no doubt that we have to write doc while we are developing software. But How do you write d ...

  5. Codeforces Round #264 (Div. 2) D. Gargari and Permutations 多序列LIS+dp好题

    http://codeforces.com/contest/463/problem/D 求k个序列的最长公共子序列. k<=5 肯定 不能直接LCS 网上题解全是图论解法...我就来个dp的解法 ...

  6. Scala_对象

    对象 单例对象 Scala并没有提供Java那样的静态方法或静态字段,但是,可以采用 object关键字实现单例对象,具备和Java静态方法同样的功能. 可以看出,单例对象的定义和类的定义很相似,明显 ...

  7. python实现Telnet远程登陆到设备并执行命令

    #encoding=utf-8 import telnetlib import time def do_telnet(Host, username, password, finish, command ...

  8. HSmartWindowControl 之 摄像头实时显示( 使用 WPF )

    1.添加Halcon控件,创建WPF项目 在VS2013中创建一个WPF工程,然后添加halcon的控件和工具包,参见: HSmartWindowControl之安装篇 (Visual Studio ...

  9. 如何获取SQL中Print语句输出内容

    SqlConnection cn = new SqlConnection("server=my\\my2005;database=rdwhdata2005;user id=zjh;passw ...

  10. 在windows10上创建ASP.NET mvc5+Memcached服务

    感谢两位两位大佬: https://blog.csdn.net/l1028386804/article/details/61417166 https://www.cnblogs.com/running ...