zoukankan      html  css  js  c++  java
  • spring boot之security

    上一节的时候,我们打开了springboot的端点,有一些数据是非常敏感的,比如/shutdown。

    这一节,我们要给一些敏感信息加上权限控制。

    spring boot本身的security模块就很好用,需要配置的东西很少,但是对于初学者而言,会有很多坑。

    一、security配置

    1.引入依赖

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

    引入这个依赖之后,你再访问之前的接口,都访问不了了,需要填写用户名和密码,由于我们还没有做任何配置,这里用户名默认是user,密码在springboot启动的日志里(当然也可以自定义在application配置文件中)

    这种默认的方式,无论如何是不太好用的,因此我们需要自定义自己的权限配置。

    2.自定义security配置类

    自定义的配置类没有几行代码,只有两个方法,先说第二个,我们初始化了一个用户user在内存中,密码是admin,角色是ADMIN,当然这些东西都是可以自己定义的。没有写在配置文件中,因为我觉得那样还是不太安全。

    我们对/actuator开始的url访问要求有ADMIN权限,其他的随意访问。

    经过这些配置,再访问接口的时候发现,/actuator/**都需要输账号密码了,其他的还是不需要,正是我们想要的结果。

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()
                    .antMatchers("/actuator/**").access("hasRole('ADMIN')")
                    .antMatchers("/**").permitAll();
            super.configure(http);
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth
                    .inMemoryAuthentication()
                    .withUser("user").password("admin")
                    .roles("ADMIN");
        }
    }

    3.设置端点接口的前缀

    spring boot 1.5.4的actuator端口都是基于根目录的,这样我们发现再进行权限控制的时候,写的很麻烦,在配置文件中可以给它加一个前缀

    #开启actuator端点,增加前缀
    management.security.enabled=false
    management.context-path=/actuator
  • 相关阅读:
    2月11日
    亚特兰蒂斯
    080215 晴
    2月9日
    2月6日
    2月10日
    080208 晴(0,50)
    关于春晚
    (15,50)
    恍然大悟
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/9229092.html
Copyright © 2011-2022 走看看