springsecurity实战
springsecurity是一种安全性框架,主要用于进行权限验证,下面是其基本使用方法:
- pom.xml
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.11</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
设置filterproxy
filterproxy是一个特殊的拦截器,用于拦截请求.在springsecurity中,我们需要注册DelegatingFilterProxy.只需要一个继承了
AbstractSecurityWebApplicationInitializer的类即可,spring会自动找到它,并且在web容器注册
/**
* 开启springsecurity
*/
public class SecurityWebInitializer extends AbstractSecurityWebApplicationInitializer{
}
编写安全性配置
我们需要安全性配置来配置对应的安全属性.注意,该配置类应该在继承AbstractSecurityWebApplicationInitializer的类
的子包下.
全部的安全配置见下:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
DataSource dataSource;
@Autowired
UserRepository userRepository;
@Bean
public SaltSource saltSource() {
//设置盐为hlhdidi
return new SaltSource() {
@Override
public Object getSalt(UserDetails userDetails) {
return "hlhdidi";
}
};
}
// 设置盐,用户服务service和md5编码
@Bean
public AuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(new UserInfoService(userRepository));
provider.setPasswordEncoder(new Md5PasswordEncoder());
provider.setSaltSource(saltSource());
return provider;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// 对/user进行认证,对于其他请求允许通过
http.authorizeRequests().antMatchers("/user").authenticated()
.antMatchers("/item/**").authenticated()
.antMatchers("/item/**").hasAuthority("ADMIN") //item/**的请求需要权限验证.
.anyRequest().permitAll(); // 其他请求允许通过
// loginPage是调用/login返回的接口,登出成功访问的url为/home,开通rememberMe.
http.formLogin().loginPage("/login").and().logout().logoutSuccessUrl("/home")
.and().rememberMe()
.tokenValiditySeconds((2419200)).key("userKey");//设置token时间和私钥名称.
// 关闭csrf,否则logout会有问题
http.csrf().disable();
}
}
rememberMe
上面的安全配置开启了rememberMe,这里我们需要的就是提供rememberMe的选项,可以看看login.html页面,它提供了rememberMe的
checkbox,它在Login.html页面里.
<!--springsecurity会自动识别这个Login..-->
<form name="f" th:action="@{/login}" method="post">
username : <input type="text" name="username" /><br/>
password : <input type="password" name="password"/> <br/>
<input type="submit" value="LOGIN"/>
<!--checkbox会被识别-->
remember me :<input id="remember_me" name="remember-me" type="checkbox"/>
</form>
自定义的用户服务
即UserDetailService.如下:
public class UserInfoService implements UserDetailsService {
UserRepository userRepository;
public UserInfoService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
UserInfo user = userRepository.findUserByUsername(username);
if(user != null) {
List<GrantedAuthority> authorities = new ArrayList<>();
// 设置用户的权限.
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return new User(user.getUsername(),user.getPassword(),authorities);
}
// 抛出异常不会打印在日志里面,会调回登录页面
throw new UsernameNotFoundException("can not found username !");
}
}
保护视图
采用thymeleaf的一些标签可以去保证某些连接不被没权限的用户访问,如下所示:
首先需要引入thymeleaf对应的springsecurity标签库
<html lang="en" xmlns = "http://www.w3.org/1999/xhtml"
xmlns:th = "http://www.thymeleaf.org"
xmlns:sec = "http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
接着使用标签:
<span sec:authorize-url="/item/detail">
<td align="center" width="150px"><a th:href="@{'/item/detail/' + ${i.id}}">详情</a></td>
</span>
- 配置错误页面
需要注意的是springsecurity如果没有权限访问会跳转到一个默认的错误页面.因此我们需要配置错误页面,只需在web.xml里面
声明即可.
<error-page>
<error-code>403</error-code>
<location>/WEB-INF/templates/error/error_403.html</location>
</error-page>
springsecurity实战的更多相关文章
- SpringSecurity实战记录(一)开胃菜:基于内存的表单登录小Demo搭建
Ps:本次搭建基于Maven管理工具的版本,Gradle版本可以通过gradle init --type pom命令在pom.xml路径下转化为Gradle版本(如下图) (1)构建工具IDEA In ...
- 你还不了解SpringSecurity吗?快来看看SpringSecurity实战总结~
SpringSecurity简介: 权限管理中的相关概念 主体 principal: 使用系统的用户或设备或从其他系统远程登录的用户等等,简单说就是谁使用系统谁就是主体. 认证 authentic ...
- SpringBoot学习笔记(十五:OAuth2 )
@ 目录 一.OAuth 简介 1.什么是OAuth 2.OAuth 角色 3.OAuth 授权流程 4.OAuth授权模式 4.1.授权码 4.2.隐藏式 4.3.密码式 4.4.凭证式 二.实践 ...
- SpringSecurity权限管理系统实战—一、项目简介和开发环境准备
目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战-三 ...
- SpringSecurity权限管理系统实战—二、日志、接口文档等实现
系列目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战 ...
- SpringSecurity权限管理系统实战—四、整合SpringSecurity(上)
目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战-三 ...
- SpringSecurity权限管理系统实战—六、SpringSecurity整合jwt
目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战-三 ...
- SpringSecurity权限管理系统实战—七、处理一些问题
目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战-三 ...
- SpringSecurity权限管理系统实战—八、AOP 记录用户、异常日志
目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战-三 ...
随机推荐
- Vue复选框的全选
<!DOCTYPE html><html> <head> <meta charset="utf-8"> ...
- Java学习笔记--Java开发坏境搭建
一.安装JDK http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 根据自己系统选择 ...
- ansible 远程以普通用户执行命令
1. ansible 10.0.0.1 -m raw -a "date" -u www 2.在ansible的主机配置文件中指定ssh_uservi/etc/ansible/hos ...
- abp 如何设置和访问嵌入资源(视图、css、js等)
1.设置文件为嵌入资源 2.在含有嵌入资源的程序集下的模版类下,配置暴露嵌入的资源. Configuration.EmbeddedResources.Sources.Add( new Embedded ...
- gitlab webhook php exec 调用 shell 脚本。shell 脚本中调用 git pull 命令无法执行。
情况如下: 我在ubuntu server 14.04 上面安装了gitlab,来托管项目代码.然后想通过gitlab的web hook 功能来做测试服务器代码自动化更新代码功能.现在遇到一个问题:就 ...
- 欢迎到我的新Blog!
https://winniechen.cn 里面的页面还不是很好看...争取改一下! 里面的题解大部分也会在这里更新! 谢谢各位捧场!
- 2.3《想成为黑客,不知道这些命令行可不行》(Learn Enough Command Line to Be Dangerous)——重命名,复制,删除
最常用的文件操作除了将文件列出来外,就应该是重命名,复制,删除了.正如将文件列出来一样,大多数现代操作系统为这些任务提供了用户图形界面,但是在许多场景中,用命令行还是会更方便. 使用mv命令重命名一个 ...
- 20155209 林虹宇 Exp9 Web安全基础
Exp9 Web安全基础 XSS 1.Phishing with XSS 跨站脚本攻击,在表单中输入超文本代码 在网页中形成一个自制的登陆表单,然后将结果反馈到自己的主机上. 攻击成功 2.Store ...
- 2017-2018 Exp7 网络欺诈技术防范 20155214
目录 Exp7 网络欺诈技术防范 实验内容 信息收集 知识点 Exp7 网络欺诈技术防范 实验内容 实验环境 主机 Kali 靶机 Windows 10 实验工具 平台 Metaploit 信息收集 ...
- 20155306 白皎 0day漏洞——漏洞利用原理之DEP
20155306 白皎 0day漏洞--漏洞利用原理之DEP 一.DEP机制的保护原理 1.为什么出现DEP? 溢出攻击的根源在于现代计算机对数据和代码没有明确区分这一先天缺陷,就目前来看重新去设计计 ...