SpringSecurity简单入门(基于SpringBoot)

2022-12-21 09:31:17 浏览数 (1)

依赖

代码语言:javascript复制
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies><!-- 以下是>spring boot依赖-->
        <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>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
    </dependencies>

启动类

代码语言:javascript复制
package com.lianxi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

配置文件

只配置了一个端口

代码语言:javascript复制
server:
  port: 8080

controller

代码语言:javascript复制
package com.lianxi.security.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TextController {

    /**
     * 认证后通过
     * @return
     */
    @GetMapping("/text/autor")
    public String text1(){
        return "认证了";

    }

    /**
     * 必须有au权限访问
     * @return
     */
    @GetMapping("/text/au")
    public String text2(){
        return "au权限访问";

    }

    /**
     *必须有auto权限或者有ROOT_CJZ角色 才可访问
     * @return
     */
    @GetMapping("/text/auto")
    public String text3(){
        return "auto认证了";
    }
}

config

在 config 包中定义 配置类 在配置类上加上 @EnableWebSecurity注解来开启安全配置 继承 WebSecurityConfigurerAdapter 重写 configure(HttpSecurity http)方法 为了快速入门使用的是内存中创建了用户和角色

代码语言:javascript复制
package com.lianxi.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 配置密码编辑器
     * 在SpringSecurity框架中密码要求进行加密
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置用户信息(用户名密码,角色权限)
     * 这里使用内存中定义
     * 在设置角色时,框架自动加上 ROOT_
     */
    @Bean
    public UserDetailsService detailsService(){
    //创建内存构建角色和用户信息
        InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
        userDetailsManager.createUser(User.withUsername("au").password(passwordEncoder().encode("123321")).authorities("au").build());
        userDetailsManager.createUser(User.withUsername("auto").password(passwordEncoder().encode("123321")).authorities("auto").roles("GUO").build());
        return userDetailsManager;
    }
    /**
     * 配置安全规则
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable() //关闭csrf
                .formLogin() //允许表单
                .and()
                .authorizeRequests()
                .antMatchers("/text/au").hasAuthority("au") //设置请求地址需要什么用户才能访问
                //设置需要什么用户或者角色才能访问 
                .antMatchers("/text/auto").access("hasRole('GUO') or hasAuthority('auto')")
                .anyRequest().authenticated();  //其他请求认证以后才能访问
    }
}

这只是简单的SpringSecurity框架入门

0 人点赞