Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to override BasicAuthenticationEntryPoint in SpringSecurity 4?

I was not able to find on SO the answer (e.g. here. Spring Security: Commence method in class extending BasicAuthenticationEntryPoint no being called)

I just want to override BasicAuthenticationEntryPoint without override other filters and other staff:

<bean id="authenticationEntryPoint" name="authenticationEntryPoint"
      class="com.myclass.BasicAuthenticationEntryPoint">
    <property name="realmName" value="myapp" />
</bean>

Unfortunately, it does not work and I need to configure filter.

<security:http auto-config="true" ..
<sec:custom-filter ref="basicAuthenticationFilter"
                                before="BASIC_AUTH_FILTER" />

</sec:http>

<bean id="basicAuthenticationFilter"
      class="org.springframework.security.web.authentication.www.BasicAuthenticationFilter">
    <constructor-arg name="authenticationManager" ref="authenticationManager" />
    <constructor-arg name="authenticationEntryPoint" ref="authenticationEntryPoint" />
</bean>

Then I have this warning.

WARN 2015-10-29 09:44:05,330 [localhost-startStop-1::DefaultFilterChainValidator] [user:system] Possible error: Filters at position 2 and 3 are both instances of org.springframework.security.web.authentication.www.BasicAuthenticationFilter

Therefore I need to disable auto-config but I do not want to do it:

<security:http auto-config="false" ...

What is the simplest way to override BasicAuthenticationEntryPoint in SpringSecurity 4?

like image 619
Michael Avatar asked Oct 29 '15 08:10

Michael


1 Answers

This works for me with Spring Security 3 (I think it should work for Spring 4), without configuring any filter :

public class CustomBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

    @Override
    public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException {

        response.setStatus( HttpServletResponse.SC_UNAUTHORIZED);
    }
}

Update :

CustomBasicAuthenticationEntryPoint is a Spring Bean. You have to tell Spring about it. Like in your post (I've just changed its name in my answer) :

<bean id="authenticationEntryPoint" name="authenticationEntryPoint"
      class="com.myclass.CustomBasicAuthenticationEntryPoint">
    <property name="realmName" value="myapp" />
</bean>

You need also to tell Spring Security to use this bean as entry point instead of default one :

<security:http entry-point-ref="authenticationEntryPoint" ...

Default configuration redirect the client to a login page when not authenticated. When you override this default behaviour, you only send a 401 code status (unauthenticated) and you don't redirect the client.

like image 124
Bilal BBB Avatar answered Sep 27 '22 02:09

Bilal BBB