1

残りの基本的なセキュリティが必要です。これは私の設定です:

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

}

userdetailservice の 3 つの実装があります。これは一例です。

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

そして私のウェブ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 メソッドを持つ rest メソッドに移動すると、エラー 500: 要求処理に失敗しました。ネストされた例外は org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContex です。

4

2 に答える 2

0

私は他の人を助けるために答えを書きます。認証をチェックする OncePerRequestFilter のようなフィルターがある場合、認証をチェックして失敗した場合は、次のように設定できます。

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

于 2019-04-27T12:09:34.963 に答える