springboot整合springSecurity

springSecurtiy作为重量级的安全框架。与spring无缝衔接。
一、jar包依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 <!-- spring sercurity安全框架 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

继承类WebSercuityConfigurerAdapter,对serurity进行配置,可实现其中的三个配置方法。目前只使用一个作为入门操作

    @Override
    protected void configure(HttpSecurity http) throws Exception {
         //禁用crsf
        http.csrf().disable();
        http
                // 开始请求权限配置
                .authorizeRequests()
                // 我们指定任何用户都可以访问多个URL的模式。
                // 任何用户都可以访问以"/resources/","/signup", 或者 "/about"开头的URL。
                .antMatchers("/css/**","/img/**","/js/**","/plugins/**","/elementuidemo/**").permitAll()
                // 请求匹配 /admin/** 只拥有 ROLE_ADMIN 角色的用户可以访问
                 .antMatchers("/pages/**").hasRole("ADMIN")
                // 请求匹配 /user/** 拥有 ROLE_ADMIN 和 ROLE_USER 的角色用户都可以访问
                //.antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
                // 任何以"/xxx/" 开头的URL需要同时具有 "ROLE_ADMIN" 和 "ROLE_DBA"权限的用户才可以访问。
                // 和上面一样我们的 hasRole 方法也没有使用 "ROLE_" 前缀。
                // .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
                // 其余所有的请求都需要认证后才可以访问
                .anyRequest().authenticated()
                .and()
                .formLogin()
                // 登陆界面;默认登陆失败的界面;表单提交地址
                .loginPage("/pages/login.html")
                //登陆成功的处理类,需要继承SavedRequestAwareAuthenticationSuccessHandler类
                .successHandler(securityAuthenctiationSuccessHandler)
                //登录处理接口,随便写一个地址,这个地址可以不存在,但是需要与表单提交的地址一样
                .loginProcessingUrl("/login.do")
                //.successForwardUrl("/loginSuccess")
                //登陆失败的url
                //.failureUrl("")
                //默认登陆成功后的界面 不起作用 ;
             .defaultSuccessUrl("/pages/main.html",true).permitAll();
                //表单提交地址
                //.failureUrl("/login?error=true")


        // 设置可以iframe访问
        http.headers().frameOptions().sameOrigin();
    }

需要在启动类获取配置类上打上@EnableWebSecurity注解。使其生效

以及用于用户校验操作的UserDetailsService接口,实现方法 public UserDetails loadUserByUsername(String username)

springSecurity默认采用BCryptPasswordEncoder作为密码的加密操作;

@Component
public class SecurityUserDetails implements UserDetailsService {

    @Autowired
    PasswordEncoder passwordEncoder;  

    /* 对用户进行权限的查询以及密码的查询 */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetails userDetails =null;
        /* 查询用户权限, */

        Collection<GrantedAuthority> authoritiesList = getAuthorities();
        userDetails = new User(username,passwordEncoder.encode("123456"),authoritiesList);
        return userDetails;
    }

    /* Query database setting permission */
    private Collection<GrantedAuthority> getAuthorities(){
        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
        authList.add(new SimpleGrantedAuthority("ROLE_USER"));
        authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        return authList;
    }

  /* 指定加密格式 */
    @Bean
    public PasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
Spring Boot整合Spring Security主要是为了提供安全控制功能,帮助开发者快速地在Spring Boot应用中添加身份验证、授权和会话管理等安全性措施。以下是基本步骤: 1. 添加依赖:首先,在Maven或Gradle项目中添加Spring Security的相关依赖到pom.xml或build.gradle文件中。 ```xml <!-- Maven --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- Gradle --> implementation 'org.springframework.boot:spring-boot-starter-security' ``` 2. 配置WebSecurityConfigurerAdapter:在`src/main/resources/application.properties`或application.yml中配置一些基础属性,如启用HTTPS、密码加密策略等。然后创建一个实现了`WebSecurityConfigurerAdapter`的类,进行具体的配置,如设置登录页面、认证器、过滤器等。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/css/**", "/js/**", "/images/**").permitAll() // 允许静态资源访问 .anyRequest().authenticated() // 所有其他请求需要认证 .and() .formLogin() // 设置基于表单的身份验证 .loginPage("/login") // 登录页URL .defaultSuccessUrl("/") // 登录成功后的默认跳转URL .usernameParameter("username") .passwordParameter("password") .and() .logout() // 注销功能 .logoutUrl("/logout") .logoutSuccessUrl("/") .deleteCookies("JSESSIONID"); } // ... 其他配置如自定义用户DetailsService、密码编码器等 } ``` 3. 用户服务(UserDetailsService):如果需要从数据库或其他数据源获取用户信息,需要实现`UserDetailsService`接口并提供用户查询逻辑。 4. 运行应用:启动Spring Boot应用后,Spring Security将自动处理HTTP请求的安全检查,例如身份验证和授权。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不断尝试

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值