Spring Spring for Rest @PreAuthorize 500错误

时间:2016-05-23 14:00:03

标签: java spring rest spring-security http-status-code-500

我想要休息的基本安全性,这是我的配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private PacijentUserDetailsService pacijent;
@Autowired
private FizioterapeutUserDetailsService fizioterapeut;
@Autowired
private FizijatarUserDetailsService fizijatar;

@Override
protected void configure(AuthenticationManagerBuilder
        auth) throws Exception {
        auth.userDetailsService(pacijent)
        .passwordEncoder(new
        BCryptPasswordEncoder());
        auth.userDetailsService(fizioterapeut).passwordEncoder(new
        BCryptPasswordEncoder());
        auth.userDetailsService(fizijatar).passwordEncoder(new
        BCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception
{
    http
    .sessionManagement()
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
    .authorizeRequests()
    .antMatchers("/pacijent/", "/fizijatar/","/fizioterapeut/").permitAll()
    .antMatchers("/pacijent/**","/fizijatar/**","/fizioterapeut/**").authenticated()
    .and()
    .httpBasic()
    .realmName("Ordinacija")
    .and()
    .csrf()
    .disable();

  }
  @Bean
   @Override
  public AuthenticationManager authenticationManagerBean() throws Exception          {
    return super.authenticationManagerBean();
}

}

我有3个userdetailservice工具,这是一个例子:

  @Component
 public class PacijentUserDetailsService implements UserDetailsService {

@Autowired
private PacijentService pacijentService;

@Override
public UserDetails loadUserByUsername(String jmbg) throws UsernameNotFoundException {
Pacijent pacijent = pacijentService.vratiPacijenta(jmbg);
    if (pacijent == null) {
        throw new UsernameNotFoundException(String.format("Pacijent nije pronadjen", jmbg));

    }

    List<GrantedAuthority> authorities = new ArrayList<>();
    if (pacijentService.postojiPacijentPoJmbgu(jmbg)) {
        authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
    }

    UserDetails userDetails = new org.springframework.security.core.userdetails.User(pacijent.getJmbg(),
            pacijent.getSifra(), authorities);
    return userDetails;
  }
}

我的web xml文件:

           <context-param>
 <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
  </context-param>

    org.springframework.web.context.ContextLoaderListener

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet- class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>

当我启动我的应用程序并转到具有@PreAuthorize方法的休息方法时,我有错误500: 请求处理失败;嵌套异常是org.springframework.security.authentication.AuthenticationCredentialsNotFoundException:在SecurityContex中找不到Authentication对象。

2 个答案:

答案 0 :(得分:0)

我写答案来帮助别人。 如果您有一个像AfterPerRequestFilter这样的过滤器在其中检查身份验证,那么当您检查身份验证失败时,可以设置以下内容:

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

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

否则,如果让管理身份验证生效,则可以使用异常处理程序:

@ControllerAdvice
@RestController
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({AccessDeniedException.class})
    public final
            ResponseEntity<Object> handleUserNotFoundException(EntityNotFoundException ex, WebRequest request){
        return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED);
    }
}

答案 1 :(得分:0)

尝试像这样更改您的配置。

SELECT CTE.ProductType, CTE.PRODUCT_ID, DECODE(CT.PRODUCT_ID,NULL,0,1) AS HasCustomer
  FROM (
    SELECT 
      LISTAGG(pt.product_type, ', ') WITHIN GROUP (ORDER BY pt.product_type) as ProductType, 
      pt.PRODUCT_ID
      FROM product_type pt          
      group by pt.PRODUCT_ID) CTE
 JOIN CUSTOMER CT ON CT.PRODUCT_ID = CTE.PRODUCT_ID;

我希望这能解决您的问题。