春季安全保护注册端点

问题描述 投票:0回答:1

我正在使用spring security来保护我的端点。

目前,在我的配置中,我有这样的内容

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        // securedEnabled = true,
        // jsr250Enabled = true,
        prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests().antMatchers("/api/v1/register/**", "/api/v1/auth/**").permitAll()
                .antMatchers("/api/v1/mycontroller/**").permitAll()
                .anyRequest().authenticated();

//        http.cors().and().csrf().disable();

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }

}

我有一个注册控制器,它是

@CrossOrigin
@RestController
@RequestMapping("/api/v1/register")
@Api(tags = {"SignupController"})
public class SignupController {

@CrossOrigin
    @RequestMapping(value = "/signup", method = RequestMethod.POST)
    @ApiOperation(value = "Sign up endpoint", notes = "You have to provide a valid sign up request.")
    public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {

     .....
  }
}

我也有一个资源控制器,提供资源

@RestController
@RequestMapping(value = "/api/v1/mycontroller")
@Api(tags = {"myController"})
@PreAuthorize("isAuthenticated()")
public class myController {
 ....
}

如你所见,我添加了一个PreAuthorize注解来保护我的端点。我如何保护注册控制器端点,因为我不希望任何人能够注册。有没有办法在spring security中专门处理这种情况?

spring-boot spring-security
1个回答
0
投票

为了保护一个url,需要 EnableGlobalMethodSecurity 在你 Configuration 类。

@EnableGlobalMethodSecurity(
    prePostEnabled = true,
    securedEnabled = true,
    jsr250Enabled = true)
  • 该类: prePostEnabled 属性将允许预置注释。
  • securedEnabled 财产 @Secured 注释。
  • jsr250Enabled 财产 @RoleAllowed 注解。

现在用任何特定的注解来装饰你的方法。

@PreAuthorize("has_role('ROLE_ADMIN')")
@GetMapping("/signup")
// ...

或者使用 @Secured:

@Secured("ROLE_ADMIN")
@GetMapping("/signup")
// ...

如果您希望通过以下方式进行配置 HttpSecurity:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) throws Exception {
        http
            // ...
            .antMatchers(HttpMethod.GET, "/signup").hasRole("ADMIN")
            // ...
    }
}

阻止所有类型的请求。

.antMatchers("/signup").hasRole('ADMIN')

如果你不想让任何人访问该网址,甚至是管理员,那么你可以将角色名改为一个任意值。例如:如果你不想让任何人访问该网址,甚至是管理员,那么你可以将角色名改为任意值。SOME_UNKNOWN_ROLE 或使用 .denyAll() 而不是 .hasRole(...)

© www.soinside.com 2019 - 2024. All rights reserved.