Skip to content

Commit

Permalink
chore: add CustomAccessDeniedHandler
Browse files Browse the repository at this point in the history
  • Loading branch information
bs32g1038 committed Apr 24, 2024
1 parent 682ae26 commit d2f32df
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.jixialunbi.security.AuthEntryPointJwt;
import com.jixialunbi.security.AuthTokenFilter;
import com.jixialunbi.security.CustomAccessDeniedHandler;
import com.jixialunbi.service.UserDetailsServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
Expand Down Expand Up @@ -43,6 +44,9 @@ public class SecurityConfig {
@Autowired
private AuthEntryPointJwt unauthorizedHandler;

@Autowired
private CustomAccessDeniedHandler customAccessDeniedHandler;

@Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter();
Expand Down Expand Up @@ -81,7 +85,10 @@ public SecurityFilterChain filterChain(HttpSecurity httpSecurity, CorsConfigurat
httpSecurity
.cors(cors -> cors.configurationSource(request -> corsConfiguration))
.csrf(e -> e.disable())
.exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
.exceptionHandling(exception -> {
exception.accessDeniedHandler(customAccessDeniedHandler);
exception.authenticationEntryPoint(unauthorizedHandler);
})
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeHttpRequests(auth ->
auth.requestMatchers(AUTH_WHITELIST).permitAll().anyRequest().authenticated()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.jixialunbi.security;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.getWriter().write("Forbidden");
}

}

0 comments on commit d2f32df

Please sign in to comment.