Listing several authentication providers within the same authentication manager - spring-security

I came across this code snippet while debugging an authentication problem :
<security:authentication-manager>
<security:authentication-provider user-service-ref="userDetailsService">
<security:password-encoder hash="sha-256">
<security:salt-source user-property="dateCreated" />
</security:password-encoder>
</security:authentication-provider>
<security:authentication-provider ref="ldapAuthProvider" />
</security:authentication-manager>
What I have noticed while debugging and playing around with the user credentials is that if the first authentication-provider (i.e. userDetailsService) fails to authenticate my user, a remote call is then made to my LDAP server to try to authenticate my user. However if the first authentication-provider manages to authenticate my user successfully, the second authentication-provider is never called.
My question is does the listing of these authentication providers work in a way that if one fails we should jump to the next? I also wonder if the order of them authentication providers listed within the authentication manager plays a role (from a priority standpoint)? An extra reference from Spring Security's official documentation will be more than appreciated.

From the Spring Security reference documentation:
Each AuthenticationProvider has an opportunity to indicate that authentication should be successful, fail, or indicate it cannot make a decision and allow a downstream AuthenticationProvider to decide. If none of the configured AuthenticationProviders can authenticate, then authentication will fail (...)
In practice each AuthenticationProvider knows how to perform a specific type of authentication. For example, one AuthenticationProvider might be able to validate a username/password, while another might be able to authenticate a SAML assertion.
When multiple AuthenticationProviders are defined, they will be queried in the order they are declared.
If the first AuthenticationProvider cannot come to a conclusion it will allow the next AuthenticationProvider to try.

Related

How to implement multiple authentication methods in Spring WebFlux Security?

I'd like to provide two ways to authenticate in my application, one is basic auth (users), and the other is some kind of token based (technical users). I understand that I need a custom ReactiveAuthenticationManager but I can't find clues on the big picture. (Actually, there are a very few insights for MVC, and none for WebFlux.)
1) How do I populate the Authentication's name and credentials in the token based approach? If I configure Spring Security to use httpBasic it's already populated. Some kind of filter needed?
2) How do I distinguish in the authentication manager where the credentials are coming from? Do I have to lookup in the userRepository and (if not found) in the technicalUserRepository too?
3) Do I have to override the SecurityContextRepository? All the tutorials do it but I don't see any reason to do so. What is it exactly? This source states that "SecurityContextRepository is similar to userDetailsService provided in regular spring security that compares the username and password of the user." but I think he means ReactiveUserDetailsService (neither UserDetailsService nor ReactiveUserDetailsService does that by the way, it's just for user lookup).
Since i am decent at Webflux and i have worked a lot with oauth2 i'll try and answer some of your questions.
1) How do I populate the Authentication's name and credentials in the
token based approach? If I configure Spring Security to use httpBasic
it's already populated. Some kind of filter needed?
A token never contains credentials. A token is something you get issued after an authentication has been done. So usually you authenticate against an issuing service. After you have authenticated yourself against that service you will be issued a token.
If its an oauth2 token the token itself is just a random string. It contains no data about the user itself. When this token is sent (using the appropriate header) to a service using spring security. Spring security has a token filter that will basically check that the token is valid, usually by sending the token to the issuer and asking "is this token valid?".
If using a jwt, its different, the jwt must contain some information like issuer, scopes, subject etc. etc. but its basically the same thing, there is a built in filter that will validate the jwt by sending it to the issuer (or using a jwk that the service fetches from the issuer so it can verify the integrity of the jwt without doing an extra request).
2) How do I distinguish in the authentication manager where the credentials are coming from? Do I have to lookup in the userRepository and (if not found) in the technicalUserRepository too?
You don't You usually define multiple SecurityWebFilterChains for different url paths. I have not done this in Webflux Spring Security, but thats how you do it in regular Spring Applications, and i don't see any difference here. Unless you are doing something crazy custom.
3) Do I have to override the SecurityContextRepository? All the tutorials do it but I don't see any reason to do so. What is it exactly? This source states that "SecurityContextRepository is similar to userDetailsService provided in regular spring security that compares the username and password of the user." but I think he means ReactiveUserDetailsService (neither UserDetailsService nor ReactiveUserDetailsService does that by the way, it's just for user lookup).
The answer here is probably no. You see Spring security 4 had very bad support for oauth2 and especially JWT. So people got accustomed to writing their own JWT parsers. When spring Security 5 came, Spring implemented a jwt filter that you can configure and use built in. But there are a lot of outdated Spring Security tutorials out there and foremost there are a lot of developers that don't read the official documentation.
They mostly google tutorials and get the wrong information and then work on that.
But easy explained:
SecurityContextRepository
If you have session based authentication (server establishes a session with a client) it will store the SecurityContext (session) in ThreadLocal during a request. But as soon as the request ends, the session will go lost unless we store it somewhere. The SecurityContextPersistenceFilter will use the SecurityContextRepository to extract the session from ThreadLocal and store it, most common is to store it in the HttpSession.
AuthenticationManager
Override this if you want to do a custom authentication process. Example if you want to validate something, call a custom LDAP, database, etc etc. It\s here you perform you authentication. But remember, most standard logins (like ldap, sql-servers, basic login etc.) already have prebuilt configurable managers implemented, when you select what login type like .httpBasic() you will get a pre-implemented AuthenticationManager.
UserDetailsManager
You override this when you want create a custom UserDetails object (also usually called Principal) In the UserDetailsManager you do you database lookup and fetch the user and then build and return a UserDetails object.
Those two interfaces are the most regular custom implementations, and are used if you need to to basic authentication/session based authentication.
If you wish to do token, you have to think about, who is the token issuer? usually the issuer is separate and all services just get tokens and validate them against the issuer.
I hope this explains some of the questions. I have written this on the bus so some things are probably wrong and not 100% correct etc. etc.

Spring security based application having both form login and SSO

I have searched enough but I haven't got a clear answer and thus posting this question.
I have an existing application which uses spring security for authentication.
Current implementation uses a custom implementation of UsernamePasswordAuthenticationFilter for doing this.
Thus the flow is something like below(in very simple terms):
inputrequest>DelegatingFilterProxy>LoginUrlAuthenticationEntryPoint>CustomUsernamePasswordAuthenticationFilter>AuthenticationManager>CustomAuthenticationProvider
Now I have a requirement to implement SSO (since the user is already asusmed to be authenticated) in some scenarios.
The requirement states that if I have a specific request parameter present then I need to automatically authenticate the request without bothering about user/password.
So it is same set of resources and I do not have to authenticate user/password if the specific SSO related request parameter is present.
e.g
suppose a resource \test\bus is a secure resource.
if I come from normal way then we need to check if the user is authenticated or nor and force user to put valid user/password
if I come from SSO channel then I need to show the \test\bus resource as the user is already authenticated.
currently all the access restrictions are put through <http> element
e.g the snippet of security-config.xml is as follows:
Query: What options do I have in this case. I can think of below options:
Pre-authenticate the user before spring security framework kicks in. This will mean creating an authentication token and putting in spring context before spring security filter is called. This can be done through another filter which is called before spring security filter chain. I have tested it and it works.
Create another custom security filter which set-up the authentication token. I am not clear if this is correct approach as not sure when do we create multiple custom security filter
Create another custom authentication provider e.g SSOCustomAuthenticationProvider. This provider will be called in the existing current flow as we can have multiple authentication providers to a authentication manager. The only issue is that in order to achieve this I have to change the request url to authentication filter's target url so that spring security doesn't check for authentication.
to explain more,
let's say request uri is /test/bus, I will write a filter which will intercept the request and change it to /test/startlogin. This is currently my CustomUsernamePasswordAuthenticationFilter's target url i.e
<property name="filterProcessesUrl" value="/test/startlogin"/>
The flow will be
inputrequest>DelegatingFilterProxy>LoginUrlAuthenticationEntryPoint>CustomUsernamePasswordAuthenticationFilter>AuthenticationManager>SSOCustomAuthenticationProvider
I have tested this and this works. Is this a valid approach or a hack.
Is there any other viable option available with me.
Thanks for reading this.

Securing REST endpoint using spring security

I am trying to provide security to the REST endpoints. I am following instructions from this page. In my case I don't have view hence I haven't created controller to specify the views and haven't added viewResolver in my AppConfig.java
After implementation it correctly shows the access denied error upon calling a secured REST endpoint. But even though I specify username/password in the request header I get the access denied error. I am testing in postman setting username/password in Basic Auth. What am I missing any idea?
The example you have followed is implementing a form-based authentication. In order to change it to http auth (which is more suitable for REST services) you need to look for the following form-login tag in your security.xml:
<form-login
login-page="/login"
default-target-url="/welcome"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
And just change it to an empty http-basic tag:
<http-basic />
If you did not change anything else, then it supposed to work perfectly. You can also test your setup from your browser, by trying to access your page. If you configured everything properly you will get a popup this time, not a form. That will be HTTP-basic authentication welcoming you.
Since likely you are using the Java-based configuration, the equivalent of this change would be to replace:
http.authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.antMatchers("/dba/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
.and().formLogin();
with:
http.authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.antMatchers("/dba/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
.and().httpBasic();

Hooking into pre-authentication with spring-security-core

I'm needing to do some custom things when a user tries to log in depending on their username but these things need to happen before the authentication process. Here's what I've got so far.
Our system allows for multiple email addresses and the client wants the user to be able to authenticate using any 1 of them. To allow for this I created a custom UserDetailsService and had the code lookup the user appropriately.
The other things I need to do require a few flags on the user object that spring-security doesn't really know or care about. But I need to hook into the auth process, check these flags, and return appropriate error messages to the user. To give a more concrete example, I need to know if this is the first time a user has ever logged into the system. So we have a flag on the user to track this. When the user tries to authenticate, I need to read this value and do some stuff, including sending a message back to the user and halting authentication.
I looked into the Event Listener mechanisms in the documentation but what I am not seeing how to do is how to inject my own workflow via the listeners. I need to do a flow like this:
Auth with valid email but first time -> cancel authentication -> display message on login page
I think if I can get that one scenario handled, I can figure the others out that I need.
UPDATE: I'm reading on filters now to see if I missed something...
The simplest was to hook into the authentication process is to provide your own AuthenticationProvider. There are only two methods to implement. In authenticate() you can do all of your custom stuff.
To configure your provider into the framework do something like:
<authentication-manager>
<authentication-provider ref="myAuthenticationProvider" />
</authentication-manager>

Spring Security 3.x: How can I enable both BASIC and DIGEST authentication?

I want to configure Spring Security to enable both BASIC and DIGEST authentication for the same set of URL's, but it's unclear whether or not this is possible. I see that I need to enable multiple AuthenticationEntryPoint instances to set the appropriate HTTP headers, but I don't see any built in classes to accomodate this. DelegatingAuthenticationEntryPoint comes close, but ultimately it only selects one entry point.
I implemented a custom AuthenticationEntryPoint that calls the commence method on a supplied list of AuthenticationEntryPoint instances, but it eventually throws an IllegalStateException because each AuthenticationEntryPoint calls sendError (which I gather is not allowed).
Is there any way to do this without implementing a completely custom entry point?
Id did it by configuring Spring security for Digest authentication only, and then adding a BasicProcessingFilter manually at the beginning of the filter chain, as explained There
<bean id="basicProcessingFilter" class="org.springframework.security.ui.basicauth.BasicProcessingFilter">
<property name="authenticationManager"><ref bean="authenticationManager"/></property>
<security:custom-filter before="AUTHENTICATION_PROCESSING_FILTER"/>
<property name="authenticationEntryPoint"><ref bean="authenticationEntryPoint"/></property>

Resources