Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
安全RESTAPI Spring MVC_Rest_Spring Mvc_Spring Security - Fatal编程技术网

安全RESTAPI Spring MVC

安全RESTAPI Spring MVC,rest,spring-mvc,spring-security,Rest,Spring Mvc,Spring Security,一直在尝试实现SpringSecuritytoRESTAPI,但即使没有用户名和密码,它们也可以工作 @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { private static String REALM="MY_TEST_REALM"; @Autowired RestAuthenticationEntryPoint restAuthent

一直在尝试实现SpringSecuritytoRESTAPI,但即使没有用户名和密码,它们也可以工作

@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, "/*");
}
}
Rest授权入口点

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 security的登录表单,但rest api甚至不要求提供凭据,因此,如果使用的api没有凭据,如何发送未经授权的响应?

通过每个请求头传递用户ID或身份验证。在服务器端添加拦截器来处理这个问题,我正在使用注释,所以我搜索了拦截器,得到了这个“@PreAuthorize(“hasRole('ROLE_ADMIN')”)”。。正在工作thanx,sumesh:DSearch HandlerInterceptor