Spring Security ①

Get Started

引入依赖

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

此时启动应用,浏览器访问localhost:8080即弹出登录框,默认账号为:user,密码在应用日志中会打印出来,类似:Using default security password: ef189b17-1b6a-4b8e-8fce-7ce5042e8a99

添加用户和角色

定义一个用户角色常量类:

public interface Roles {
    String ADMIN = "ADMIN";
    String USER = "USER";
}

通过重载WebSecurityConfigurerAdapter来修改Security的默认配置:

@Component
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    private String encode(String rawPassword) {
        // 调用PasswordEncoder对密码明文进行加密
        return this.passwordEncoder.encode(rawPassword);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .passwordEncoder(this.passwordEncoder)
                .withUser("admin").password(encode("1111")).roles(Roles.ADMIN)
                .and().withUser("user1").password(encode("0000")).roles(Roles.USER)
                .and().withUser("user2").password(encode("0000")).roles(Roles.USER);
    }
}

说明:

  • inMemoryAuthentication()表示把用户信息直接放在内存里,使用其他方式参见 TODO
  • passwordEncoder()指定了一个编码器,这里使用BCryptPasswordEncoder来对密码进行加密,这样存储在服务端的密码就必须以密文存储,因此需要进行encode
  • withUser()用于添加用户和角色

现在重启应用,可以尝试使用配置的用户进行登录。

限制方法访问权限

Spring Security支持在方法级别设置访问权限,首先需要在任意配置类上声明开启权限控制:

@SpringBootApplication
@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true)
public class MyApplication 

然后只需在方法上加@Secured或@RolesAllowed注解即可,如:

@RestController
@RequestMapping("/hello")
public class HelloController {

    @RolesAllowed(Roles.ADMIN)
    @RequestMapping("/admin")
    public String helloAdmin() {
        return "hello admin";
    }

    @RolesAllowed(Roles.USER)
    @RequestMapping("/user")
    public String helloUser() {
        return "hello user";
    }

    @RequestMapping("/anyone")
    public String helloAnyone() {
        return "hello you";
    }
}

@Secured是spring提供的注解,必须设置securedEnabled = true,这里有个小坑,就是使用@Secured就必须加上ROLE_前缀,例如:@Secured("ROLE_" + Roles.ADMIN)。

而@RolesAllowed是Java自带的注解,必须设置jsr250Enabled = true,且角色名不用加前缀,故此使用该注解。

Last Updated 2024/11/24 20:50:53