美文网首页
Spring Security(安全)

Spring Security(安全)

作者: 马铃薯a | 来源:发表于2020-09-18 23:22 被阅读0次

Spring Security(安全)

简介:

Spring Security 是针对Spring 项目的安全框架,也是Spring Boot 底层安全模块默认的技术选型,他可以实现强大的web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理。

记住的类:

  • WebSecurityConfigurerAdapter:自定义 Security 策略。
  • AuthenticationManagerBuilder:自定义认证策略。
  • @EnableWebSecurity:开启WebSecurity模式。

“认证” :Authentication

“授权”:Authorization

  • @EnableXXXX====>开启某个功能

maven导包:

<dependency>
    <groupId>org.spirngframework.boot</groupId>
    <artifctId>spring-boot-starter-security</artifctId>
</dependency>

配置类:(config)

public class SecurityConfig extends webSecurityConfigurerAdapter{
    
    //Http 安全策略  授权规则
    @Override
    protected void configure(HttpSecurit http) throws Exception{
        // super.configure(http);
        // 首页所有人可以访问,功能页只有对应权限的人才能访问
        // authorizeRequests: 认证请求
        // antMatchers: 写入地址
        // permitAll: 所有人都可以访问
        // hasRole: 限定可以访问的角色
        http.authorizeRequests()
            .antMatchers("/地址").permitAll()
            .antMatchers("/地址/**").hasRole("角色");
        
        //没有权限默认跳转登录页,需要开启登录页面
        // .loginPage("/地址"): 指定登录页面
        // .loginProcessingUrl(): 指定登录页之后,默认访问的页面
        http.formoLogin();
        
        // 注销、开启注销功能
        // .deleteCookies: 移除所有的cookies
        // .invalidateHttpSession(true): 清空所有的Session
        // .logouturl("/地址"): 指向一个位置----logout
        http.logout();
        // 关闭 csrf 功能, 登录
        http.csrf().disable();
        
        // 开启记住我功能
        http.formLogin();
    }
    
    // 认证   boot 2.1.x 可以使用
    @Override
    protected void configure(AuthenticationManagerBuilder auth ) throws Exception{
        // 类中认证
        // 这些正常情况下应该从数据库中读取。
        // SpringSecurity:内有多种加密方式
        // passwordEncoder:获取加密方式
        // BCryptPasswordEncoder: 加密方式,是可选的
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
            .withuser("zhang_hao").password(new BCryptPasswordEncoder().encode("mi-ma")).roles("jue_se")
            .and()  // 链接上下
            .withuser("zhang_hao").password("mi_ma").roles("jue_se");
    }
}

Security 与 thymeleaf 整合使用

Security 与 thymeleaf 整合包:

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifctId>thymeleaf-extras-springsecurity</artifctId>
    <version>3.0.4.RELEASE</version>
</dependency>

放入之后的命名空间:

xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity"

相关文章

网友评论

      本文标题:Spring Security(安全)

      本文链接:https://www.haomeiwen.com/subject/jxbsyktx.html