/ / Не може да се промени пролетният достъп до защита отказан стандартен отговор - java, spring, spring-security, oauth

Невъзможно е да се промени пролетният достъп до защита, отказан стандартен отговор - java, пролет, пролет-сигурност, oauth

Имам приложение Spring Boot, в което използвах OAuth с Spring Security. Когато заявя токен за упълномощаване към Spring Security, той връща следния отговор:

{"error":"invalid_grant","error_description":"Bad credentials"}

Трябва да променя този отговор на персонализиран json, но нито един от подходите, които съм изпробвал, не работи.

Опитах се да използвам обичай AccessDeniedHandler като следните:

public class CustomOAuth2AccessDeniedHandler implements AccessDeniedHandler{

public CustomOAuth2AccessDeniedHandler() {
}

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException)
throws IOException, ServletException {
response.setContentType(MediaType.TEXT_PLAIN_VALUE);
response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
response.getOutputStream().println("Exception with message : " + authException.getMessage());
//doHandle(request, response, authException);

}

но не се извиква. Използвайки web.xml пренасочването на отговор не е опция за мен, тъй като използвам Spring Boot и не искам да променя формата на отговора глобално.

мой spring-security.xml е конфигуриран по следния начин:

<!-- Definition of the Authentication Service -->
<http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="clientAuthenticationManager"
xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY"/>
<anonymous enabled="false"/>
<http-basic entry-point-ref="clientAuthenticationEntryPoint"/>
<!-- include this only if you need to authenticate clients via request parameters -->
<custom-filter ref="clientCredentialsTokenEndpointFilter" after="BASIC_AUTH_FILTER"/>
<access-denied-handler ref="oauthAccessDeniedHandler"/>
</http>

<bean id="oauthAuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="dstest"/>
</bean>

<bean id="clientAuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="dstest/client"/>
<property name="typeName" value="Basic"/>
</bean>

<!-- <bean id="oauthAccessDeniedHandler" -->
<!--       class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler"/> -->
<bean id="oauthAccessDeniedHandler"
class="in.robotrack.brad.config.CustomOAuth2AccessDeniedHandler"/>


<bean id="clientCredentialsTokenEndpointFilter"
class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
<property name="authenticationManager" ref="clientAuthenticationManager"/>
</bean>

<bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"
xmlns="http://www.springframework.org/schema/beans">
<constructor-arg>
<list>
<bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter"/>
<bean class="org.springframework.security.access.vote.RoleVoter"/>
<bean class="org.springframework.security.access.vote.AuthenticatedVoter"/>
</list>
</constructor-arg>
</bean>

<!-- Authentication in config file -->
<authentication-manager id="clientAuthenticationManager" xmlns="http://www.springframework.org/schema/security">
<authentication-provider user-service-ref="clientDetailsUserService"/>
</authentication-manager>

<authentication-manager alias="authenticationManager" xmlns="http://www.springframework.org/schema/security">
<authentication-provider user-service-ref="customUserDetailsService">
</authentication-provider>
</authentication-manager>

<bean id="clientDetailsUserService"
class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
<constructor-arg ref="clientDetails"/>
</bean>

<!-- Token Store  -->
<bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.InMemoryTokenStore"/>

<bean id="tokenServices" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
<property name="tokenStore" ref="tokenStore"/>
<property name="supportRefreshToken" value="true"/>
<property name="clientDetailsService" ref="clientDetails"/>
<!-- VIV -->
<property name="accessTokenValiditySeconds" value="10"/>
</bean>

<bean id="userApprovalHandler"
class="org.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandler">
<property name="tokenServices" ref="tokenServices"/>
</bean>

Отговори:

0 за отговор № 1

опитайте долу:

HttpSecurity http = ...
http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);

ако не искате да дефинирате вашия персонализиран AccessdeniedHandler, тогава дори вие можете да опитате това

HttpSecurity http = ...
http.exceptionHandling().accessDeniedPage("/403");

И тогава във вашия контролер просто дефинирайте един метод, който може да обработва / 403 картографиране на заявки и там просто връщате страницата си за грешка 403, както правите при нормалните методи във всеки клас на контролер.