spring security LogoutSuccessHandler message [duplicate] - java

I have a problem with Spring Security authentication failure handler redirect with parameter.
In security config when I use
failureUrl("/login.html?error=true")
it works. But when I use custom authentication failure handler (as shown below), it always returns: url/login.html
getRedirectStrategy().sendRedirect(request, response, "/login.html?error=true");
or
response.sendRedirect(request.getContextPath() + "/login.html?error=true");
I don't know whats wrong. Why does it not show the parameter ?error=true?
Info: I am using Spring + JSF + Hibernate + Spring Security
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.usernameParameter("j_username")
.passwordParameter("j_password")
.loginProcessingUrl("/j_spring_security_check")
.failureHandler(customAuthenticationFailureHandler)// .failureUrl("/login.html?error=true")//.successHandler(authSuccsessHandler)
.defaultSuccessUrl("/dashboard.html")
.permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.logoutSuccessUrl("/")
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/access.html")
.and()
.headers()
.defaultsDisabled()
.frameOptions()
.sameOrigin()
.cacheControl();
http
.csrf().disable();
}
This is custom authentication failure handler:
#Component
public class CustomAuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
getRedirectStrategy().sendRedirect(request, response, "/login.html?error=true");
}
}
I will change parameter for some cases.

You didn't allow anonymous access to URL /login.html?error=true, so you are redirected to the login page (/login.html).
AbstractAuthenticationFilterConfigurer#permitAll allows access (for anyone) to failure URL but not for custom failure handler:
Ensures the urls for failureUrl(String) as well as for the HttpSecurityBuilder, the getLoginPage() and getLoginProcessingUrl() are granted access to any user.
You have to allow access explicitly with AbstractRequestMatcherRegistry#antMatchers:
Maps a List of AntPathRequestMatcher instances that do not care which HttpMethod is used.
and ExpressionUrlAuthorizationConfigurer.AuthorizedUrl#permitAll:
Specify that URLs are allowed by anyone.
You don't have to allow the exact URL /login.html?error=true, because AntPathRequestMatcher ignores the query string:
Matcher which compares a pre-defined ant-style pattern against the URL ( servletPath + pathInfo) of an HttpServletRequest. The query string of the URL is ignored and matching is case-insensitive or case-sensitive depending on the arguments passed into the constructor.
Your modified configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login.html").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.usernameParameter("j_username")
.passwordParameter("j_password")
.loginProcessingUrl("/j_spring_security_check")
.failureHandler(customAuthenticationFailureHandler)// .failureUrl("/login.html?error=true")//.successHandler(authSuccsessHandler)
.defaultSuccessUrl("/dashboard.html")
.permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.logoutSuccessUrl("/")
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/access.html")
.and()
.headers()
.defaultsDisabled()
.frameOptions()
.sameOrigin()
.cacheControl();
http
.csrf().disable();
}

In the case of OAuth token failure, I am getting below response, which is inconsistent with app response style.
{
"error": "invalid_token",
"error_description": "Invalid access token: 4cbc6f1c-4d47-44bd-89bc-92a8c86d88dbsdfsdfs"
}
I just wanted to use common response object for the consistency.
Following approach worked for me.
Build your resource server with your custom entry-point object
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.authenticationEntryPoint(new CustomOAuth2AuthenticationEntryPoint());
}
and here is your custom entry point
public class CustomOAuth2AuthenticationEntryPoint extends OAuth2AuthenticationEntryPoint{
public CustomOAuth2AuthenticationEntryPoint() {
super.setExceptionTranslator(new CustomOAuth2WebResponseExceptionTranslator());
}
}
here is your custom WebResponseExceptionTranslator, In my case I have just used a replica of DefaultWebResponseExceptionTranslator and rewritten handleOAuth2Exception method.
CustomOAuth2WebResponseExceptionTranslator implements WebResponseExceptionTranslator<Response> {
....
.....
private ResponseEntity<Response> handleOAuth2Exception(OAuth2Exception e) throws IOException {
int status = e.getHttpErrorCode();
HttpHeaders headers = new HttpHeaders();
headers.set("Cache-Control", "no-store");
headers.set("Pragma", "no-cache");
if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
}
ResponseEntity<Response> response =new ResponseEntity<>(new Response().message(e.getMessage()).status(StatusEnum.ERROR)
.errorType(e.getClass().getName()), HttpStatus.UNAUTHORIZED);
return response;
}
Result looks like
{
"status": "error",
"message": "Invalid access token: 4cbc6f1c-4d47-44bd-89bc-92a8c86d88dbsdfsdfs",
"error_type": "org.springframework.security.oauth2.common.exceptions.InvalidTokenException"
}

Related

Gettig error while trying to access unsecured route

I am using spring security in my java project to secure web services.
All my web services are secured here are filter chain configuiration that i use:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilter(new JwtEmailAndPasswordAuthenticationFilter(authenticationManager(), jwtConfig, secretKey))
.addFilterAfter(new JwtTokenVerifier(secretKey, jwtConfig),JwtEmailAndPasswordAuthenticationFilter.class)
.authorizeRequests()
.anyRequest()
.authenticated();
}
Now I have a requirement to create one web service that will be accessible to everybody.
For this purpose I add this row:
.and().authorizeRequests().antMatchers("/auth/reset").permitAll()
To chained filers and it looks like that:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilter(new JwtEmailAndPasswordAuthenticationFilter(authenticationManager(), jwtConfig, secretKey))
.addFilterAfter(new JwtTokenVerifier(secretKey, jwtConfig),JwtEmailAndPasswordAuthenticationFilter.class)
.authorizeRequests()
.and().authorizeRequests().antMatchers("/auth/reset").permitAll()
.anyRequest()
.authenticated();
}
After adding the row above I get exception JWT not found, it comes from this JwtTokenVerifier bean which is fired by
addFilterAfter.
My question is how can I prevent trigger addFilterAfter or any other filter that is needed only for the secured routes in case of the request for an unsecured web service?
UPDATE
Here is definition of JwtTokenVerifier bean:
public class JwtTokenVerifier extends OncePerRequestFilter {
private final SecretKey secretKey;
private final JwtConfig jwtConfig;
public JwtTokenVerifier(SecretKey secretKey,
JwtConfig jwtConfig) {
this.secretKey = secretKey;
this.jwtConfig = jwtConfig;
}
#Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
try {
String authorizationHeader = request.getHeader(jwtConfig.getAuthorizationHeader());
if (Strings.isNullOrEmpty(authorizationHeader) || !authorizationHeader.startsWith(jwtConfig.getTokenPrefix())) {
filterChain.doFilter(request, response);
return;
}
String token = authorizationHeader.replace(jwtConfig.getTokenPrefix(), "");
try {
Jws<Claims> claimsJws = Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token);
Claims body = claimsJws.getBody();
String email = body.getSubject();
var authorities = (List<Map<String, String>>) body.get("authorities");
Set<SimpleGrantedAuthority> simpleGrantedAuthorities = authorities.stream()
.map(m -> new SimpleGrantedAuthority(m.get("authority")))
.collect(Collectors.toSet());
Authentication authentication = new UsernamePasswordAuthenticationToken(
email,
null,
simpleGrantedAuthorities
);
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (JwtException e) {
throw new IllegalStateException(String.format("Token %s cannot be trusted", token));
}
filterChain.doFilter(request, response);
} catch (JwtException e) {
throw e;
}
}
}
I realize you didn't ask this, but I'd first recommend that you use Spring Security's built-in JWT support instead of building your own. Security is hard, and using vetted support is likely more secure.
Regarding your question about having separate auth mechanisms for separate endpoints, you can instead publish two filter chains, one for open endpoints and one for token-based endpoints like so:
#Bean
#Order(0)
SecurityFilterChain open(HttpSecurity http) {
http
.requestMatchers((requests) -> requests.antMatchers("/auth/reset"))
.authorizeHttpRequests((authorize) -> authorize.anyRequest().permitAll());
return http.build();
}
#Bean
SecurityFilterChain tokenBased(HttpSecurity http) {
http
.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated())
.addFilter(...)
.addFilterAfter(...);
return http.build();
}
Have you tried something like that :
.and()
.authorizeRequests()
.antMatchers("...").permitAll()
.and()
.addFilter(...)
.authorizeRequests()
.anyRequest()
.authenticated()
.and()

Spring security: Cannot permit access to resource when adding custom filter

I have following configuration for my spring security
http
// if I gonna comment adding filter it's gonna work as expected
.addFilterBefore(tokenAuthenticationFilter, BasicAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/rest/_health")
.permitAll()
.anyRequest()
.authenticated()
.and()
.csrf()
.disable();
So without custom filter everything works as expected - I have access to /rest/_health and access denied to everything else.
But when I'm adding this filter - matchers don't work and filter works even for 'permitAll' resources.
Code from my filter looks like this:
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
try {
String token = httpRequest.getHeader(HttpHeaders.AUTHORIZATION);
Authentication authentication = authenticationManager.authenticate(
new TokenBasedAuthentication(token)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
} catch (AuthenticationException ex) {
authenticationEntryPoint.commence(httpRequest, httpResponse, ex);
}
}
Any suggestions?
The filter is executed before the checks on the endpoints. In your case the unsuccesful authentication aborts the filter chain and let the access point handle the rest. Whith this you do not allow anonymous access at all. You need to set the Authentication to null to indicate that an anonymous user is accessing the endpoint.
Try the following:
Authentication authentication = null;
String token = httpRequest.getHeader(HttpHeaders.AUTHORIZATION);
//check if not anonymous and preceed with authentication
if (token != null && !token.isEmpty()) {
try {
authentication = authenticationManager.authenticate(
new TokenBasedAuthentication(token));
} catch (AuthenticationException ex) {
//illigal access atempt
authenticationEntryPoint.commence(httpRequest, httpResponse, ex);
}
}
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
In my configuration (that extends WebSecurityConfigurerAdapter), I did it in this way:
http.csrf().disable().
addFilterBefore(authenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/login*", "/logout*").permitAll().anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/secured/index")
.failureUrl("/login?error=true").permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.deleteCookies("JSESSIONID")
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.permitAll();
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/static/**", "/webjars/**", "/error*");
}
Maybe not perfect, but it works.

Spring Security - Custom handler for Authentication Failed: Bad credentials

I have implemented these custom handler in my spring security app
AuthenticationSuccessHandler (SimpleUrlAuthenticationSuccessHandler)
AuthenticationFailureHandler (SimpleUrlAuthenticationFailureHandler)
AuthenticationEntryPoint
so I can get JSON response as per my requirement.
In case of successful login I am getting valid JSON response as it is going through my custom AuthenticationSuccessHandler but in case of invalid credential it is giving me a HTTP Status 401 - Authentication Failed: Bad credentials along with it's default HTML error page.
I want a JSON error response for this instead of default HTML page.
Is there any other handler which I need to implement? If it there then how to configure it in config method?
Here is my Spring Security config method:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/list").access("hasRole('USER') or hasRole('ADMIN') or hasRole('DBA')")
.antMatchers("/delete-user-*").access("hasRole('ADMIN')")
.antMatchers("/edit-user-*").access("hasRole('ADMIN') or hasRole('DBA')")
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.formLogin()
.loginProcessingUrl("/login")
.usernameParameter("ssoId")
.passwordParameter("password")
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler)
.and()
.rememberMe()
.rememberMeParameter("remember-me")
.tokenRepository(tokenRepository)
.tokenValiditySeconds(86400)
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.accessDeniedHandler(accessDeniedHandler);
}
Here is my CustomAuthenticationFailureHandler
#Component
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
response.setStatus(HttpStatus.BAD_REQUEST.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
JSONObject jsonResponse = new JSONObject();
jsonResponse.put("error", true);
jsonResponse.put("message", "Invalid credentials");
response.getWriter().append(jsonResponse.toString());
super.onAuthenticationFailure(request, response, exception);
}
}
I have tried multiple things but nothing is working for me till now.

How to get loggedin user id after user logs out in spring security?

I have created a following LogoutSuccessHandlerImpl
public class LogoutSuccessHandlerImpl extends SimpleUrlLogoutSuccessHandler {
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
final Long currentUserRoleId = SecurityUtils.getCurrentUserRoleId();
request.getSession().invalidate();
SecurityContextHolder.clearContext();
request.setAttribute("isLoggedOut", "true");
if(currentUserRoleId == UserRole.ADMIN.getId()){
redirectStrategy.sendRedirect(request, response, Constants.ADMIN_LOGIN_URL);
} else {
redirectStrategy.sendRedirect(request, response, Constants.APPLICANT_LOGIN_URL);
}
}
}
and below is my security config.
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.accessDeniedPage("/accessDenied")
.and()
.authorizeRequests()
.accessDecisionManager(accessDecisionManager)
.antMatchers("/").permitAll()
.antMatchers("/application/register**").permitAll()
.antMatchers("/adminLogin**").permitAll()
.antMatchers("/error**").permitAll()
.antMatchers("/checkLogin**").permitAll()
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
.loginPage("/")
.loginProcessingUrl("/checkLogin")
.defaultSuccessUrl("/dashboard")
.failureHandler(new LoginFailureHandlerImpl())
.usernameParameter("username")
.passwordParameter("password")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(new LogoutSuccessHandlerImpl())
.deleteCookies("JSESSIONID")
.permitAll()
.and()
.headers()
.frameOptions()
.disable()
.and()
.sessionManagement()
.maximumSessions(1);
}
Below is my SecurityUtils.
public static SecurityUser getCurrentUser() {
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
if (authentication != null) {
if (authentication.getPrincipal() instanceof SecurityUser) {
return (SecurityUser) authentication.getPrincipal();
}
}
throw new IllegalStateException("User not found!");
}
public static Long getCurrentUserRoleId() {
return SecurityUtils.getCurrentUser().getRoleId();
}
and the error i get is
java.lang.IllegalStateException: User not found!
at com.portal.core.user.security.SecurityUtils.getCurrentUser(SecurityUtils.java:34)
at com.portal.core.user.security.SecurityUtils.getCurrentUserRoleId(SecurityUtils.java:38)
at com.portal.core.user.security.LogoutSuccessHandlerImpl.onLogoutSuccess(LogoutSuccessHandlerImpl.java:22)
authentication is always null, because LogoutSuccessHandler is called after a successful logout, see LogoutSuccessHandler:
Strategy that is called after a successful logout by the LogoutFilter, to handle redirection or forwarding to the appropriate destination.
You could implement a custom LogoutHandler to get user's role id before a successful logout, see LogoutHandler#logout:
Parameters:
request - the HTTP request
response - the HTTP response
authentication - the current principal details
LogoutSuccessHandler will be called after all the LogoutHandlers are finished executing. This means by the Your code in LogoutSuccessHandlerImpl.onLogoutSuccess is called when there will be nothing in SecurityContextHolder. This is because a SecurityContextLogoutHandler will be registered by default. The following line in your LogoutSuccessHandlerImpl has no effect as it is already done by SecurityContextLogoutHandler.
SecurityContextHolder.clearContext();
You can do the following.
Store the User Id and Role Id in the Http Session
Configure your logout to have logout().invalidateHttpSession(false)
Modify your LogoutSuccessHandlerImpl.onLogoutSuccess to get the User Id and Role Id from HttpSession instead of SecurityContextHolder

Spring Boot Security Anonymous authorization

For multiple purposes I need to use
SecurityContextHolder.getContext().getAuthentication()
methods in my controllers/services.
I did migrate my app to Spring Boot 1.4.1 from XML configured Spring MVC app (now only Java configs), similar approach worked before.
I have a problem calling SecurityContextHolder.getContext().getAuthentication(), for example in this controller:
#RestController
#Secured("IS_AUTHENTICATED_ANONYMOUSLY")
#RequestMapping("utils")
public class UtilsController {
#RequestMapping(value = "/check_auth", method = RequestMethod.GET)
public Boolean getAuthState() throws SQLException {
if (SecurityContextHolder.getContext().getAuthentication() == null){
logger.info("Auth obj null");
}
if (SecurityContextHolder.getContext().getAuthentication().getName() != null && SecurityContextHolder.getContext().getAuthentication().getName() != "anonymousUser") {
return true;
} else return false;
}
}
it always returns null. Can't figure out why anonymous authentication is not working.
Here is the Spring Security configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and()
.formLogin()
.successHandler(ajaxSuccessHandler)
.failureHandler(ajaxFailureHandler)
.loginProcessingUrl("/authentication")
.passwordParameter("password")
.usernameParameter("username")
.and()
.logout()
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.and()
.csrf().disable()
// .anonymous().disable()
.authorizeRequests()
// .anyRequest().anonymous()
.antMatchers("/utils").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/admin/*").access("hasRole('ROLE_ADMIN')")
.antMatchers("/user/*").access("hasRole('ROLE_USER')");
}
I did tried with and without #Secured annotation on the controller.
.authorizeRequests()
// .anyRequest().anonymous()
.antMatchers("/utils").permitAll()
different variations with this settings.
You are getting null with:
SecurityContextHolder.getContext().getAuthentication()
because you are not authenticating within you security configuration.
You can add a simple:
.authenticated()
.and()
// ...
.formLogin();
in case you're using form login.
Now after you'll authenticate each request you suppose to get something other than null.
Here's an example from Spring Security docs:
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/signup", "/about").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated()
.and()
// ...
.formLogin();
}

Categories