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实战的更多相关文章

  1. SpringSecurity实战记录(一)开胃菜:基于内存的表单登录小Demo搭建

    Ps:本次搭建基于Maven管理工具的版本,Gradle版本可以通过gradle init --type pom命令在pom.xml路径下转化为Gradle版本(如下图) (1)构建工具IDEA In ...

  2. 你还不了解SpringSecurity吗?快来看看SpringSecurity实战总结~

    SpringSecurity简介:   权限管理中的相关概念 主体 principal: 使用系统的用户或设备或从其他系统远程登录的用户等等,简单说就是谁使用系统谁就是主体. 认证 authentic ...

  3. SpringBoot学习笔记(十五:OAuth2 )

    @ 目录 一.OAuth 简介 1.什么是OAuth 2.OAuth 角色 3.OAuth 授权流程 4.OAuth授权模式 4.1.授权码 4.2.隐藏式 4.3.密码式 4.4.凭证式 二.实践 ...

  4. SpringSecurity权限管理系统实战—一、项目简介和开发环境准备

    目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战-三 ...

  5. SpringSecurity权限管理系统实战—二、日志、接口文档等实现

    系列目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战 ...

  6. SpringSecurity权限管理系统实战—四、整合SpringSecurity(上)

    目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战-三 ...

  7. SpringSecurity权限管理系统实战—六、SpringSecurity整合jwt

    目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战-三 ...

  8. SpringSecurity权限管理系统实战—七、处理一些问题

    目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战-三 ...

  9. SpringSecurity权限管理系统实战—八、AOP 记录用户、异常日志

    目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战-三 ...

随机推荐

  1. ThinkCenter安装CentOS7

    重启电脑按F12选择从光盘启动: 选择install CentOS7,并按“E”键 进行编辑 编辑后,并按Ctrl+X 查看并找到你需要的盘符名称,如:sr0:随后强制重启电脑. 并修改如下: 按Ct ...

  2. QT的常用对话框的应用

    QMessageBox类提供了常用的弹出式对话框:提示.警告.错误.询问.关于对话框 需要添加头文件 #include <QMessageBox> MESSAGE  是要是显示的字符串 v ...

  3. 声明式API replica controller vs replica set 对比

    1.在命令式API中,你可以直接发出服务器要执行的命令,例如: “运行容器”.“停止容器”等. 在声明性API中,你声明系统要执行的操作,系统将不断向该状态驱动. 可以想象成手动驾驶和自动驾驶系统.( ...

  4. abp 模块系统

    abp模块系统:ABP理论学习之模块系统 ABP提供了构建模块并将这些模块组合起来创建应用的基础设施.一个模块可以依赖另一个模块.一般来说,一个程序集可以认为是一个模块.一个模块是由一个派生了AbpM ...

  5. Storm 运行例子

    1.建立Java工程 使用idea,添加lib库,拷贝storm中lib到工程中 2.拷贝wordcount代码 下载src包,解压找到 apache-storm-0.9.4-src\apache-s ...

  6. Swift使用AlamoFire超时设置和事件处理

    一直在写swift项目,正好碰到服务器部署,请求超时或者请求失败的问题,页面就卡着不动了.顺手解决一下吧 差了些资料,说要设置超时时间 方法一: static let sharedSessionMan ...

  7. 【转载】WINAPI宏

    原文:http://blog.sina.com.cn/s/blog_3f27dee60100qi4j.html 一直搞不懂为什么在函数前面加上WINAPI.CALLBACK等是什么意思 又不是返回值 ...

  8. Elasticsearch Query DSL 整理总结(一)—— Query DSL 概要,MatchAllQuery,全文查询简述

    目录 引言 概要 Query and filter context Match All Query 全文查询 Full text queries 小结 参考文档 引言 虽然之前做过 elasticse ...

  9. pandas 初识(四)

    Pandas 和 sqlalchemy 配合实现分页查询 Mysql 并获取总条数 @api.route('/show', methods=["POST"]) def api_sh ...

  10. photoshop cs6安装过程中安装程序遇到错误:请重启计算机,解决办法

    1.关闭防火墙和杀毒软件 2.删除注册表 依次展开HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager目录,找到其中的 ...