How to retrive user entered password in UserDetailsService - spring

Spring security 3 may do some trick to validate user's password behind the scene, but that's become my problem right now, I am trying to intercept whatever entered for password by user, and just couldn't find a clue.
#Component("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
............
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
User user = userService.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User '"+username+"' not found !");
}
return user;
}
}
is there any API that I can use to intercept the user's password?

The UserDetailsService is responsible to load the user and provide a UserDetails object that contains the password stored in the database. Unfortunaly (for you) this password is hashed (SHA or MD5) in the most cases.
If you want to intercept the password that is entered by the user, then you have different choices:
The UserNamePasswordFilter (when you use Form Authentication, if you use an other kind of authentication, then you need an other filter) ins one point to intercept the password. It is responsible to fetch the login http request, create a UserNamePasswordAuthenticationToken and forward them to the AuthenticationManager.
An other interception point would be the AuthenticationManager (more precise the ProviderManager - then only real implemenation of the AuthenticationManager). It has a method Authentication authenticate(Authentication authentication) that take the user input (Subclass of Authentication for example UsernamePasswordAuthenticationToken) and verifiy it (by forwarding it to an AuthenticationProvider)
The AuthenticationProvider (for example the DaoAuthenticationProvider) would be an other place to intercept the password.
The DaoAuthenticationProvider uses a PasswordEncoder to hash the user entered password. Then the DaoAuthenticationProvider will compare the hash password obtained from the database with the hashed password entered by the user. So the PasswordEncoder is probably the easiest way to intercept the user entered password!
And of course you can intercept the HttpRequest itself: eighter you register an additional SecurityFilter (before the UsernamePasswordFilter) or a simple Servlet Filter (before the Spring Security Filter). (A Spring Interceptor will not work, because the Spring Security Filter will handle the request an will not forward it to the Spring Dispatcher, so the Spring Dispatcher can not invoke the Spring Interceptor.)
password encoder registration:
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider user-service-ref="jdbcUserService">
<sec:password-encoder ref="myPasswordEncoder"/>
</sec:authentication-provider>
</sec:authentication-manager>
<beans:bean id="myPasswordEncoder"class="InterceptingPassordEncoderSubclassShaPasswordEncoder" />

Related

Spring Boot - JWT authentication without db calls

Is it possible to implement simple JWT authentication (not caring about invalidating tokens - I'll do it in cache) without database calls to load user into Security Context? I see my current implementation hits database with every call to api (to load user into security context). Below you can see part of implementation of JwtAuthenticationFilter extending OncePerRequestFilter:
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
String jwt = getJwtFromRequest(request);
if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
Long userId = tokenProvider.getUserIdFromJWT(jwt);
UserDetails userDetails = customUserDetailsService.loadUserById(userId);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception ex) {
logger.error("Could not set user authentication in security context", ex);
}
filterChain.doFilter(request, response);
}
And here is the call to database, which I would like to avoid (with every authenticated call to api):
#Service
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
UserRepository userRepository;
// This method is used by JWTAuthenticationFilter
#Transactional
public UserDetails loadUserById(Long id) {
User user = userRepository.findById(id).orElseThrow(
() -> new UsernameNotFoundException("User not found with id : " + id)
);
return UserPrincipal.create(user);
}
}
I found some kind of solution of problem to build UserPrincipal object (it implements UserDetails interface) with only user id, username and granted authorities, and without e.g. password, which I cannot read from JWT token itself (the rest I can), but I am not sure if it's secure and and considered as a good-practice solution (UserDetails class requires password field and storing it JWT would not be wise I think). I need UserPrincipal instance (implementing UserDetails interface) to support as argument to UsernamePasswordAuthenticationToken, as you can see in the first paragraph.
One approach can be having two filter as follows.
CustomAuthenticationFilter that serves only login request/endpoint. You can do the following in this filter,
Call the db and validate the credential and retrieve the roles of the user
Generate the JWT token and you can store the user id or email along with roles in the subject of the JWT token. As we are adding user specific details I would recommend to encrypt the JWT token.
CustomAuthroizationFilter that serves all other requests/endpoints. You can do the following in this filter,
Validate JWT token
Retrieve the user id or email along with roles of the user from the subject of the JWT token.
Build spring authentication (UsernamePasswordAuthenticationToken) and set it in SecurityContextHolder like you did.
This way you will be calling db only during the login request not for all other api endpoints.

Spring security: what function does AuthenticationManager.authenticate() perform

I have been studying Spring security with JWT for a while and i noticed that at every tutorial I read, the username and password is taken, wrapped in a UsernamePasswordAuthenticationToken and passed on to a AuthenticationManager.authenticate() somthinglike this :
#RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(#RequestBody JwtAuthenticationRequest authenticationRequest) throws AuthenticationException {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword()));
// Reload password post-security so we can generate the token
final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails);
// Return the token
return ResponseEntity.ok(new JwtAuthenticationResponse(token));
}
my question is what does the authenticate method do, why is it used ?
From the Spring Security Reference:
AuthenticationManager is just an interface, so the implementation can be anything we choose. (...) The default implementation in Spring Security is called ProviderManager and rather than handling the authentication request itself, it delegates to a list of configured AuthenticationProviders, each of which is queried in turn to see if it can perform the authentication. Each provider will either throw an exception or return a fully populated Authentication object.

How to have Spring Security enabled for an application using third party login?

I have a Spring Boot enabled application whose login is controlled by third party Siteminder application. After successful authentication, Sitemeinder redirects to our application url. We fetch the HttpRequest from Siteminder and process the requests.
Now, how can Spring security be enabled in this case for authorizing users based on roles.
#Controller
public class LoginController
#RequestMapping( value= "/")
public void requestProcessor(HttpServletRequest request)
{
.
.
.}
The above controller's request mapper reads the request coming from SiteMinder and processes the request which has the Role of the user logged in. Where can we have Spring Security enabled to authorize pages and service methods to the user.
This is an scenario for the PreAuthenticated security classes:
Take a look here:
http://docs.spring.io/spring-security/site/docs/current/reference/html/preauth.html
Spring Security processes request before it gets to your controller in a filter configured in spring security configuration.
There is a documentation on how to configure spring security with SiteMinder.
The rules in your configuration will define the access to resources
Depends what you get in session. If somehow u can to take user and password from session you can authenticate user directly from code as :
#Autowired
AuthenticationManager authenticationManager;
...
public boolean autoLogin(String username, String password) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
Authentication auth = authenticationManager.authenticate(token);
if (auth.isAuthenticated()) {
logger.debug("Succeed to auth user: " + username);
SecurityContextHolder.getContext().setAuthentication(auth);
return true;
}
return false;
}

spring security authentication using ip address and username password

I am using loadUserByUsername method to authenticate user, however, I need to validate against allowed ip addresses as well.
But when I am trying
SecurityContextHolder.getContext().getAuthentication();
getting null.
Please advice, how I can access users client ip address while authenticating user.
To solve your problem you should implement custom authentication provider (that can be based on DaoAuthenticationProvider or can be implemented from scratch, etc). This authentication provider should be registered in Authentication manager providers set. Also, this provider will have autowired HttpServletRequest type property, related to context http request. Then, when you performing client authenticationv via that provider, you can obtain user IP address by invoking HttpServletRequest.getRemoteAddr().
Code:
/**
* IP address based authentication provider
*/
#Service
public class IPAddressBasedAuthenticationProvider extends AuthenticationProvider {
/**
* Context http request
*/
#Autowired
private HttpServletRequest request;
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String ipAddress = request.getRemoteAddr();
//do authentication specific stuff (accessing users table in database, etc.)
//return created authentication object (if user provided valid credentials)
}
}
Configuration:
<security:http auto-config="true" authentication-manager-ref="authenticationManager" use-expressions="true"/>
<bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
<constructor-arg name="providers">
<list>
<ref bean="iPAddressBasedAuthenticationProvider"/>
</list>
</constructor-arg>
</bean>
Also, you can add other authentication providers (if you need to).
Hope this helps.
Links: AuthenticationProvider
ProviderManager
/**
* IP address based authentication provider
*/
#Service
public class IPAddressBasedAuthenticationProvider extends AuthenticationProvider {
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
final WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails();
details.getRemoteAddress();
}
}
You are implementing UserDetailsService's loadUserByUsername method.
As per documentation
There is often some confusion about UserDetailsService. It is purely a DAO for user data and performs no other function other than to supply that data to other components within the framework. In particular, it does not authenticate the user, which is done by the AuthenticationManager. In many cases it makes more sense to implement AuthenticationProvider directly if you require a custom authentication process.
UserDetails userDetails= customUserDetailsService.loadUserByUsername("name");
this will give a userDetails object.You can do all authority related code in loadUserByUsername().If you would like to manually set an authenticated user in Spring Security.follow the code
Authentication authentication= new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()) ;
SecurityContextHolder.getContext().setAuthentication(authentication);
You will get IP address from request header.
How can I retrieve IP address from HTTP header in Java
you can do that somewhere in spring security filterchain.

remember-me and authentication-success-handler

i have strange issue of for login sucess and redirect to page.
below is my spring security configuration.
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/login.hst**" access="anonymous or authenticated" />
<intercept-url pattern="/**/*.hst" access="authenticated" />
<form-login login-page="/login.hst"
authentication-failure-url="/login.hst?error=true"
authentication-success-handler-ref="loginSucessHandler" />
<logout invalidate-session="true" logout-success-url="/home.hst"
logout-url="/logout.hst" />
<remember-me key="jbcpHaverERP" authentication-success-handler-ref="loginSucessHandler"/>
<session-management>
<concurrency-control max-sessions="1" />
</session-management>
</http>
LoginSuessHandler class:
#Service
public class LoginSucessHandler extends
SavedRequestAwareAuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws ServletException, IOException {
...
super.setUseReferer(true);
super.onAuthenticationSuccess(request, response, authentication);
}
}
now problem of redirect to requested page on success. if i directly refer to any secure url spring redirects me to login page and on successful login to original requested link.
but this is not working in case if user had earlier selected remember-me and then closing browser and now requesting direct URL, he is being properly authenticated but instead of redirecting him to requested page spring redirects to /. i have checked log and some spring source code and found it is not able to determine target url.
i have tried to set refer but referer value is null. but one strange thing i have noticed that in spring security configuration if i remove authentication-success-handler from remember-me configuration then it works.
<remember-me key="jbcpHaverERP" authentication-success-handler-ref="loginSucessHandler"/>
not able to figure out issue. is authentication-success-handler implementation requied to be different for form login and remember-me?
Remember-me differs from form-login in that authentication occurs during the actual request the user makes. For form-login, the user must first be redirected to the login page, submit the login form and after that they are redirected to the original target (which is usually cached in the session). So form-login requires a redirect, whereas remember-me doesn't. With a remember-me request, the user can be authenticated, and the request allowed to proceed without any intervention.
The primary purpose of an AuthenticationSuccessHandler is to control the navigation flow after authentication, so you wouldn't normally use one with remember-me at all. Using SavedRequestAwareAuthenticationSuccessHandler isn't a good idea, as there won't be a saved request available. If there is no saved request, then by default it will perform a redirect to "/" as you have observed.
If all you want is to add some functionality during a remember-me login, then you can implement the AuthenticationSuccessHandler interface directly without performing a redirect or a forward. As I explained above, you can't use the same implementation for form-login, since the current request is the submission of the login form (usually to the URL j_spring_security_check), and not a request to a URL within your application. So you need a redirect for form-login.
You would rather use ApplicationListener and look for the event InteractiveAuthenticationSuccessEvent.
InteractiveAuthenticationSuccessEvent has a property generatedBy which will be the filter, ie UsernamePasswordAuthenticationFilter (form logins) and RememberMeAuthenticationFilter (remeber me logins)
#Component
class AuthenticationApplicationListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {
#Override
void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) {
//do something
}
}
using a custom implementation of AuthenticationSuccessHandler on rememberMe will cause problems. Take a look at the flow in RememberMeAuthenticationFilter. if the successHandler is used, the filter chain is bypassed
Using an AuthenticationSuccessHandler does not work. As stated in another answer, the spring security filter chain will be bypassed!
What works, is to use an ApplicationListener - as another answer also proposes. But to find out, if your user is authenticated by remember me, the idea to use InteractiveAuthenticationSuccessEvent.getGeneratedBy() is not working: getGeneratedBy returns Class<T>, that means a generic. Therefore at runtime you cannot find out, if T is a RememberMeAuthenticationFilter.
What worked fine for me: Use InteractiveAuthenticationSuccessEvent.getAuthentication().
Here an example (by the way: #EventListener is used since Spring Security 4.2 - if you use an earlier version, do the following via implementing ApplicationListener<InteractiveAuthenticationSuccessEvent>):
#Component
public class AuthenticationApplicationListener {
#EventListener
public void handleInteractiveAuthenticationSuccess(InteractiveAuthenticationSuccessEvent event) {
if (RememberMeAuthenticationToken.class.isAssignableFrom(event.getAuthentication().getClass())) {
.... do some stuff
}
}
}
You should implement different authentication-success-handler for login form and for remember-me.
If you want to perform redirect in remeber-me handler you can use SimpleUrlAuthenticationSuccessHandler and set DefaultTargetUrl.
public class RememberMeAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// ...
super.setAlwaysUseDefaultTargetUrl(true);
super.setDefaultTargetUrl(request.getRequestURL().toString());
super.onAuthenticationSuccess(request, response, authentication);
}

Resources