AuthenticationFailureHandler HttpServletResponse.sendError url - spring

I have developed single page web application using Spring Boot and Spring MVC. I am using Spring Security and JWT to authenticate users. I have written a custom AuthenticationFailureHandler which works but I want to know how I can control the url that a user gets redirect to when an exception is thrown. My AuthenticationFailureHandler looks like this:
public class JwtAuthenticationFailureHandler implements AuthenticationFailureHandler {
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.sendError(HttpStatus.UNAUTHORIZED.value(), exception.getMessage());
}
}
When the JWT expires the application throws an AccountExpiredException, the AuthenticationFailureHandler.onAuthenticationFailure method gets executed and the user gets redirected to the login page:
http://localhost:8080/login?sessionExpired=true
This is all good, but I have no idea how the sessionExpired=true query string is generated and I want to have some control over it. In the past I have used ExceptionMappingAuthenticationFailureHandlers like this:
Map<String, String> mappings = new HashMap<>();
mappings.put(BadCredentialsException.class.getCanonicalName(), BAD_CREDENTIALS_EXCEPTION_URL);
mappings.put(AccountExpiredException.class.getCanonicalName(), ACCOUNT_EXPIRED_EXCEPTION_URL);
mappings.put(CredentialsExpiredException.class.getCanonicalName(), CREDENTIALS_EXPIRED_EXCEPTION_URL);
mappings.put(DisabledException.class.getCanonicalName(), ACCOUNT_INACTIVE_EXCEPTION_URL);
mappings.put(LockedException.class.getCanonicalName(), ACCOUNT_LOCKED_EXCEPTION_URL);
mappings.put(ValidationException.class.getCanonicalName(), VALIDATION_EXCEPTION_URL);
ExceptionMappingAuthenticationFailureHandler exceptionMappingAuthenticationFailureHandler = new ExceptionMappingAuthenticationFailureHandler();
exceptionMappingAuthenticationFailureHandler.setExceptionMappings(mappings);
So based on the various exceptions above I would like to be able to redirect to the following URLs:
http://localhost:8080/login?error
http://localhost:8080/login?accountexpired
http://localhost:8080/login?credentialsexpired
http://localhost:8080/login?accountlocked
http://localhost:8080/login?accountinactive
http://localhost:8080/login?validationerror
I'm not sure who to do this with response.sendError and I don't know how the sessionExpired=true query string is being generated. I have tried throwing different exceptions but the url never changes.
I have a couple of questions. Is it possible to control the URL when using HttpServletResponse.sendError and if not is it possible ot set the HttpStatus code when using ExceptionMappingAuthenticationFailureHandler.sendRedirect?

Why don't you try to use the response.sendRedirect:
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
final HttpSession session = request.getSession(false);
if (session != null) {
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
}
//here the logic to get the error type of the exception
String errorMessage = ????
redirectStrategy.sendRedirect(request, response,
"http://localhost:8080/login?" + errorMessage);
}

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.

Spring Boot Redirect to requested URL after login

I have a Spring Boot UI application. I am trying to redirect users to the originally requested URL after login.
When a user requests http://www.example.com/myapp/user/22, the application aptly redirects to http://www.example.com/myapp/login. Once the user logs in, the application redirects to http://www.example.com/myapp/dashboard. I would like the application to redirect to http://www.example.com/myapp/user/22.
I have gone through several links and feel I have a proper configuration, yet, redirection is not working as expected.
My Security Config is
public class SecurityConfig extends WebSecurityConfigurerAdapter {
.....
....
#Autowired
private MyAuthenticationSuccessHandler authenticationSuccessHandler;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.
authorizeRequests()
.antMatchers("/user/**").authenticated()
.and().csrf().disable().formLogin()
.successHandler(authenticationSuccessHandler)
......
and My Success Handler is
#Component
public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
...
public MyAuthenticationSuccessHandler() {
super();
this.setDefaultTargetUrl("/myapp/dashboard");
this.setUseReferer(true);
}
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
//Do something ..........
........
.........
super.onAuthenticationSuccess(request, response, authentication);
}
I tried using SavedRequestAwareAuthenticationSuccessHandler too.
I notice that my success handler is invoked, but the target URL is always /user/login and my login controller is invoked..
#RequestMapping("/login")
public ModelAndView login(#ModelAttribute() {
if(!userIdentified) {
//go to login page
} else {
new ModelAndView("redirect:/myapp/dashboard");
}
}
and the user is redirected to "dashboard".
What else am I missing?
Use "Referer" from session attribute to get the latest request URL. On my app, i use this one
public class CustomAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
public static final String REDIRECT_URL_SESSION_ATTRIBUTE_NAME = "REDIRECT_URL";
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
Object redirectURLObject = request.getSession().getAttribute(REDIRECT_URL_SESSION_ATTRIBUTE_NAME);
if(redirectURLObject != null)
setDefaultTargetUrl(redirectURLObject.toString());
else{
setDefaultTargetUrl("/");
}
request.getSession().removeAttribute(REDIRECT_URL_SESSION_ATTRIBUTE_NAME);
super.onAuthenticationSuccess(request, response, authentication);
}
}
Edit :
Sorry i forgot to show the login controller
#RequestMapping(method = RequestMethod.GET, value = {"/login"})
String login(Model model, Principal principal, HttpServletRequest request) throws Exception{
String referer = request.getHeader("Referer"); //Get previous URL before call '/login'
//save referer URL to session, for later use on CustomAuthenticationSuccesshandler
request.getSession().setAttribute(CustomAuthenticationSuccessHandler.REDIRECT_URL_SESSION_ATTRIBUTE_NAME, referer);
return principal == null ? "login" : "redirect:/";
}
Although Singgih S answer works, BUT there is a better way as below :
Ref:
https://www.baeldung.com/spring-security-redirect-login
There is no magic in these easy to use features in Spring Security.
When a secured resource is being requested, the request will be
filtered by a chain of various filters. Authentication principals and
permissions will be checked. If the request session is not
authenticated yet, AuthenticationException will be thrown.
The AuthenticationException will be caught in the
ExceptionTranslationFilter, in which an authentication process will be
commenced, resulting in a redirection to the login page.
Therefore :
1. When redirection to the "/login" page occurs, your secured request url is saved in the session as DefaultSavedRequest object.
2. Also we know when a successful form based login occurs, one of the implementations of AuthenticationSuccessHandler is called.
so we can create a custom class and get DefaultSavedRequest in it as below :
public class CustomAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST");
if(defaultSavedRequest != null){
getRedirectStrategy().sendRedirect(request, response, defaultSavedRequest.getRedirectUrl());
}else{
super.onAuthenticationSuccess(request, response, authentication);
}
}
}
3. We have to introduce this class in WebSecurityConfigurerAdapter :
#Override
protected void configure(HttpSecurity http) throws Exception {
http.(...).anyRequest().authenticated().and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login")
.successHandler(new CustomAuthenticationSuccessHandler());
So you can implement your logic in the above onAuthenticationSuccess method.
Best wishes
The Spring route, ala extending SavedRequestAwareAuthenticationSuccessHandler or SimpleUrlAuthenticationSuccessHandler can be a bit clunky to implement. In the controller (ex. a POST method that processes logins), you can do the header request yourself; ex:
HttpServletRequest request =null;
String priorUrl = request.getHeader("Referer");
You will notice that you will have the URL prior to either a manual (initiated by user) logout or a session timeout (as handled by Spring session): you'll get an https://iAmPriorUrl.com/.... Then you can do whatever you want with it.

dynamically add param to userAuthorizationUri in oauth2

Sometimes user's refresh token in local DB becomes stale. To replenish I'm trying to add prompt=consent param while making the oauth2 call. I was trying to #Autowire AuthorizationCodeAccessTokenProvider in my config class and in the afterPropertiesSet I was doing a setTokenRequestEnhancer and then realized that this bean is not even initialized via spring container when i looked the following code in OAuth2RestTemplate
private AccessTokenProvider accessTokenProvider = new AccessTokenProviderChain(Arrays.<AccessTokenProvider> asList(
new AuthorizationCodeAccessTokenProvider(), new ImplicitAccessTokenProvider(),
new ResourceOwnerPasswordAccessTokenProvider(), new ClientCredentialsAccessTokenProvider()));
Searched if any spring code is calling org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.setAuthorizationRequestEnhancer(RequestEnhancer) to learn how to access it, but no one is calling it.
Question: How to dynamically add a param to userAuthorizationUri while making oauth2 call?
Unfortunately, I haven't found an elegant solution neither. I have noticed, however, that redirect is triggered by UserRedirectRequiredException.
I was able to dynamically add request params by registering custom filter that modifies this exception on the fly.
#Component
#Order(-102)
public class EnhanceUserRedirectFilter implements Filter {
#Override
public void init(final FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
try {
chain.doFilter(request, response);
} catch (final UserRedirectRequiredException ex) {
ex.getRequestParams().put("prompt", "consent");
throw ex;
}
}
#Override
public void destroy() {
}
}
Please note, such servlet filter has to have higher precedence than Spring Security. In my case, -102 is higher precedence than Spring Security default of -100.

SSO with Spring security

I have an application, where user is pre-authorized by SSO and lands to my page, now I need to make a call to another rest api to get some data, which is running on another server, but it will be use the same authentication. So I just wanted to know, how I can provide the authentication process? Do I need to set the cookie what I am getting from the incoming request.
When the request lands on your page it should have a token or key, in the http AUTHORIZATION header, this should be used with a filter
public class AuthFilter extends OncePerRequestFilter {
private String failureUrl;
private SimpleUrlAuthenticationFailureHandler failureHandler = new SimpleUrlAuthenticationFailureHandler();
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
try {
// check your SSO token here
chain.doFilter(request, response);
} catch (OnlineDriverEnquiryException ode) {
failureHandler.setDefaultFailureUrl(failureUrl);
failureHandler.onAuthenticationFailure(request, response, new BadCredentialsException("Captcha invalid!"));
}
}
public String getFailureUrl() {
return failureUrl;
}
public void setFailureUrl(String failureUrl) {
this.failureUrl = failureUrl;
}
}
Also read this post on how to set up the auto config. Spring security without form login

Set a redirect into a custom Authentication Failure Handler with Spring

Which is the properly way to set a redirect into a custom AuthenticationFailureHandler in Spring?
Is it possible to call a controller?
The code is as follows:
#Component
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
#Override
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException {
super.onAuthenticationFailure(request, response, exception);
if (exception.getClass().isAssignableFrom(
CustomUsernameNotFoundException.class)) {
// TODO Set the redirect
}
}
}
Try soemthing like this
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
saveException(request, exception);
//do your things
getRedirectStrategy().sendRedirect(request, response, "/page/login?error=Retry");
}
You are calling super.onAuthenticationFailure which will peform a redirect to the configured URL. The response is thus already committed and you cannot decide to redirect somewhere else.
You can configure SimpleUrlAuthenticationFailureHandler to redirect to one URL and only call the super method if you aren't going to do a redirect yourself.
Alternatively, implement AuthenticationFailureHandler directly and implement all the logic you want in the failure method - once things get beyond a certain level of complexity I prefer to avoid inheritance altogether:
if (oneCondition) {
// redirect to IdP
} else {
// redirect to registration page
}
You can call a controller., a code snippet from you would help, but am getting this from the example that is discussed here.,
Spring Security Tutorial
#RequestMapping(value = "/login/failure")
public String loginFailure() {
String message = "Login Failure!";
return "redirect:/login?message="+message;
}
make sure you understand how the redirect works by looking at the mapping for login in the xml
Spring Mapping.xml
You can redirect to a specific URL.
response.sendRedirect("/redirect");

Resources