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.
Related
I am having a hard time configuring my spring security. The problem is, my authentication filter always skips my success and failure handlers whenever I authenticate via a custom UsernamePasswordAuthenticationFilter. I don't seem to know why this happens.
First off, I pass the authentication parameter as JSON, and filter out the username and password, then I pass those two parameters into a new UsernamePasswordAuthenticationToken(username, password) then I get the authentication manager and authenticate the returned token. At the point of success full authentication I expect that the success handler should take over but no it doesn't get called at all.
This is my security configuration.
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.and()
.exceptionHandling()
.authenticationEntryPoint(restAuthenticationEntryPoint)
.and()
.authorizeRequests()
.antMatchers("/signup")
.permitAll()
.antMatchers("/", "/security/login", "/request", "/request.html")
.authenticated()
.and()
.formLogin()
.loginProcessingUrl("/security/login")
.successHandler(authenticationSuccessHandler())
.failureHandler(authenticationFailureHandler())
.and()
.logout()
.logoutUrl("/logout")
.permitAll()
.and()
.addFilterAfter
(authenticationFilter(), UsernamePasswordAuthenticationFilter.class)
//.and()
.userDetailsService(userDetailsServiceBean());
}
The relevant beans are
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsServiceBean());
}
#Bean
#Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return new JdbcUserDetails();
}
#Bean
public RestAuthenticationSuccessHandler authenticationSuccessHandler(){
return new RestAuthenticationSuccessHandler();
}
#Bean
public RestAuthenticationFailureHandler authenticationFailureHandler(){
return new RestAuthenticationFailureHandler();
}
#Bean
JsonAuthenticationFilter authenticationFilter() throws Exception {
logger.debug("Authenication filter processing loggin request ");
JsonAuthenticationFilter filter = new JsonAuthenticationFilter();
filter.setAuthenticationManager(authenticationManagerBean());
return filter;
}
The filter is
public class JsonAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
UsernamePasswordAuthenticationToken authRequest = this.getUserNamePasswordAuthenticationToken(request);
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
and finally my success handler
class RestAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication)
throws ServletException, IOException {
logger.debug("Successful login");
System.out.println("\n\n\n\n\n\n\n\nresponse here\n\n\n\n\n\n\n");
response.getWriter().write("{This is a login success response}");
response.getWriter().flush();
response.getWriter().close();
}
I have been battling for too long
Spring Security will back off on a given bean configuration when you supply that bean.
So, because you supplied your filter (JsonAuthenticationFilter), Spring Security expects that you'll know best how to compose it.
So, then, you'd instead do:
#Bean
JsonAuthenticationFilter authenticationFilter() {
JsonAuthenticationFilter filter = new JsonAuthenticationFilter();
// .. other configs
filter.setAuthenticationSuccessHandler(new RestAuthenticationSuccessHandler());
filter.setAuthenticationFailureHandler(new RestAuthenticationFailureHandler());
}
It looks like there is a lot going on, so if that doesn't solve your issue, feel free to put together a sample, say on GitHub, and I'd be happy to look it over.
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.
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"
}
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
I am just beginner in Spring Security Oauth2.
I have Authorization Server and Resource Server (separated).
The flow that I used is Authorization Code. And I have success to login tho the Authorization Server, get the code, and then get the accessToken.
Then, I have a problem when I want to logout. When I deploy the Authorization Server in Apache Tomcat, it can call 'j_spring_security_logout' but when I deploy in Glashfish, it cant.
Here my security config:
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(false);
http.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll().and()
.authorizeRequests()
.antMatchers("/login.jsp").permitAll()
.and()
.formLogin()
.loginPage("/login.jsp")
.loginProcessingUrl("/j_spring_security_check")
.usernameParameter("j_username")
.passwordParameter("j_password")
.and()
.logout()
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
.logoutUrl("/j_spring_security_logout")
.logoutSuccessHandler(logoutHandler);
}
Here my logouthandler:
public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse res, Authentication a) throws IOException, ServletException {
String token=req.getParameter("token");
if(token != null){
consumerTokenServices.revokeToken(token);
}
String redirect = req.getParameter("redirect");
if(redirect != null){
res.sendRedirect(redirect);
}
}