SpringSecurity快速入门

SpringSecurity快速入门

1. SpringSecurity简介

SpringSecurity快速入门
image
  • Spring Security是基于Spring的安全框架,提供了包含认证和授权的落地方案;
  • Spring Security底层充分利用了Spring IOC和AOP功能,为企业应用系统提供了声明式安全访问控制解决方案;
  • SpringSecurity可在Web请求级别和方法调用级别处理身份认证和授权,为应用系统提供声明式的安全访问控制功能;

官网地址: https://spring.io/projects/spring-security

2. SpringSecurity工程搭建


【步骤一】 创建工程引入依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.4.RELEASE</version>
    <relativePath/>
</parent>
<dependencies>
    <!-- web起步依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- springBoot整合Security -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
 <!-- lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>

【步骤二】 引导类

@SpringBootApplication
public class MySecurityApplication {
    public static void main(String[] args) {
        SpringApplication.run(MySecurityApplication.class,args);
    }
}

【步骤三】 创建Controller

@RestController
public class TestController {

    @GetMapping("/hello")
    public String hello(){
        return "hello security";
    }


    @GetMapping("/say")
    public String say(){
        return "say security";
    }


    @GetMapping("/register")
    public String register(){
        return "register security";
    }
}

【步骤四】 测试

  • 访问: http://localhost:8080/hello

会自动拦截,并跳转到登录页面(SpringSecurity提供),登录之后才可以访问; 而登录的用户名和密码都是SpringSecurity中内置的默认的用户名密码, 用户名为user, 密码为控制台输出的一段随机数

SpringSecurity快速入门
image

效果:

SpringSecurity快速入门
image

登录成功之后,会自动跳转到之前访问的地址:

SpringSecurity快速入门
image

特别说明:可在配置文件中配置用户名和密码,实际开发中密码不应明文配置

# 我们也可在配置文件中配置用户名和密码,实际开发中密码不应明文配置
spring:
  security:
    user:
      name: user
      password: 6666

3.SpringSecurity自定义认证配置

在上述入门程序中, 用户名、密码都是框架默认帮我们生成的, 方式不够友好,SpringSecurity也为我们提供了通过配置的形式声明合法的账户信息的方式。

声明配置类,定义用户名密码信息

package com.zbbmeta.config;

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.method.configuration.EnableGlobalMethodSecurity;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * @Author: springboot葵花宝典
 * @Github: https://github.com/bangbangzhou
 * @description: TODO
 */

@Configuration
@EnableWebSecurity//开启web安全设置生效
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 构建认证服务,并将对象注入spring IOC容器,用户登录时,会调用该服务进行用户合法信息认证
     * @return
     */

    @Bean
    public UserDetailsService userDetailsService(){
        //从内存获取用户认证信息的服务类(了解)后期用户的信息要从表中获取
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        //构建用户,真实开发中用户信息要从数据库加载构建
        UserDetails u1 = User
                .withUsername("zbbmeta")
                .password("{noop}123456")//{noop}:no operration--》表示登录时对避免不做任何操作,说白了就是明文比对
                .authorities("P5""ROLE_ADMIN")//用户的权限信息,如果角色也作为一种权限资源,则角色名称的前缀必须加ROLE_
                .build();
        UserDetails u2 = User
                .withUsername("zbbmeta2")
                .password("{noop}123456")
                .authorities("P7""ROLE_SELLER","ROLE_ADMIN")//用户的权限信息,如果角色也作为一种权限资源,则角色名称的前缀必须加ROLE_
                .build();
        inMemoryUserDetailsManager.createUser(u1);
        inMemoryUserDetailsManager.createUser(u2);
        return inMemoryUserDetailsManager;
    }

}

说明:

1.在userDetailsService()方法中 返回了一个UserDetailsService对象给spring容器管理,当用户发生登录认证行为时,Spring Security底层会自动调用UserDetailsService类型bean提供的用户信息进行合法比对,如果比对成功则资源放行,否则就认证失败;

2.当前暂时使用InMemoryUserDetailsManager实现类,后续我们也可手动实现UserDetailsService接口,做最大程度的自定义;

测试配置账户信息

  • 重启项目,访问: http://localhost:8080/hello

通过测试,配置的账户和密码信息都是有效的。

4.SpringSecurity自定义授权配置

经过上面配置,我们发现用户认证通过后,资源是都可被访问的。

思考: 如果我们想为不同的用户指定不同的访问资源,该如何实现呢?

接下来,我们通过配置为不同用户访问授权。

4.1  基于编码方式定义授权

package com.zbbmeta.config;

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.method.configuration.EnableGlobalMethodSecurity;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * @Author: springboot葵花宝典
 * @Github: https://github.com/bangbangzhou
 * @description: TODO
 */

@Configuration
@EnableWebSecurity//开启web安全设置生效
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 构建认证服务,并将对象注入spring IOC容器,用户登录时,会调用该服务进行用户合法信息认证
     * @return
     */

    @Bean
    public UserDetailsService userDetailsService(){
        //从内存获取用户认证信息的服务类(了解)后期用户的信息要从表中获取
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        //构建用户,真实开发中用户信息要从数据库加载构建
        UserDetails u1 = User
                .withUsername("zbbmeta")
                .password("{noop}123456")//{noop}:no operration--》表示登录时对避免不做任何操作,说白了就是明文比对
                .authorities("P5""ROLE_ADMIN")//用户的权限信息,如果角色也作为一种权限资源,则角色名称的前缀必须加ROLE_
                .build();
        UserDetails u2 = User
                .withUsername("zbbmeta2")
                .password("{noop}123456")
                .authorities("P7""ROLE_SELLER","ROLE_ADMIN")//用户的权限信息,如果角色也作为一种权限资源,则角色名称的前缀必须加ROLE_
                .build();
        inMemoryUserDetailsManager.createUser(u1);
        inMemoryUserDetailsManager.createUser(u2);
        return inMemoryUserDetailsManager;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()//开启默认form表单登录方式
                .and()
                .logout()//登出用默认的路径登出 /logout
                .permitAll()//允许所有的用户访问登录或者登出的路径
                .and()
                .csrf().disable()//启用CSRF,防止CSRF攻击
                .authorizeRequests()//授权方法,该方法后有若干子方法进行不同的授权规则处理
                //允许所有账户都可访问(不登录即可访问),同时可指定多个路径
                .antMatchers("/register").permitAll()
                .antMatchers("/hello").hasAuthority("P5"//具有P5权限才可以访问
                .antMatchers("/say").hasRole("ADMIN"//具有ROLE_ADMIN 角色才可以访问
                .anyRequest().authenticated(); //除了上边配置的请求资源,其它资源都必须授权才能访问
    }
}

CSRF(Cross-site request forgery)跨站请求伪造,也被称为”One Click Attack”或者 Session Riding,通常缩写为 CSRF 或者 XSRF,是一种对网站的恶意利用。

测试配置账户信息

  • 重启项目,访问: http://localhost:8080/hello

思考: /hello是拥有P5权限的账号,才可以访问,那么使用那么账户才能访问到/hello

使用zbbmeta账号才可以访问的/hello

SpringSecurity快速入门
image

思考: /say是拥有ADMIN角色才可访问,那么使用那么账户才能访问到/say

发现zbbmeta和zbbmeta2账号都可以访问/say

5.2 基于注解方式定义授权

基于注解的方式维护权限更偏向于集中化配置管理,但是这种方式带来的问题是随着权限管理的资源的增多,会导致权限配置变得十分的臃肿,所以SpringSecurity为我们提供了基于注解的配置方式

在配置类开启security的前置注解

//开启SpringSecurity相关注解支持
@EnableGlobalMethodSecurity(prePostEnabled = true)
SpringSecurity快速入门
image

调整资源配置类

修改 configure(HttpSecurity http)方法

       @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()//开启默认form表单登录方式
                .and()
                .logout()//登出用默认的路径登出 /logout
                .permitAll()//允许所有的用户访问登录或者登出的路径
                .and()
                .csrf().disable()//启用CSRF,防止CSRF攻击
                .authorizeRequests()//授权方法,该方法后有若干子方法进行不同的授权规则处理
                //允许所有账户都可访问(不登录即可访问),同时可指定多个路径
//                .antMatchers("/register").permitAll()
//                .antMatchers("/hello").hasAuthority("P5") //具有P5权限才可以访问
//                .antMatchers("/say").hasRole("ADMIN") //具有ROLE_ADMIN 角色才可以访问
                .anyRequest().authenticated(); //除了上边配置的请求资源,其它资源都必须授权才能访问
    }

注意:在 Spring Security 5.8 后要把  antMatchers() 改为 requestMatchers()

注解配置资源权限

在控制方法/URL的权限时, 可以通过配置类中配置的方式进行控制, 也可以使用 注解 @PreAuthorize 来进行控制, 推荐使用注解:

@RestController
public class TestController {

    /**
     *  @PreAuthorize:指在注解作用的方法执行之前,做权限校验
     *  @PostAuthorize:指在注解作用的方法执行之后,做权限校验
     *  @return
     */

    @PreAuthorize("hasAuthority('P5')")
    @GetMapping("/hello")
    public String hello(){
        return "hello security";
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/say")
    public String say(){
        return "say security";
    }

    @PermitAll //等价于antMatchers("/register").permitAll()//任何用户都可访问
    @GetMapping("/register")
    public String register(){
        return "register security";
    }
}

说明:使用@PreAuthorize,需要开启全局方法授权开关,加上注解@EnableGlobalMethodSecurity(prePostEnabled=true)


如果您觉得本文不错,欢迎关注,点赞,收藏支持,您的关注是我坚持的动力!

转载请注明出处,感谢支持!如果本文对您有用,欢迎转发分享!


原文始发于微信公众号(springboot葵花宝典):SpringSecurity快速入门

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/271633.html

(0)
土豆大侠的头像土豆大侠

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!