Secure Rest API Spring MVC

时间:2018-06-20 11:34:18

标签: rest spring-mvc spring-security

试图对REST api实施spring security,但是即使没有用户名和密码也可以使用

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

private static String REALM="MY_TEST_REALM";

@Autowired
RestAuthenticationEntryPoint restAuthenticationEntryPoint;

@Autowired
public void ConfigureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER", "ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
     http.csrf().disable()
    .authorizeRequests()
    .antMatchers("/user").hasRole("ADMIN")
    .and().httpBasic().realmName(REALM).authenticationEntryPoint(gEntryPoint())
    .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}


@Bean
public RestAuthenticationEntryPoint gEntryPoint() {
    return new RestAuthenticationEntryPoint();
}


@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers(HttpMethod.OPTIONS, "/*");
}
}

其他身份验证入口点

public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{


@Override
   public void commence(
     HttpServletRequest request,
     HttpServletResponse response, 
     AuthenticationException authException) throws IOException {

      response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" );
   }
}

其他控制器

@RestController
@RequestMapping(value = "/dray")
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class dray {

@RequestMapping(value = "/user", method = RequestMethod.GET)
@ResponseBody
public Auser getUser() {
    return new Auser("john", "carter");
}   
}

对jsp页面的请求可以正常工作,如果用户未通过身份验证,他将被重定向到spring安全性的登录表单,但是即使没有要求提供凭据也可以进行api工作,因此如果使用的api没有凭据?

0 个答案:

没有答案