博客
关于我
SpringSecurity
阅读量:293 次
发布时间:2019-03-01

本文共 7548 字,大约阅读时间需要 25 分钟。

SpringSecurity入坑第一步:内存的权限验证与授权

构建依赖 pom.xml

4.0.0
com.shaojie.authority
authority
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
2.2.0.RELEASE
1.8
${java.version}
${java.version}
UTF-8
UTF-8
Hoxton.RC1
org.springframework.cloud
spring-cloud-dependencies
Hoxton.RC1
pom
import
org.projectlombok
lombok
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-security
org.springframework.boot
spring-boot-starter-data-jpa
org.projectlombok
lombok
mysql
mysql-connector-java
com.alibaba
druid
1.1.21
org.springframework.boot
spring-boot-maven-plugin

构建权限验证

package com.shaojie.authority.security;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;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.crypto.bcrypt.BCryptPasswordEncoder;/** * @author ShaoJie * @Date 2019/10/25 */@Configuration// 启动 SpringSecurity 的过滤器链@EnableWebSecuritypublic class SpringSecurityConfig extends WebSecurityConfigurerAdapter {       @Bean    public BCryptPasswordEncoder passwordEncoder() {           return new BCryptPasswordEncoder();    }    /**     * 授权     *     * @param auth     * @throws Exception     */    // 代替配置文件 
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // 老版本的角色设置 在 springboot 2.0 以后 不能这样设置// auth.inMemoryAuthentication()// .withUser("shaojie").password("123456")// .authorities("PRODUCT_ADD"); // inMemoryAuthentication 内存验证 auth.inMemoryAuthentication() .passwordEncoder(passwordEncoder()) .withUser("shaojie") .password(passwordEncoder().encode("123456")) // .roles("PRODUCT_ADD","PRODUCT_LIST"); // authorities 和 roles 都是设置权限 这里使用 roles 不能访问 403 .authorities("PRODUCT_ADD", "PRODUCT_LIST"); } /** * 验证 * * @param http * @throws Exception */ // 代替配置文件
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() // antMatchers 设置拦截的请求 hasAnyAuthority 设置所拥有的角色访问权限 .antMatchers("/product/add").hasAnyAuthority("PRODUCT_ADD") .antMatchers("/product/update").hasAnyAuthority("PRODUCT_UPDATE") .antMatchers("/product/list").hasAnyAuthority("PRODUCT_LIST") .antMatchers("/product/delete").hasAnyAuthority("PRODUCT_DELETE") // permitAll 所有的权限都能访问 .antMatchers("/login").permitAll() .antMatchers("/**") // fullyAuthenticated 不允许匿名用户查看 .fullyAuthenticated() .and() // httpbasic 登录 // .httpBasic(); // 表单登录 登录请求的页面 .formLogin().loginPage("/login") // 修改 spring 提供的 默认登陆参数 // .usernameParameter("name") // .passwordParameter("password") .and() // 开启记住我功能 .rememberMe() .and() // 开启登出 .logout() .and() // 禁用跨域的保护 .csrf().disable(); }}

构建错误页面配置

验证没有权限时跳转

package com.shaojie.authority.security;import org.springframework.boot.web.server.ConfigurableWebServerFactory;import org.springframework.boot.web.server.ErrorPage;import org.springframework.boot.web.server.WebServerFactoryCustomizer;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.HttpStatus;/** * @author ShaoJie * @Date 2019/10/25 */@Configurationpublic class ErrorPageConfig {       // 使用 WebServerFactoryCustomizer 接口替换 EmbeddedServletContainerCustomizer 组件完成对嵌入式Servlet容器的配置    @Bean    public WebServerFactoryCustomizer
webServerFactoryCustomizer(){ return new WebServerFactoryCustomizer
() { @Override public void customize(ConfigurableWebServerFactory factory) { factory.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN,"/403")); } }; }}
login.html
    
Title

登录页面

账号:
密码:

值得注意一下这里的<input>的属性name

官方源码 写的很清楚 默认就是 usernamepassword

* protected void configure(HttpSecurity http) throws Exception {        * 		http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin()	 * 				.usernameParameter("username") // default is username	 * 				.passwordParameter("password") // default is password	 * 				.loginPage("/authentication/login") // default is /login with an HTTP get	 * 				.failureUrl("/authentication/login?failed") // default is /login?error	 * 				.loginProcessingUrl("/authentication/login/process"); // default is /login	 * 																		// with an HTTP	 * 																		// post	 * 	}
index.html
    
我的页面以下是网站的功能
商品的添加
商品修改
商品的查询
商品的删除
403.html
    
错误页面 你没有权限访问
add.html
    
产品的增加 产品的增加
delete.html
    
产品的删除 产品的删除
list.html
    
产品的查询 产品的查询
update.html
    
产品的修改 产品的修改

整体使用内存做授权验证, 后续整理基于JDBC 做权限授权,整体一套下来的话,基本上对于springsecurity有一个基本的了解,入坑第一步建议以基础入手,大部分的配置建议查看官方源码 ,对于登出以及记住密码,细节在 源码HttpSecurity类中有详细说明,这里不做过多的说明。只提供基础的Demo示例

有什么问题欢迎在我的博客留言:
地址:

转载地址:http://xkvo.baihongyu.com/

你可能感兴趣的文章
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>
MySQL Connector/Net 句柄泄露
查看>>
multiprocessor(中)
查看>>
mysql CPU使用率过高的一次处理经历
查看>>
Multisim中555定时器使用技巧
查看>>
MySQL CRUD 数据表基础操作实战
查看>>
multisim变压器反馈式_穿过隔离栅供电:认识隔离式直流/ 直流偏置电源
查看>>
mysql csv import meets charset
查看>>
multivariate_normal TypeError: ufunc ‘add‘ output (typecode ‘O‘) could not be coerced to provided……
查看>>
MySQL DBA 数据库优化策略
查看>>