Spring Security for Rest @PreAuthorize 500错误

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

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

@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对象。

java spring rest spring-security http-status-code-500
2个回答
0
投票

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

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

否则,如果您将管理身份验证设置为spring,则可以使用异常处理程序:

@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);
    }
}


0
投票

尝试更改这样的配置。

.authorizeRequests()
.antMatchers(permitAllEndpointList.toArray(new String[permitAllEndpointList.size()]))
.permitAll()
.and()
.authorizeRequests()
.antMatchers(API_ROOT_URL).authenticated()

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

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