x509 validation fails before it can be captured - spring

I have a Spring Boot application, using x509 authentication which further validates users against a database. When a user accesses the site, internal Spring code calls the loadUserByUsername method which in turn makes the database call. This all happens before the controller is aware anything is happening. If the user is not found it throws an EntityNotFoundException and displays the stack trace on the user's browser.
I'm using Spring Boot Starter. The controller has code to capture the exception and return a 'Not Authorized' message, but this happens long before. Has anyone else seen this and do you have a workaround?
#Service
public class UserService implements UserDetailsService {
public UserDetails loadUserByUsername(String dn) {
ApprovedUser details = auService.getOne(dn);
if (details == null){
String message = "User not authorized: " + dn;
throw new UsernameNotFoundException(message);
}
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
if (details.isAdminUser()){
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN_USER"));
}
return new AppUser(dn, "", authorities);
}

Usually, you would use a AuthenticationFailureHandler to encapsulate logic that's triggered by an AuthenticationException. The X509AuthenticationFilter would usually call PreAuthenticatedAuthenticationProvider to authenticate, which would in turn invoke the loadUserByUsername(...) method from UserDetailsService. Any AuthenticationException thrown by the UserDetailsService is caught by the filter and control is passed to the registered AuthenticationFailureHandler. This includes UsernameNotFoundException.
However, if you're using the X509Configurer, (http.x509()) there is no way of setting a handler directly on the filter. So once the exception is thrown, X509AuthenticationFilter catches it, sees that there's no default handler, and then simply passes the request to the next filter in the filter chain.
One way to get around this could be to provide a custom X509AuthenticationFilter.
In WebSecurityConfigurerAdapter:
#Autowired
private AuthenticationFailureHandler customFailureHandler;
#Autowired
private UserService customUserService;
#Bean(name = BeanIds.AUTHENTICATION_MANAGER)
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
protected void configure(HttpSecurity http) throws Exception {
...
http.x509().x509AuthenticationFilter(myX509Filter())
.userDetailsService(customUserService)
...
}
private X509AuthenticationFilter myX509Filter() {
X509AuthenticationFilter myCustomFilter = new X509AuthenticationFilter();
myCustomFilter.setAuthenticationManager(authenticationManagerBean());
...
myCustomFilter.setContinueFilterChainOnUnsuccessfulAuthentication(false);
myCustomFilter.setAuthenticationFailureHandler(customFailureHandler);
return myCustomFilter;
}
Then you can write your own AuthenticationFailureHandler implementation and expose it as a bean.

Related

How to track all login logs about the jwt in spring security

Recently, I started to make a platform and chose spring security as the back end and angular as the front end. And I want to track all login logs, such as failed login, successful login, username does not exist, incorrect password, etc.
I try to use spring aop to track all login logs, but I only get the logs when the login is successful.
These are the jwt filter and the spring aop code.
public class JwtUsernameAndPasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final AuthenticationManager authenticationManager;
public JwtUsernameAndPasswordAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
/* get username and password in user request by jwt */
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
try {
UsernameAndPasswordAuthenticationRequest authenticationRequest = new ObjectMapper()
.readValue(request.getInputStream(), UsernameAndPasswordAuthenticationRequest.class);
Authentication authentication = new UsernamePasswordAuthenticationToken(
authenticationRequest.getUsername(),
authenticationRequest.getPassword()
);
Authentication authenticate = authenticationManager.authenticate(authentication);
return authenticate;
} catch (IOException e) {
throw new RuntimeException();
}
}
/* create jwt token when user pass the attemptAuthentication */
#Override
protected void successfulAuthentication(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain, Authentication authResult) throws IOException, ServletException {
String key = "securesecuresecuresecuresecuresecuresecuresecuresecuresecuresecure";
String token = Jwts.builder()
.setSubject(authResult.getName())
.claim("authorities", authResult.getAuthorities())
.setIssuedAt(new Date())
.setExpiration(java.sql.Date.valueOf(LocalDate.now().plusWeeks(2)))
.signWith(Keys.hmacShaKeyFor(key.getBytes()))
.compact();
response.addHeader("Authorization", "Bearer " + token);
}
}
#Aspect
#Component
public class LoginLogAOP {
private static final Logger logger = LoggerFactory.getLogger(LoginLogAOP.class);
#AfterReturning(pointcut="execution(* org.springframework.security.authentication.AuthenticationManager.authenticate(..))"
,returning="result")
public void afteReturn(JoinPoint joinPoint,Object result) throws Throwable {
logger.info("proceed: {}", joinPoint.getArgs()[0]);
logger.info("result: {}", ((Authentication) result));
logger.info("user: " + ((Authentication) result).getName());
}
}
Has anyone tracked login logs through Spring Security jwt? Thank you very much for your help!
Your advice type #AfterReturning does exactly what the name implies: It kicks in after the method returned normally, i.e. without exception. There is another advice type #AfterThrowing, if you want to intercept a method which exits by throwing an exception. Then there is the general #After advice type which kicks in for both. It is like the supertype for the first two subtypes.
And then of course if you want to do more than just react to method results and log something, but need to actually modify method parameters or method results, maybe handle exceptions (which you cannot do in an "after" advice), you can use the more versatile, but also more complex #Around advice.
Actually, all of what I said is nicely documented in the Spring manual.
Update: I forgot to mention why #AfterReturning does not capture the cases you are missing in your log: Because according to the documentation for AuthenticationManager.authenticate(..), in case of disabled or locked accounts or wrong credentials the method must throw certain exceptions and not exit normally.

Throw custom exception from AuthenticationProvider to client(spring security)

I develop a spring boot REST service. I use #ControllerAdvice for exception catching. Also, I have a custom AuthenticationProvider and check a license in it.
#Component
public class MyAuthenticationProvider implements AuthenticationProvider {
private final LicenseService licenseService;
public MyAuthenticationProvider(LicenseService licenseService) {
this.licenseService = licenseService;
}
#Override
public boolean supports(Class<?> authentication) {
//...some code
}
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
try {
//...some code
licenseService.checkLicense(userDetails.getSomeId(), LicenseCode.FOO);
//..some code
} catch (LicenseException error) {
throw new AccessDeniedException(error.getMessage());
}
}
}
My licenseService throws LicenseException if the license does not exist or incorrect. I catch it and wrap to AccessDeniedException
at first, I wanted to catch LicenseException in #ControllerAdvice but quickly understood that it could be wrong. #ControllerAdvice catches exceptions in the controller layer.
That is why I wrap my exception to AccessDeniedException. But I want another logic: I want to throw a custom exception to the frontend. The frontend must understand this exception and show a special dialog to the client(License is required... bla-bla-bla). But I don't know how to do it on this step(AuthenticationProvider)
Your Controller catching the exception from your AuthenticationProvider would send a ResponseEntity with HttpStatus.FORBIDDEN to your client. You can wrap your exception or an errormessage in the body of the HTTP response.

How can I read the user credentials from a JSON login attempt using default classes?

I am following a tutorial on Implementing JWT Authentication on Spring Boot APIs and in the key part of the author's JWTAuthenticationFilter class (which is just what it sounds like), he retrieves the username and password from the JSON body of a POST request to a login endpoint.
So, using curl or Postman or something, you'd POST to /login with the body of your request containing something like {"username":"joe", "password":"pass"}.
The author's authentication filter maps this JSON into an ApplicationUser instance with this method:
#Override
public Authentication attemptAuthentication(HttpServletRequest req,
HttpServletResponse res) throws AuthenticationException {
try {
ApplicationUser creds = new ObjectMapper()
.readValue(req.getInputStream(), ApplicationUser.class);
return authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
creds.getUsername(),
creds.getPassword(),
new ArrayList<>())
);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Good enough, but to do this he's created a custom class ApplicationUser as well as a customer UserDetailsService, a UserController, and an ApplicationUserRepository all to work with his own idiosyncratic in-memory database backend. In my real Spring Boot app, I'm using the default database schema and letting Spring Boot authenticate users via JDBC. It works great with form authentication. This is the bit in my WebSecurityConfigurerAdapter that does it:
#Autowired
private DataSource dataSource;
#Override
public void configure(AuthenticationManagerBuilder builder) throws Exception {
builder .jdbcAuthentication()
.dataSource(dataSource);
}
So my question is, how does the attemptAuthentication method need to change from the tutorial's code? I took a guess that the default implementation might be User.class and tried to plug it into the expression that imports "creds", like this:
User creds = new ObjectMapper().readValue(request.getInputStream(), User.class);
That didn't work. I get this exception:
webapp_1 | 2019-11-22 15:54:43.234 WARN 1 --- [nio-8080-exec-2] n.j.w.g.config.JWTAuthenticationFilter : inputstream: org.apache.catalina.connector.CoyoteInputStream#1477c9d5
webapp_1 | 2019-11-22 15:54:43.298 ERROR 1 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
webapp_1 |
webapp_1 | java.lang.RuntimeException: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.security.core.userdetails.User` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
I don't want to just dive into subclassing User because I actually don't even know if it's the right class, or if I even need it here. Can I just extract username and password from my JSON POST in some other way, maybe bypassing the use of ObjectMapper()? Or should I create a private internal class here? To sum up, the question is: How can I best adapt this "attemptAuthentication" method while using the default JDBC-based implementation of users in Spring Boot?
I found a solution that works, although I still think that there's got to be a more elegant way of doing it. What I do is define a static inner class LoginAttempt and use ObjectMapper to read the JSON as an instance of it.
I found that without the static modifier, Jackson cannot deserialize an inner class (see this question) but with "static" it works.
The relevant code from JWTAuthenticationFilter is:
static class LoginAttempt {
private String username;
private String password;
public LoginAttempt() {}
public String getUsername() { return username; }
public String getPassword() { return password; }
public void setUsername(String username) { this.username = username; }
public void setPassword(String password) { this.password = password; }
}
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
try {
LoginAttempt creds = new ObjectMapper().readValue(request.getInputStream(), LoginAttempt.class);
return authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
creds.getUsername(),
creds.getPassword(),
new ArrayList<>()
)
);
} catch( IOException e ) {
throw new RuntimeException(e);
}
}

Where is better to put my custom authentication logic?

I want to add a bit of logic to my authentication in Spring Boot, check if an account have a specific logic, for example if a date in its account is before the current date.
Where is best placed in a custom filter or in UserDetailsService?
If it's in a filter, is better to extends from any spring class?
Explanation
As you can see bellow I use a custom userDetailsService() to get the users details (CuentaUser) in which there are the fields needed for the logic (for example the expiration date). So now I need to add the logic and comes to me two places where I can put it: in UserDetailsServices (throwing an exception if the logic fails) or as a custom filter.
Where is better to put my custom the authentication logic?
This is my actual security configuration:
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private CuentaRepository accountRepository;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService());
}
#Bean
public UserDetailsService userDetailsService() {
return (username) -> accountRepository.findByUsuario(username)
.map(a -> new CuentaUser(a, AuthorityUtils.createAuthorityList("USER", "write")))
.orElseThrow(() -> new UsernameNotFoundException("could not find the user '" + username + "'"));
}
#Override
protected void configure(HttpSecurity http) throws Exception {
CsrfTokenResponseHeaderBindingFilter csrfTokenFilter = new CsrfTokenResponseHeaderBindingFilter();
http.addFilterAfter(csrfTokenFilter, CsrfFilter.class);
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
Edit: I found that for the example of expiration date, UserDetails have an attribute for it, so is better to use it. Anyway you need to check it with a custom AuthenticationProvider if you don't use the default.
You can use an AuthenticationProvider and put the login inside it.
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
You can see more here:
http://www.baeldung.com/spring-security-authentication-provider

Add custom UserDetailsService to Spring Security OAuth2 app

How do I add the custom UserDetailsService below to this Spring OAuth2 sample?
The default user with default password is defined in the application.properties file of the authserver app.
However, I would like to add the following custom UserDetailsService to the demo package of the authserver app for testing purposes:
package demo;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Service;
#Service
class Users implements UserDetailsManager {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
String password;
List<GrantedAuthority> auth = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER");
if (username.equals("Samwise")) {
auth = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_HOBBIT");
password = "TheShire";
}
else if (username.equals("Frodo")){
auth = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_HOBBIT");
password = "MyRing";
}
else{throw new UsernameNotFoundException("Username was not found. ");}
return new org.springframework.security.core.userdetails.User(username, password, auth);
}
#Override
public void createUser(UserDetails user) {// TODO Auto-generated method stub
}
#Override
public void updateUser(UserDetails user) {// TODO Auto-generated method stub
}
#Override
public void deleteUser(String username) {// TODO Auto-generated method stub
}
#Override
public void changePassword(String oldPassword, String newPassword) {
// TODO Auto-generated method stub
}
#Override
public boolean userExists(String username) {
// TODO Auto-generated method stub
return false;
}
}
As you can see, this UserDetailsService is not autowired yet, and it purposely uses insecure passwords because it is only designed for testing purposes.
What specific changes need to be made to the GitHub sample app so that a user can login as username=Samwise with password=TheShire, or as username=Frodo with password=MyRing? Do changes need to be made to AuthserverApplication.java or elsewhere?
SUGGESTIONS:
The Spring OAuth2 Developer Guide says to use a GlobalAuthenticationManagerConfigurer to configure a UserDetailsService globally. However, googling those names produces less than helpful results.
Also, a different app that uses internal spring security INSTEAD OF OAuth uses the following syntax to hook up the UserDetailsService, but I am not sure how to adjust its syntax to the current OP:
#Order(Ordered.HIGHEST_PRECEDENCE)
#Configuration
protected static class AuthenticationSecurity extends GlobalAuthenticationConfigurerAdapter {
#Autowired
private Users users;
#Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(users);
}
}
I tried using #Autowire inside the OAuth2AuthorizationConfig to connect Users to the AuthorizationServerEndpointsConfigurer as follows:
#Autowired//THIS IS A TEST
private Users users;//THIS IS A TEST
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)
.accessTokenConverter(jwtAccessTokenConverter())
.userDetailsService(users)//DetailsService)//THIS LINE IS A TEST
;
}
But the Spring Boot logs indicate that the user Samwise was not found, which means that the UserDetailsService was not successfully hooked up. Here is the relevant excerpt from the Spring Boot logs:
2016-04-20 15:34:39.998 DEBUG 5535 --- [nio-9999-exec-9] o.s.s.a.dao.DaoAuthenticationProvider :
User 'Samwise' not found
2016-04-20 15:34:39.998 DEBUG 5535 --- [nio-9999-exec-9]
w.a.UsernamePasswordAuthenticationFilter :
Authentication request failed:
org.springframework.security.authentication.BadCredentialsException:
Bad credentials
What else can I try?
I ran into a similar issue when developing my oauth server with Spring Security. My situation was slightly different, as I wanted to add a UserDetailsService to authenticate refresh tokens, but I think my solution will help you as well.
Like you, I first tried specifying the UserDetailsService using the AuthorizationServerEndpointsConfigurer, but this does not work. I'm not sure if this is a bug or by design, but the UserDetailsService needs to be set in the AuthenticationManager in order for the various oauth2 classes to find it. This worked for me:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
Users userDetailsService;
#Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
// other stuff to configure your security
}
}
I think if you changed the following starting at line 73, it may work for you:
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.parentAuthenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
You would also of course need to add #Autowired Users userDetailsService; somewhere in WebSecurityConfigurerAdapter
Other things I wanted to mention:
This may be version specific, I'm on spring-security-oauth2 2.0.12
I can't cite any sources for why this is the way it is, I'm not even sure if my solution is a real solution or a hack.
The GlobalAuthenticationManagerConfigurer referred to in the guide is almost certainly a typo, I can't find that string anywhere in the source code for anything in Spring.
My requirement was to get a database object off the back of the oauth2 email attribute. I found this question as I assumed that I need to create a custom user details service. Actually I need to implment the OidcUser interface and hook into that process.
Initially I thought it was the OAuth2UserService, but I've set up my AWS Cognito authentication provider so that it's open id connect..
//inside WebSecurityConfigurerAdapter
http
.oauth2Login()
.userInfoEndpoint()
.oidcUserService(new CustomOidcUserServiceImpl());
...
public class CustomOidcUserServiceImpl implements OAuth2UserService<OidcUserRequest, OidcUser> {
private OidcUserService oidcUserService = new OidcUserService();
#Override
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser = oidcUserService.loadUser(userRequest);
return new CustomUserPrincipal(oidcUser);
}
}
...
public class CustomUserPrincipal implements OidcUser {
private OidcUser oidcUser;
//forward all calls onto the included oidcUser
}
The custom service is where any bespoke logic can go.
I plan on implementing UserDetails interface on my CustomUserPrincipal so that I can have different authentication mechanisms for live and test to facilitate automated ui testing.
I ran into the same issue and originally had the same solution as Manan Mehta posted. Just recently, some version combination of spring security and spring oauth2 resulted in any attempt to refresh tokens resulting in an HTTP 500 error stating that UserDetailsService is required in my logs.
The relevant stack trace looks like:
java.lang.IllegalStateException: UserDetailsService is required.
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$UserDetailsServiceDelegator.loadUserByUsername(WebSecurityConfigurerAdapter.java:463)
at org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper.loadUserDetails(UserDetailsByNameServiceWrapper.java:68)
at org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider.authenticate(PreAuthenticatedAuthenticationProvider.java:103)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
at org.springframework.security.oauth2.provider.token.DefaultTokenServices.refreshAccessToken(DefaultTokenServices.java:150)
You can see at the bottom that the DefaultTokenServices is attempting to refresh the token. It then calls into an AuthenticationManager to re-authenticate (in case the user revoked permission or the user was deleted, etc.) but this is where it all unravels. You see at the top of the stack trace that UserDetailsServiceDelegator is what gets the call to loadUserByUsername instead of my beautiful UserDetailsService. Even though inside my WebSecurityConfigurerAdapter I set the UserDetailsService, there are two other WebSecurityConfigurerAdapters. One for the ResourceServerConfiguration and one for the AuthorizationServerSecurityConfiguration and those configurations never get the UserDetailsService that I set.
In tracing all the way through Spring Security to piece together what is going on, I found that there is a "local" AuthenticationManagerBuilder and a "global" AuthenticationManagerBuilder and we need to set it on the global version in order to have this information passed to these other builder contexts.
So, the solution I came up with was to get the "global" version in the same way the other contexts were getting the global version. Inside my WebSecurityConfigurerAdapter I had the following:
#Autowired
public void setApplicationContext(ApplicationContext context) {
super.setApplicationContext(context);
AuthenticationManagerBuilder globalAuthBuilder = context
.getBean(AuthenticationManagerBuilder.class);
try {
globalAuthBuilder.userDetailsService(userDetailsService);
} catch (Exception e) {
e.printStackTrace();
}
}
And this worked. Other contexts now had my UserDetailsService. I leave this here for any brave soldiers who stumble upon this minefield in the future.
For anyone got UserDetailsService is required error when doing refresh token, and you confirm you already have UserDetailsService bean.
try add this:
#Configuration
public class GlobalSecurityConfig extends GlobalAuthenticationConfigurerAdapter {
private UserDetailsService userDetailsService;
public GlobalSecurityConfig(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
#Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
}
This is my try and error, maybe not work for you.
By the way, if you give up "guess" which bean will pick by spring, you can extends AuthorizationServerConfigurerAdapter and WebSecurityConfigurerAdapter and config all stuff by yourself, but I think it's lose power of spring autoconfig.
Why I need config everything if I just need customize some config?

Resources