【SpringSecurity】一一一一Spring boot 整合 security 分布式安全框架(一)

Spring boot-security 分布式安全框架 (一)

1. 概述

基本上,在所有的开发的系统中,都必须做认证(authentication)和授权(authorization),以保证系统的安全性。

2. 快速入门

Spring Security ,实现访问 API 接口时,需要首先进行登录,才能进行访问。

2.1 依赖引入

pom.xml 文件中,引入相关依赖。

<dependencies>
        <!-- 实现对 Spring MVC 的自动化配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- 实现对 Spring Security 的自动化配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    </dependencies>

2.2 Application.java

@SpringBootApplication
public class ZtreeApplication {

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

}

2.3 配置文件

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启对 Spring Security 注解的方法,进行权限验证。
public class WebSecurityConfig extends WebSecurityConfigurerAdapter  {

    /**
     * 重写 #configure(AuthenticationManagerBuilder auth) 方法,实现 AuthenticationManager 认证管理器。
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.
                // <X> 使用内存中的 InMemoryUserDetailsManager
                        inMemoryAuthentication()
                // <Y> 不使用 PasswordEncoder 密码编码器
                .passwordEncoder(NoOpPasswordEncoder.getInstance())
                // <Z> 配置 admin 用户
                .withUser("admin").password("admin").roles("ADMIN")
                // <Z> 配置 normal 用户
                .and().withUser("normal").password("normal").roles("NORMAL");
    }

    /**
     * 重写 #configure(HttpSecurity http) 方法,主要配置 URL 的权限控制。
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 配置请求地址的权限
                .authorizeRequests()
                .antMatchers("/user/home").permitAll() // 所有用户可以访问
                .antMatchers("/user/admin").hasRole("ADMIN") //需要有ADMIN角色的用户可以访问
                .antMatchers("/user/normal").access("hasRole('ROLE_NORMAL')") //需要 NORMAL 角色
                // 任何请求,访问的用户都需要经过认证
                .anyRequest().authenticated()
                .and()
                // <Y> 设置 Form 表单登录
                .formLogin()
                //.loginPage("/login") // 登录 URL 地址
                .permitAll() // 所有用户可访问
                .and()
                // 配置退出相关
                .logout()
//                    .logoutUrl("/logout") // 退出 URL 地址
                .permitAll(); // 所有用户可访问
    }
}

2.4 测试

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author XiaoCoder
 * @since 2021-04-30
 */
@RestController
@AllArgsConstructor
@RequestMapping("/user")
public class UserController { 
    
@PreAuthorize("hasAnyRole('ROLE_NORMAL')")
    @ApiOperation(value = "springSecurity+Oauth2,测试user登录",
            notes = "springSecurity+Oauth2,测试user登录")
    @GetMapping("/normal")
    public String normal() {
        return "hello 我是normal用户 !";
    }

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @ApiOperation(value = "springSecurity+Oauth2,测试admin登录",
            notes = "springSecurity+Oauth2,测试admin登录")
    @GetMapping("/admin")
    public String admin() {
        return "hello 我是管理员!! !";
    }

    @PermitAll
    @ApiOperation(value = "springSecurity+Oauth2,测试admin登录",
            notes = "springSecurity+Oauth2,测试admin登录")
    @GetMapping("/home")
    public String home() {
        return "hello 我是首页!! !";
    }
    
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值