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. PAT B1034 有理数四则运算 (20 分)

    本题要求编写程序,计算 2 个有理数的和.差.积.商. 输入格式: 输入在一行中按照 a1/b1 a2/b2 的格式给出两个分数形式的有理数,其中分子和分母全是整型范围内的整数,负号只可能出现在分子前 ...

  2. jqgrid 谈谈给表格设置列头事件、行事件、内容事件

    往往我们需要给显示的jqgrid表格赋予事件功能,比如:列头事件.行事件.内容事件.需要的效果可能如下: 如你所见,以上的超链接和按钮均是绑定的事件.那分别如何实现这些事件的绑定呢? 一.行事件 行事 ...

  3. “System.Reflection.AmbiguousMatchException”类型的异常在 mscorlib.dll 中发生

    错误提示: “System.Reflection.AmbiguousMatchException”类型的异常在 mscorlib.dll 中发生,但未在用户代码中进行处理. 发现不明确的匹配. 问题原 ...

  4. DRUPAL7 : 安装中文版本时遇到的问题

    http://yeenav.com是基于Drupal 7+汉化资源 搭建. 期间遇到一些麻烦, 做个记录. 首先把语言包drupal-7.0.zh-hans.po 放在htdocs/drupal-7. ...

  5. 3D Touch开发技巧的笔记

    iPhone6s以及iPhone6s plus搭载iOS9,有一个新功能叫做3D Touch,这个功能有很大的用处,关键是要会用,这给交互方式又多了一个新的选择和思考,比如说游戏中的额外控制选项.绘图 ...

  6. 【服务器】Https服务配置

    1)利用openssl生成证书 2)再次修改nginx配置文件nginx.conf中的server配置 ① 是默认监听http请求的8080端口的 server    (再次修改,第一次是在 用ngi ...

  7. RegExp,实现匹配合法时间(24小时制)的正则表达式

    合法时间格式  00:00:00 - 23:59:59   格式分析:H + ":" + M + ":" + S   H-分析: 00:00:00 - 09:5 ...

  8. QT要点

    1. QT设计器最终会被解释为ui_**.h. 2. QString与init之间的转换: QString转int: bool bIsOk; int a = str.toInt( &bIsOk ...

  9. [CF1007B]Pave the Parallelepiped[组合计数+状态压缩]

    题意 \(t\) 组询问,给你 \(A, B, C\) ,问有多少组三元组 \((a, b, c)\) 满足他们任意排列后有: \(a|A,\ b|B,\ c|C\) . \(A,B,C,t\leq ...

  10. c++时间计算模块

    c++时间计算模块 可用于计算代码运行耗时.计算代码运行时间线(比如处理与运行时间相关函数). 该模块从实际项目中产生,使用方式仁者见仁智者见智,设计思想可供参考. 源码: //author: cai ...