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. Eclipse-设置格式化代码时不格式化注释

    在Eclipse里设置格式化代码时不格式化注释 今天格式化代码 发现直接format会把注释也一块格式化了,有时候会把好好的注释弄的很乱.甚为头疼. 查阅之后解决办法如下: Windows -> ...

  2. Vivado中xilinx_courdic IP核(求exp指数函数)使用

    由于Verilog/Vhdl没有计算exp指数函数的库函数,所以在开发过程中可利用cordic IP核做exp函数即e^x值: 但前提要保证输入范围在(-pi/4—pi/4) 在cordic核中e^x ...

  3. 2017-2018 Exp5 MSF基础应用 20155214

    目录 Exp5 MSF基础应用 实验内容 渗透攻击 主要思路 知识点 Exp5 MSF基础应用 本次实验本实践目标是掌握metasploit的基本应用方式,重点常用的三种攻击方式的思路. 主动攻击:m ...

  4. 20155318 Exp1 PC平台逆向破解(5)M

    20155318 Exp1 PC平台逆向破解(5)M 实践目标 本次实践的对象是一个名为pwn1的linux可执行文件. 该程序正常执行流程是:main调用foo函数,foo函数会简单回显任何用户输入 ...

  5. 20155323刘威良 网络对抗 Exp2 后门原理与实践

    20155323 刘威良<网络攻防>Exp2后门原理与实践 实验内容 (1)使用netcat获取主机操作Shell,cron启动 (0.5分) (2)使用socat获取主机操作Shell, ...

  6. 【Win32 API】利用SendMessage实现winform与wpf之间的消息传递

    原文:[Win32 API]利用SendMessage实现winform与wpf之间的消息传递 引言    有一次心血来潮,突然想研究一下进程间的通信,能够实现消息传递的方法有几种,其中win32ap ...

  7. Node.js 下载路径/微软产品下载路径

    https://nodejs.org/en/ https://www.microsoft.com/en-us/download //微软官方下载地址,可以下载VS2015  SQL 等 微软产品

  8. [清华集训2015 Day1]主旋律-[状压dp+容斥]

    Description Solution f[i]表示状态i所代表的点构成的强连通图方案数. g[i]表示状态i所代表的的点形成奇数个强连通图的方案数-偶数个强连通图的方案数. g是用来容斥的. 先用 ...

  9. Android与Libgdx入门实例

    本文讲解如何实现Android与Libgdx各自的Hello World过程. 1. Android版Hello World 点击Eclipse快捷方式,选择New Android Applicati ...

  10. idea 迁移maven项目出现导入仓库半天没反应的问题解决

    可以先参考: https://www.cnblogs.com/kinome/p/10289212.html 然后再看看maven配置文件是否正确,项目进行迁移时,如果环境不同,比如一个是使用的自定义m ...