springBoot笔记(六)---springSecurity进行安全及权限控制

Spring Security

简介:
  • Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。 它是用于保护基于Spring的应用程序的实际标准。

  • Spring Security是一个框架,致力于为Java应用程序提供身份验证和授权。 与所有Spring项目一样,Spring Security的真正强大 之处在于可以轻松扩展以满足自定义要求。

  • springboot默认的底层安全模块,使用时仅需要引入spring-boot-starter-security依赖

重要类:

  • WebSecurityConfigurerAdapter: 自定义的Security策略

  • AuthenticationManageBuilder: 自定义认证策略

  • @EnableWebSecurity : 开启WebSecurity模式

特征:

- 对身份验证和授权的全面且可扩展的支持
- 防止攻击,例如会话固定,点击劫持,跨站点请求伪造等
- Servlet API集成
- 与Spring Web MVC的可选集成

1.项目的路径重写

package com.example.securingweb;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/home").setViewName("home");
		registry.addViewController("/").setViewName("home");
		registry.addViewController("/hello").setViewName("hello");
		registry.addViewController("/login").setViewName("login");
	}
}

2.pom.xml中导入Security依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-test</artifactId>
  <scope>test</scope>
</dependency>

3.config进行security配置(security采用的链式编程)

package com.example.securingweb;

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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

 
// 表示security模式开启,必须添加
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	@Override
    // HttpSecurity权限设置,允许哪些人访问目标页面
    // formLogin()默认跳转的页面
	protected void configure(HttpSecurity http) throws Exception {
		http
			.authorizeRequests()
				.antMatchers("/", "/home").permitAll()       // permitAll()允许所有人访问
				.anyRequest().authenticated()
				.and()
			.formLogin()                    // 没有权限直接跳转到登录页面
				.loginPage("/tologin")   // 这里设置这几个后出现页面跳转不出来错误,这里是定制登录页面
				.permitAll()           // 所以登录时,tologin是去登录页面,提交登录时一种是同样的路径, 
				.and()          //另一种就是后面加.loginProcessionUrl("/login"),同时表单提交name:要和源码一致
			.logout()                      // 注销
				.permitAll();
	}
    
    // 进行权限设置,通常是从数据库中读取数据,同时也支持从内存中读取数据
    // 在进行password设置时,需要进行编码,security提供多种编码方式
    // withDefaultPasswordEncoder()进行编码设置
    // 下面的方式是ongoing数据库中读取信息
	 
	  // 从数据库中读取
    @Autowired
    DataSource dataSource;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
       // 从数据库中读取
        auth.jdbcAuthentication()
                .dataSource(dataSource)
                .withDefaultSchema()
                .withUser("").password("").roles("");
    }
    
    // 内存进行读取数据
	@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth.inMemoryAuthentication().PasswordEncoder(new BCryptPasswordEncoder())
            .withUser("admin").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2")
            .and()
            .withUser("admin").password(new BCryptPasswordEncoder().encode("1234")).roles("vip2","vip3")
    }
}

4.注销,可以在前端页面跳转到loginout,注销可以进行session和cookie的清除,可以指定跳转页面;

5.通过使用thymeleaf和springboot的组合依赖,控制前端进行页面是否显示控制;

标签:sec

实现动态菜单:

例如:sec:authorize=“hasRole(‘vip1’)” // 该页面只对VIP1用户显示

​ sec:authorize=“isAuthenticated()” // 判断是否登录了,登录了就显示用户名div,没有登录就显示登录div

注意:注销失败原因:http.csrf().disable(); //防止网站攻击开启了,关闭就可以了

6.记住我功能实现(前端页面):

http.rememberme().rememberMeparamter("接受前端记住我name属性");      // 开启记住我功能,通过传递cookie值的方式,默认保存两周
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值