Spring boot 整合 spring security

Spring boot 整合 spring security

  • 在pom.xml中添加spring security的引用
  • 重写WebSecurityConfigurerAdapter类中的configure方法和configureGlobal方法
  • 编写测试方法

在pom.xml中添加spring security的引用

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

重写WebSecurityConfigurerAdapter类中的configure方法和configureGlobal方法

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("administrator").password("123456").roles("USER");
}

注意重写的类上还需要增加三个注解
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)

编写测试方法

@PreAuthorize("isAuthenticated() and hasRole('USER')")
@RequestMapping("/test")
public String test() {
    return "this is a test request";
}

猜你喜欢

转载自blog.csdn.net/shui878412/article/details/53347816