spring security整合Spring Boot以及用法

   spring security是个什么呢?它可以用来做什么呢?接下来我来和小伙伴分享一下。
   spring security有两大重要的功能,1、授权(你能干什么),2、认证(你是谁)
下面介绍下入门项目:首先在pom依赖中导入security依赖:

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

然后创建security的config配置文件,继承WebSecurityConfigurerAdapter方法,重写部分代码,配置文件如下图所示:

package com.kuang.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
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.WebSecurityConfiguration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.sql.DataSource;

/**
 * @author ygl
 * @description
 * @date 2020/11/5 11:40
 */

//AOP 横切
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //是链式编程
        //请求授权规则
        http.authorizeRequests()
                //首页所有人可以访问
                .antMatchers("/").permitAll()
                //访问level1下的所有页面只有拥有vip1的才可以访问
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //若没有权限则会到登录页面,需要开启登录的页面
        http.formLogin()
                //定制登录页
                .loginPage("/toLogin");
        //防止网站工具
        http.csrf().disable();//关闭csrf攻击功能   登出失败的原因

        //注销: 开启了注销功能
        http.logout()
         //跳转到首页
        .logoutSuccessUrl("/");

        //开启记住我功能
        http.rememberMe();

    }

    //认证
    //密码编码:There is no PasswordEncoder mapped for the id "null"
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //从数据库也可以,从内存也可以
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
            //数据正常应该从数据库读取
                //用户名   密码   权限
            .withUser("ygl").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
            .and()
            .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
            .and()
            .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");//这是从内存认证
        // auth.jdbcAuthentication()  这是从jdbc认证

        /*
        User.UserBuilder users = User.withDefaultPasswordEncoder();
        auth.jdbcAuthentication()
                .dataSource(dataSource)
                .withDefaultSchema()
                .withUser(users.username("user").password("password").roles("vip1"))
                .withUser(users.username("admin").password("password").roles("vip1","vip2","vip3"));

         */

    }
}

上图代码中写的有部分功能作用,主要重写configure方法,进行来完成授权和认证
注意;@EnableWebSecurity注解和@Configuration一起使用,这样就构成security配置。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要在 Spring Boot使用 Spring Security,需要进行以下步骤: 1. 添加 Spring Security 依赖。 在 `pom.xml` 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 配置 Spring Security。 在 Spring Boot 中,可以通过 `WebSecurityConfigurerAdapter` 来配置 Spring Security。创建一个类继承 `WebSecurityConfigurerAdapter`,并重写其中的方法来配置 Spring Security。 例如: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .anyRequest().authenticated() .and() .formLogin() .and() .httpBasic(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin") .password(passwordEncoder().encode("admin123")) .roles("ADMIN") .and() .withUser("user") .password(passwordEncoder().encode("user123")) .roles("USER"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 上述代码中,`configure(HttpSecurity http)` 方法用于配置 URL 的访问权限,`configure(AuthenticationManagerBuilder auth)` 方法用于配置用户的认证信息。在上述示例中,配置了两个角色 ADMIN 和 USER,分别具有不同的访问权限。 3. 使用 Spring Security。 在 Spring Security 配置完成后,可以在 Spring Boot 项目的其他地方使用 Spring Security。例如,在控制器中使用注解 `@PreAuthorize` 来控制方法的访问权限。 例如: ```java @RestController @RequestMapping("/admin") public class AdminController { @GetMapping("/hello") @PreAuthorize("hasRole('ADMIN')") public String helloAdmin() { return "Hello, Admin!"; } } ``` 上述代码中,`@PreAuthorize("hasRole('ADMIN')")` 注解用于控制该方法只能被具有 ADMIN 角色的用户访问。 以上就是在 Spring Boot整合 Spring Security 的基本步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

岭岭颖颖

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

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

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

打赏作者

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

抵扣说明:

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

余额充值