我是使用 Spring Boot 構建 Rest APi 的新手。
這是我的controller片段
@PreAuthorize("hasRole('ADMIN')")
@PostMapping(value = "/api/post/posts", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<PostDto> createPost(@Valid @RequestBody PostDto postDto) {
System.out.println("postDto : " postDto.getId());
return new ResponseEntity<>(postService.createPost(postDto), HttpStatus.CREATED);
}
這是我的Security配置
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) //give method level security
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers(HttpMethod.GET, "/api/**").permitAll().anyRequest()
.authenticated().and().httpBasic();
}
@Override
@Bean
protected UserDetailsService userDetailsService() {
// In Memory Users
UserDetails ashish = User.builder().username("oxana").password(getPasswordEncoder().encode("password")).roles("USER").build();
UserDetails admin = User.builder().username("admin").password(getPasswordEncoder().encode("admin")).roles("ADMIN").build();
return new InMemoryUserDetailsManager(ashish, admin);
}
@Bean
PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
我在這里嘗試超越例外
@ExceptionHandler(Exception.class)
public ResponseEntity<Errors> handleGlobalException(Exception exception,
WebRequest webRequest){
Error errorDetails = new Error();
errorDetails.setErrorDesc(exception.getMessage());
errorDetails.setErrorCode(Error.ErrorCodeEnum.BAD_REQUEST);
Errors errors = new Errors();
errors.addErrorsItem(errorDetails);
return new ResponseEntity<>(errors, HttpStatus.INTERNAL_SERVER_ERROR);
}
但它不會出現并給出一大堆錯誤,就像這樣
"timestamp": "2022-02-21T11:39:28.797 00:00",
"status": 403,
"error": "Forbidden",
"trace": "org.springframework.security.access.AccessDeniedException: Access is denied\r\n\tat org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:73)\r\n\tat org.springframework.security.access.intercept.AbstractSecurityInterceptor.attemptAuthorization(AbstractSecurityInterceptor.java:238)\r\n\tat org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:208)\r\n\tat org.springframework.security.access.intercept.aopalliance.
任何人都可以建議我,我如何處理或捕獲這個例外來自定義錯誤,用戶無權做某事?
謝謝
更新
AccessDeniedHandler通過以下方式實作
@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "Dont have sufficient priviliges to perform this action")
public class AccessDeniedError implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exec)
throws IOException, ServletException {
response.sendRedirect("Dont have sufficient priviliges to perform this action");
}
}
現在能夠收到這樣的訊息
{
"timestamp": "2022-02-21T13:29:08.377 00:00",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/api/post/Dont have sufficient priviliges to perform this action"
}
它有點好,但是我怎樣才能("error", "message", "status")從上面的回應中控制這些變數值,以便我可以在其中添加我的自定義值?
uj5u.com熱心網友回復:
由AccessDeniedException處理ExceptionTranslationFilter,然后委托給AccessDeniedHandler寫入到客戶端的相應回應。
如果要自定義此行為,則可以實作 aAccessDeniedHandler然后將您的實作設定為HttpSecurity物件。
MyAccessDeniedHandler.java
public class MyAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
writeCustomResponse(response);
}
private void writeCustomResponse(HttpServletResponse response) {
if (!response.isCommitted()) {
try {
response.setStatus(HttpStatus.FORBIDDEN.value());
response.getWriter().write("{ \"error\": \"User is not authorized.\"}");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
安全配置.java
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// set the customized AccessDeniedHandler to the HttpSecurity object
http.exceptionHandling().accessDeniedHandler(new MyAccessDeniedHandler());
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/431779.html
標籤:弹簧靴 休息 弹簧安全 http-status-code-403
