Spring boot 整合 spring security

来源:互联网 发布:java程序员哪个方向好 编辑:程序博客网 时间:2024/04/29 18:45

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方法

@Overrideprotected void configure(HttpSecurity http) throws Exception {    http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();}@Autowiredpublic 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";}
0 0
原创粉丝点击