spring security redirect based on role - spring

i have the following spring-security.xml file :-
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<http auto-config="true">
<intercept-url pattern="/Freelancer/**" access="ROLE_FREELANCE" />
<intercept-url pattern="/Client/**" access="ROLE_CLIENT" />
<intercept-url pattern="/Agency/**" access="ROLE_AGENCY" />
<intercept-url pattern="/Manager/**" access="ROLE_MANAGER" />
<intercept-url pattern="/User/**" access="ROLE_USER" />
<form-login default-target-url="/${role}" login-page="/login.jsp" />
<logout logout-url="/logout" logout-success-url="/" />
</http>
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select user_name,password, enabled from Users where user_name=?"
authorities-by-username-query="select u.user_name, u.role from Users u where u.user_name =?"/>
</authentication-provider>
</authentication-manager>
</beans:beans>
what i want, i want to redirect the user to their workspace, for example if Client login then he will be redirected to the /Client/index.jsp, if Agency login, they will be redirected to the /Agency/index.jsp.
is there any way to access the role before, he will be redirected to their workspace in spring-security.xml file.
<form-login default-target-url="/${role}" login-page="/login.jsp" />
I have the directory structure similer to role.
have any idea.

Write a spring controller which will serve different pages to be shown based on user role. Write Authentication success handler class and write code to decide where to redirect based on roles.
First of all <form-login /> tag need to be changed.
<form-login login-page="/landing" authentication-success-handler-ref="authSuccessHandler" />
<beans:bean id="authSuccessHandler" class="com.package.AuthSuccessHandler" />
Remove default-target-url attribute. Let auth handler decide where to redirect the user.
Auth success handler class will be like :
public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
#Override
protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
// Get the role of logged in user
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String role = auth.getAuthorities().toString();
String targetUrl = "";
if(role.contains("client")) {
targetUrl = "/client/index";
} else if(role.contains("agency")) {
targetUrl = "/agency/index";
}
return targetUrl;
}
}
This is a sample code. Change it as per your requirements.

You can use annotation based solution by using custom success handler like this:
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
#Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Override
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
System.out.println("Can't redirect");
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
/*
* This method extracts the roles of currently logged-in user and returns
* appropriate URL according to his/her role.
*/
protected String determineTargetUrl(Authentication authentication) {
String url = "";
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
List<String> roles = new ArrayList<String>();
for (GrantedAuthority a : authorities) {
roles.add(a.getAuthority());
}
if (isDba(roles)) {
url = "/db";
} else if (isAdmin(roles)) {
url = "/admin";
} else if (isUser(roles)) {
url = "/home";
} else {
url = "/accessDenied";
}
return url;
}
private boolean isUser(List<String> roles) {
if (roles.contains("ROLE_USER")) {
return true;
}
return false;
}
private boolean isAdmin(List<String> roles) {
if (roles.contains("ROLE_ADMIN")) {
return true;
}
return false;
}
private boolean isDba(List<String> roles) {
if (roles.contains("ROLE_DBA")) {
return true;
}
return false;
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}
And security config as:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
CustomSuccessHandler customSuccessHandler;
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("USER");
auth.inMemoryAuthentication().withUser("admin").password("root123").roles("ADMIN");
auth.inMemoryAuthentication().withUser("dba").password("root123").roles("ADMIN","DBA");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").access("hasRole('USER')")
.antMatchers("/admin/**").access("hasRole('ADMIN')")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.and().formLogin().loginPage("/login").successHandler(customSuccessHandler)
.usernameParameter("ssoId").passwordParameter("password")
.and().csrf()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
}

It is better to check roles with equals in granted authority, contains may fail if multiple role exist with a same part.
Add authentication success handler in form login config like below:
<http auto-config="true">
<intercept-url pattern="/Freelancer/**" access="ROLE_FREELANCE" />
<intercept-url pattern="/Client/**" access="ROLE_CLIENT" />
<intercept-url pattern="/Agency/**" access="ROLE_AGENCY" />
<intercept-url pattern="/Manager/**" access="ROLE_MANAGER" />
<intercept-url pattern="/User/**" access="ROLE_USER" />
<form-login login-page='/login.html'
authentication-failure-url="/login.html?error=true"
authentication-success-handler-ref="myAuthenticationSuccessHandler"/>
<logout logout-url="/logout" logout-success-url="/" />
</http>
And the success handler goes like this:
public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
protected Log logger = LogFactory.getLog(this.getClass());
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
handle(request, response, authentication);
clearAuthenticationAttributes(request);
}
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
logger.debug(
"Response has already been committed. Unable to redirect to "
+ targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(Authentication authentication) {
boolean isUser = false;
boolean isFreelance = false;
boolean isClient = false;
boolean isAgency = false;
boolean isManager = false;
Collection<? extends GrantedAuthority> authorities
= authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_FREELANCE")) {
isFreelance = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_CLIENT")) {
isClient = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_AGENCY")) {
isAgency = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_MANAGER")) {
isManager = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
isUser = true;
break;
}
}
if (isFreelance) {
return "freelance/homepage.html";
} else if (isClient) {
return "client/homepage.html";
} else if (isAgency) {
return "agency/homepage.html";
} else if (isManager) {
return "manager/homepage.html";
} else if (isUser) {
return "user/homepage.html";
} else {
throw new IllegalStateException();
}
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}

Related

Not getting login failure reason (only BadCredential Exception is popped)

Tried various ways to get custom message from spring, if user authentication fails.
Using
<spring.version>4.2.4.RELEASE</spring.version>
<spring.security.version>4.0.3.RELEASE</spring.security.version>
XML configuration
<http auto-config="true" use-expressions="false">
<intercept-url pattern="/**" access='ROLE_FUNCTION' />
<form-login login-page="/login"
default-target-url="/welcome"
username-parameter="j_username"
password-parameter="j_password"
login-processing-url="/j_spring_security_check"
always-use-default-target="true"
authentication-success-handler-ref="authenticationSuccessHandler"
authentication-failure-handler-ref="authenticationFailureHandler"
/>
<logout logout-url="/j_spring_security_logout" logout-success-url="/login?logout" delete-cookies="JSESSIONID" />
<access-denied-handler error-page="/accessDenied" />
<csrf disabled="true"/>
</http>
<authentication-manager>
<authentication-provider user-service-ref="**userDetailsService**">
<password-encoder ref="bcryptEncoder"/>
</authentication-provider>
</authentication-manager>
<beans:bean id="authenticationSuccessHandler" class="com.company.project.CustomAuthenticationSuccessHandler"/>
<beans:bean id="**authenticationFailureHandler**" class="com.company.project.CustomAuthenticationFailureHandler"/>
<beans:bean name="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
Bean definition excerpt is as below
Implementation
userDetailsService
#Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
logger.info("Getting access details for user : {}", username);
UserDto userDto = null;
boolean accountNonExpired = true;
boolean accountNonLocked = true;
boolean credentialsNonExpired = true;
boolean enabled = true;
try {
userDto = userService.loginUser(username);
if (userDto == null) {
throw new UsernameNotFoundException("User not found");
}
if (Active.Y != userDto.getActive()) {
enabled = false;
throw new BadCredentialsException("User account is inactive");
}
} catch (BaseException be) {
throw new BadCredentialsException(be.getMessage().toLowerCase());
}
UserContext context = new UserContext();
context.setLoginId(username);
context.setName(userDto.getName());
context.setPrincipleId(userDto.getId());
List<GrantedAuthority> grantedAuthorities = getGrantedAuthorities(userDto);
String password = getActivePassword(userDto);
accountNonExpired = isAccountActive(userDto);
accountNonLocked = isAccountUnlocked(userDto);
credentialsNonExpired = isCredentialsActive(userDto);
return new UserLoginDetails(grantedAuthorities, password, username, accountNonExpired, accountNonLocked, credentialsNonExpired, enabled, context);
}
}
authenticationSuccessHandler works fine.
authenticationFailureHandler
#Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Autowired
UserService userService;
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
try {
// execute it when user enters wrong password, i.e loginAttempt ...
} catch (Exception e) {
// TODO: something
}
// TODO: how do I send message, if authenticationException.
redirectStrategy.sendRedirect(request, response, "/login?error");
// clearAuthenticationAttributes(request);
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
}
To show error message I'm using following line
JSP
<c:set var="errorMessage" value="${sessionScope[\"SPRING_SECURITY_LAST_EXCEPTION\"].message}" />
Let me brief the expected messages.
If user enters wrong credentials he should get
"Invalid credentials"
If user account is inactive he should get
"Your account is not active"
If user exceeded permissible no. of
attempt his account will get locked and he will get "Your account is
locked"
If my implementation is not correct please let me know what changes should be done.
If you want to override the AuthenticationFailureHandler, you can extend the SimpleUrlAuthenticationFailureHandler, it already has a method to save exception.
protected final void saveException(HttpServletRequest request, AuthenticationException exception) {
if (forwardToDestination) {
request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
} else {
HttpSession session = request.getSession(false);
if (session != null || allowSessionCreation) {
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
}
}
}
When you save the exception to request or session, then you can get the message.
${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}

Spring JAAS Authentication with database authorization

I am using Spring security 4.0. My login module is configured in Application server so I have to do authentication using JAAS but my user details are stored in database, so once authenticated user object will be created by querying database. Could you please let me know how to achieve this i.e. LDAP authentication and load user details from database. Also how cache the user object using eh-cache, so that the user object can be accessed in the service / dao layer.
This can be achieved using CustomAuthentication Provider. Below are the codes.
import java.util.Arrays;
import java.util.List;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.authentication.jaas.JaasGrantedAuthority;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.sun.security.auth.UserPrincipal;
public class CustomAutenticationProvider extends DaoAuthenticationProvider implements AuthenticationProvider {
private AuthenticationProvider delegate;
public CustomAutenticationProvider(AuthenticationProvider delegate) {
this.delegate = delegate;
}
#Override
public Authentication authenticate(Authentication authentication) {
Authentication a = delegate.authenticate(authentication);
if(a.isAuthenticated()){
a = super.authenticate(a);
}else{
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad credentials"));
}
return a;
}
private List<GrantedAuthority> loadRolesFromDatabaseHere(String name) {
GrantedAuthority grantedAuthority =new JaasGrantedAuthority(name, new UserPrincipal(name));
return Arrays.asList(grantedAuthority);
}
#Override
public boolean supports(Class<?> authentication) {
return delegate.supports(authentication);
}
/* (non-Javadoc)
* #see org.springframework.security.authentication.dao.DaoAuthenticationProvider#additionalAuthenticationChecks(org.springframework.security.core.userdetails.UserDetails, org.springframework.security.authentication.UsernamePasswordAuthenticationToken)
*/
#Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
if(!authentication.isAuthenticated())
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad credentials"));
}
}
UserDetails required for DAOAuthentication
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import com.testjaas.model.User;
import com.testjaas.model.UserRepositoryUserDetails;
#Component
public class AuthUserDetailsService implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("loadUserByUsername called !!");
com.testjaas.model.User user = new User();
user.setName(username);
user.setUserRole("ROLE_ADMINISTRATOR");
if(null == user) {
throw new UsernameNotFoundException("User " + username + " not found.");
}
return new UserRepositoryUserDetails(user);
}
}
RoleGrantor - This will be a dummy class required for Spring JAAS authentication
import java.security.Principal;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.security.authentication.jaas.AuthorityGranter;
public class RoleGranterFromMap implements AuthorityGranter {
private static Map<String, String> USER_ROLES = new HashMap<String, String>();
static {
USER_ROLES.put("test", "ROLE_ADMINISTRATOR");
//USER_ROLES.put("test", "TRUE");
}
public Set<String> grant(Principal principal) {
return Collections.singleton("DUMMY");
}
}
SampleLogin - This should be replaced with your login module
import java.io.Serializable;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
public class SampleLoginModule implements LoginModule {
private Subject subject;
private String password;
private String username;
private static Map<String, String> USER_PASSWORDS = new HashMap<String, String>();
static {
USER_PASSWORDS.put("test", "test");
}
public boolean abort() throws LoginException {
return true;
}
public boolean commit() throws LoginException {
return true;
}
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map<String, ?> sharedState, Map<String, ?> options) {
this.subject = subject;
try {
NameCallback nameCallback = new NameCallback("prompt");
PasswordCallback passwordCallback = new PasswordCallback("prompt",false);
callbackHandler.handle(new Callback[] { nameCallback,passwordCallback });
this.password = new String(passwordCallback.getPassword());
this.username = nameCallback.getName();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public boolean login() throws LoginException {
if (USER_PASSWORDS.get(username) == null
|| !USER_PASSWORDS.get(username).equals(password)) {
throw new LoginException("username is not equal to password");
}
subject.getPrincipals().add(new CustomPrincipal(username));
return true;
}
public boolean logout() throws LoginException {
return true;
}
private static class CustomPrincipal implements Principal, Serializable {
private final String username;
public CustomPrincipal(String username) {
this.username = username;
}
public String getName() {
return username;
}
}
}
Spring XML configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<security:http auto-config="true">
<security:intercept-url pattern="/*" access="isAuthenticated()"/>
</security:http>
<!-- <security:authentication-manager>
<security:authentication-provider ref="jaasAuthProvider" />
</security:authentication-manager> -->
<bean id="userDetailsService" class="com.testjaas.service.AuthUserDetailsService"></bean>
<bean id="testService" class="com.testjaas.service.TestService"/>
<bean id="applicationContextProvider" class="com.testjaas.util.ApplicationContextProvider"></bean>
<security:authentication-manager>
<security:authentication-provider ref="customauthProvider"/>
</security:authentication-manager>
<bean id="customauthProvider" class="com.testjaas.security.CustomAutenticationProvider">
<constructor-arg name="delegate" ref="jaasAuthProvider" />
<property name="userDetailsService" ref="userDetailsService" />
</bean>
<bean id="jaasAuthProvider" class="org.springframework.security.authentication.jaas.JaasAuthenticationProvider">
<property name="loginConfig" value="classpath:pss_jaas.config" />
<property name="authorityGranters">
<list>
<bean class="com.testjaas.security.RoleGranterFromMap" />
</list>
</property>
<property name="loginContextName" value="JASSAuth" />
<property name="callbackHandlers">
<list>
<bean class="org.springframework.security.authentication.jaas.JaasNameCallbackHandler" />
<bean class="org.springframework.security.authentication.jaas.JaasPasswordCallbackHandler" />
</list>
</property>
</bean>
</beans>
Sample jaas config
JASSAuth {
com.testjaas.security.SampleLoginModule required;
};

authentication-provider is not called

Here is my security-context.xml file:
<http auto-config='false' authentication-manager-ref="authenticationManager" entry-point-ref="authenticationEntryPoint">
<intercept-url pattern="/"/>
<intercept-url pattern="/**"/>
<csrf disabled="true"/>
<custom-filter position="REMEMBER_ME_FILTER" ref="DashboardFilter"></custom-filter>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider ref="DashboardAuthProvider"></authentication-provider>
</authentication-manager>
<beans:bean id="DashboardFilter" class="com.apple.store.dashboard.security.DashboardAuthFilter">
<beans:property name="authenticationManager" ref="authenticationManager"/>
</beans:bean>
<beans:bean id="authenticationEntryPoint" class="com.apple.store.dashboard.security.DashboardAuthEntryPoint">
</beans:bean>
<beans:bean id="DashboardAuthProvider" class="com.apple.store.dashboard.security.DashboardAuthProvider">
I have defined DashboardAuthProvider as such:
public class DashboardAuthProvider implements AuthenticationProvider {
private static final Logger logger = LoggerFactory.getLogger(DashboardAuthProvider.class);
#Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
logger.debug("Inside DashboardAuthProvider: authenticate method +authentication=" + authentication);
Authentication auth = null;
[...]
}
}
When I executed the code, I can hit the filter, but not provider. I read many spring security related document and couldn't find anything wrong with my configuration in xml. Could someone help?
Here is my filter:
public class DashboardAuthFilter extends AbstractAuthenticationProcessingFilter {
private static final Logger logger = LoggerFactory.getLogger(DashboardAuthFilter.class);
public DashboardAuthFilter() {
super("/**");
}
public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response)
throws org.springframework.security.core.AuthenticationException {
logger.debug("Inside DashboardAuthFilter:attemptAuthentication method:");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth!=null ){
if (auth.isAuthenticated()){
logger.debug("Previously authenticated.isAuthenticated=true::: Auth details:" +auth);
return auth;
}
}
//Validate the DS Auth Cookie
Cookie AOSCookie = WebUtils.getCookie(request, "myacinfo-uat");//
if ( AOSCookie == null )
return null;
Authentication authResult = null;
try {
if( org.apache.commons.lang.StringUtils.isEmpty(AOSCookie.toString())) {
throw new PreAuthenticatedCredentialsNotFoundException("DS Auth Cookie not found. Commence DS Authentication..");
}
String credentials = "NA";
String validateCookieDetails = correctAuthentication(AOSCookie, request);
logger.debug("validateCookieDetails ....." + validateCookieDetails);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(validateCookieDetails, credentials);
authResult = getAuthenticationManager().authenticate(authRequest);
logger.debug("Attempted authentication: authResult ::" + authResult.toString());
} catch (org.springframework.security.core.AuthenticationException e) {
logger.error("AttemptAuthentication: Not Authenticated : AuthenticationException ....." + e.getMessage());
} catch (Exception e) {
logger.error("Exception occured during authentication....." + e.getMessage());
}
return authResult;
}
}

Profile with spring-security doesn´t work

I´m using spring-security to validate at users in function its profiles, but my app doesn´t make it well, when I see the file log, it show me this:
DEBUG DaoAuthenticationProvider:308 - User account is locked
In my form login I put the data well, but I never pass to other page, I´m always in the same page (form page), I introduce good or bad data
My code is:
file configuration spring-security.xml
<beans:beans xmlns:security="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<security:http auto-config="true" access-decision-manager-ref="accessDecisionManager">
<security:intercept-url pattern="/" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/init" access="PROFILE_ADMINISTRATOR" />
<security:form-login
login-page="/"
default-target-url="/init"
always-use-default-target='true'
authentication-failure-url="/"/>
<security:http-basic />
</security:http>
<security:authentication-manager alias="autenticationManagerUserService">
<security:authentication-provider user-service-ref="userService">
<security:password-encoder hash="md5"/>
</security:authentication-provider>
</security:authentication-manager>
<beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
<beans:property name="decisionVoters">
<beans:list>
<beans:ref bean="decisorDeRoles"/>
<beans:ref bean="decisorDeAutenticacion"/>
</beans:list>
</beans:property>
</beans:bean>
<beans:bean id="decisorDeRoles" class="org.springframework.security.access.vote.RoleVoter">
<beans:property name="rolePrefix" value="PROFILE_"/>
</beans:bean>
<beans:bean id="decisorDeAutenticacion" class="org.springframework.security.access.vote.AuthenticatedVoter"/>
<beans:bean id="loggerListener" class="org.springframework.security.authentication.event.LoggerListener"/>
</beans:beans>
class of UserDatailsService
#Service("userService")
public class SecurityAuthenticationProvider implements UserDetailsService
{
UserDao userDao = new UserDao ();
#Override
public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException, DataAccessException
{
User user = null;
List<User> users = userDao.getUser (username);
if (users.size () == 0)
{
throw new UsernameNotFoundException ("");
}
else
{
user = users.get (0);
user.setAuthorities (userDao.getProfileUser (username));
return user;
}
}
}
class UserDatails
public class User implements UserDetails
{
private List<GrantedAuthority> profiles;
private String username;
private String password;
private boolean accountNonExpired;
private boolean accountNonLocked;
private boolean credentialsNonExpired;
private boolean enabled;
#Override
public Collection<? extends GrantedAuthority> getAuthorities ()
{
return profiles;
}
#SuppressWarnings("unchecked")
public void setAuthorities (List<? extends GrantedAuthority> profiles)
{
this.profiles = (List<GrantedAuthority>) profiles;
}
#Override
public String getPassword ()
{
return password;
}
#Override
public String getUsername ()
{
return username;
}
#Override
public boolean isAccountNonExpired ()
{
return accountNonExpired;
}
#Override
public boolean isAccountNonLocked ()
{
return accountNonLocked;
}
#Override
public boolean isCredentialsNonExpired ()
{
return credentialsNonExpired;
}
#Override
public boolean isEnabled ()
{
return enabled;
}
public void setUsername (String username)
{
this.username = username;
}
public void setPassword (String password)
{
this.password = password;
}
public void setAccountNonExpired (boolean accountNonExpired)
{
this.accountNonExpired = accountNonExpired;
}
public void setAccountNonLocked (boolean accountNonLocked)
{
this.accountNonLocked = accountNonLocked;
}
public void setCredentialsNonExpired (boolean credentialsNonExpired)
{
this.credentialsNonExpired = credentialsNonExpired;
}
public void setEnabled (boolean enabled)
{
this.enabled = enabled;
}
}
class GrantedAuthority
public class Profile implements GrantedAuthority
{
private String profile;
#Override
public String getAuthority ()
{
return profile;
}
public String getProfile ()
{
return profile;
}
public void setProfile (String profile)
{
this.profile = profile;
}
}
Class that I have created to simulate access to database (to obtain data)
public class UserDao
{
public List<? extends GrantedAuthority> getProfileUser (String name)
{
List<GrantedAuthority> listGrantedAuthorities = new ArrayList<GrantedAuthority> ();
Profile profile = new Profile ();
profile.setProfile ("PROFILE_ADMINISTRATOR");
listGrantedAuthorities.add (profile);
return listGrantedAuthorities;
}
public List<User> getUser (String name)
{
List<User> listUser = new ArrayList<User> ();
User user = new User ();
user.setUsername ("Admin");
user.setPassword ("1234");
// user.setAccountNonExpired (true);
// user.setAccountNonLocked (true);
// user.setCredentialsNonExpired (true);
// user.setEnabled (true);
listUser.add (user);
return listUser;
}
}
Thanks.
I faced the same issue while working with rest oauth2 spring security.
SOLUTION
you need to make few changes in your class which implements UserDetails (org.springframework.security.core.userdetails), in your case its the user class.
For the following overriding methods isAccountNonLocked(), isAccountNonExpired(), isEnabled(), isCredentialsNonExpired()
change the retrun type to true (by default its false).
make note that these all methods should have a logic to return true or false depending on your requirement but to make your code work i am suggesting you to return true for all the mentioned methods.

Spring Security redirect to previous page after successful login

I know this question has been asked before, however I'm facing a particular issue here.
I use spring security 3.1.3.
I have 3 possible login cases in my web application:
Login via the login page : OK.
Login via a restricted page : OK too.
Login via a non-restricted page : not OK... a "product" page can be accessed by everybody, and a user can post a comment if he's logged. So a login form is contained in the same page in order to allow users to connect.
The problem with case 3) is that I can't manage to redirect users to the "product" page. They get redirected to the home page after a successful login, no matter what.
Notice that with case 2) the redirection to the restricted page works out of the box after successful login.
Here's the relevant part of my security.xml file:
<!-- Authentication policy for the restricted page -->
<http use-expressions="true" auto-config="true" pattern="/restrictedPage/**">
<form-login login-page="/login/restrictedLogin" authentication-failure-handler-ref="authenticationFailureHandler" />
<intercept-url pattern="/**" access="isAuthenticated()" />
</http>
<!-- Authentication policy for every page -->
<http use-expressions="true" auto-config="true">
<form-login login-page="/login" authentication-failure-handler-ref="authenticationFailureHandler" />
<logout logout-url="/logout" logout-success-url="/" />
</http>
I suspect the "authentication policy for every page" to be responsible for the problem. However, if I remove it I can't login anymore... j_spring_security_check sends a 404 error.
EDIT:
Thanks to Ralph, I was able to find a solution. So here's the thing: I used the property
<property name="useReferer" value="true"/>
that Ralph showed me. After that I had a problem with my case 1) : when logging via the login page, the user stayed in the same page (and not redirected to the home page, like it used to be). The code until this stage was the following:
<!-- Authentication policy for login page -->
<http use-expressions="true" auto-config="true" pattern="/login/**">
<form-login login-page="/login" authentication-success-handler-ref="authenticationSuccessHandlerWithoutReferer" />
</http>
<!-- Authentication policy for every page -->
<http use-expressions="true" auto-config="true">
<form-login login-page="/login" authentication-failure-handler-ref="authenticationFailureHandler" />
<logout logout-url="/logout" logout-success-url="/" authentication-success-handler-ref="authenticationSuccessHandler"/>
</http>
<beans:bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<!-- After login, return to the last visited page -->
<beans:property name="useReferer" value="true" />
</beans:bean>
<beans:bean id="authenticationSuccessHandlerWithoutReferer" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<!-- After login, stay to the same page -->
<beans:property name="useReferer" value="false" />
</beans:bean>
This should work, in theory at least, but it wasn't. I still dont know why, so if someone has an answer on this, I will gladly create a new topic to allo him to share his solution.
In the meantime, I came to a workaround. Not the best solution, but like I said, if someone has something better to show, I'm all ears. So this is the new authentication policy for the login page :
<http use-expressions="true" auto-config="true" pattern="/login/**" >
<intercept-url pattern="/**" access="isAnonymous()" />
<access-denied-handler error-page="/"/>
</http>
The solution here is pretty obvious: the login page is allowed only for anonymous users. Once a user is connected, the error handler redirects him to the home page.
I did some tests, and everything seems to be working nicely.
What happens after login (to which url the user is redirected) is handled by the AuthenticationSuccessHandler.
This interface (a concrete class implementing it is SavedRequestAwareAuthenticationSuccessHandler) is invoked by the AbstractAuthenticationProcessingFilter or one of its subclasses like (UsernamePasswordAuthenticationFilter) in the method successfulAuthentication.
So in order to have an other redirect in case 3 you have to subclass SavedRequestAwareAuthenticationSuccessHandler and make it to do what you want.
Sometimes (depending on your exact usecase) it is enough to enable the useReferer flag of AbstractAuthenticationTargetUrlRequestHandler which is invoked by SimpleUrlAuthenticationSuccessHandler (super class of SavedRequestAwareAuthenticationSuccessHandler).
<bean id="authenticationFilter"
class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<property name="filterProcessesUrl" value="/login/j_spring_security_check" />
<property name="authenticationManager" ref="authenticationManager" />
<property name="authenticationSuccessHandler">
<bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="useReferer" value="true"/>
</bean>
</property>
<property name="authenticationFailureHandler">
<bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
<property name="defaultFailureUrl" value="/login?login_error=t" />
</bean>
</property>
</bean>
I want to extend Olcay's nice answer. His approach is good, your login page controller should be like this to put the referrer url into session:
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(HttpServletRequest request, Model model) {
String referrer = request.getHeader("Referer");
request.getSession().setAttribute("url_prior_login", referrer);
// some other stuff
return "login";
}
And you should extend SavedRequestAwareAuthenticationSuccessHandler and override its onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) method. Something like this:
public class MyCustomLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
public MyCustomLoginSuccessHandler(String defaultTargetUrl) {
setDefaultTargetUrl(defaultTargetUrl);
}
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
HttpSession session = request.getSession();
if (session != null) {
String redirectUrl = (String) session.getAttribute("url_prior_login");
if (redirectUrl != null) {
// we do not forget to clean this attribute from session
session.removeAttribute("url_prior_login");
// then we redirect
getRedirectStrategy().sendRedirect(request, response, redirectUrl);
} else {
super.onAuthenticationSuccess(request, response, authentication);
}
} else {
super.onAuthenticationSuccess(request, response, authentication);
}
}
}
Then, in your spring configuration, you should define this custom class as a bean and use it on your security configuration. If you are using annotation config, it should look like this (the class you extend from WebSecurityConfigurerAdapter):
#Bean
public AuthenticationSuccessHandler successHandler() {
return new MyCustomLoginSuccessHandler("/yourdefaultsuccessurl");
}
In configure method:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
// bla bla
.formLogin()
.loginPage("/login")
.usernameParameter("username")
.passwordParameter("password")
.successHandler(successHandler())
.permitAll()
// etc etc
;
}
I have following solution and it worked for me.
Whenever login page is requested, write the referer value to the session:
#RequestMapping(value="/login", method = RequestMethod.GET)
public String login(ModelMap model,HttpServletRequest request) {
String referrer = request.getHeader("Referer");
if(referrer!=null){
request.getSession().setAttribute("url_prior_login", referrer);
}
return "user/login";
}
Then, after successful login custom implementation of SavedRequestAwareAuthenticationSuccessHandler will redirect user to the previous page:
HttpSession session = request.getSession(false);
if (session != null) {
url = (String) request.getSession().getAttribute("url_prior_login");
}
Redirect the user:
if (url != null) {
response.sendRedirect(url);
}
I've custom OAuth2 authorization and request.getHeader("Referer") is not available at poit of decision. But security request already saved in ExceptionTranslationFilter.sendStartAuthentication:
protected void sendStartAuthentication(HttpServletRequest request,...
...
requestCache.saveRequest(request, response);
So, all what we need is share requestCache as Spring bean:
#Bean
public RequestCache requestCache() {
return new HttpSessionRequestCache();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
...
.requestCache().requestCache(requestCache()).and()
...
}
and use it wheen authorization is finished:
#Autowired
private RequestCache requestCache;
public void authenticate(HttpServletRequest req, HttpServletResponse resp){
....
SavedRequest savedRequest = requestCache.getRequest(req, resp);
resp.sendRedirect(savedRequest != null && "GET".equals(savedRequest.getMethod()) ?
savedRequest.getRedirectUrl() : "defaultURL");
}
The following generic solution can be used with regular login, a Spring Social login, or most other Spring Security filters.
In your Spring MVC controller, when loading the product page, save the path to the product page in the session if user has not been logged in. In XML config, set the default target url. For example:
In your Spring MVC controller, the redirect method should read out the path from the session and return redirect:<my_saved_product_path>.
So, after user logs in, they'll be sent to /redirect page, which will promptly redirect them back to the product page that they last visited.
Back to previous page after succesfull login, we can use following custom authentication manager as follows:
<!-- enable use-expressions -->
    <http auto-config="true" use-expressions="true">
        <!-- src** matches: src/bar.c src/baz.c src/test/bartest.c-->
        <intercept-url pattern="/problemSolution/home/**" access="hasRole('ROLE_ADMIN')"/>
        <intercept-url pattern="favicon.ico" access="permitAll"/>
        <form-login
                authentication-success-handler-ref="authenticationSuccessHandler"
                always-use-default-target="true"
                login-processing-url="/checkUser"
                login-page="/problemSolution/index"
                default-target-url="/problemSolution/home"
                authentication-failure-url="/problemSolution/index?error"
                username-parameter="username"
                password-parameter="password"/>
        <logout logout-url="/problemSolution/logout"
                logout-success-url="/problemSolution/index?logout"/>
        <!-- enable csrf protection -->
        <csrf/>
    </http>
    <beans:bean id="authenticationSuccessHandler"
            class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
        <beans:property name="defaultTargetUrl" value="/problemSolution/home"/>
    </beans:bean>
    <!-- Select users and user_roles from database -->
    <authentication-manager>
        <authentication-provider user-service-ref="customUserDetailsService">
            <password-encoder hash="plaintext">
            </password-encoder>
        </authentication-provider>
    </authentication-manager>
CustomUserDetailsService class
#Service
public class CustomUserDetailsService implements UserDetailsService {
     #Autowired
     private UserService userService;
     public UserDetails loadUserByUsername(String userName)
             throws UsernameNotFoundException {
         com.codesenior.telif.local.model.User domainUser = userService.getUser(userName);
         boolean enabled = true;
         boolean accountNonExpired = true;
         boolean credentialsNonExpired = true;
         boolean accountNonLocked = true;
         return new User(
                 domainUser.getUsername(),
                 domainUser.getPassword(),
                 enabled,
                 accountNonExpired,
                 credentialsNonExpired,
                 accountNonLocked,
                 getAuthorities(domainUser.getUserRoleList())
         );
     }
     public Collection<? extends GrantedAuthority> getAuthorities(List<UserRole> userRoleList) {
         return getGrantedAuthorities(getRoles(userRoleList));
     }
     public List<String> getRoles(List<UserRole> userRoleList) {
         List<String> roles = new ArrayList<String>();
         for(UserRole userRole:userRoleList){
             roles.add(userRole.getRole());
         }
         return roles;
     }
     public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
         List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
         for (String role : roles) {
             authorities.add(new SimpleGrantedAuthority(role));
         }
         return authorities;
     }
}
User Class
import com.codesenior.telif.local.model.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
#Service
public class CustomUserDetailsService implements UserDetailsService {
     #Autowired
     private UserService userService;
     public UserDetails loadUserByUsername(String userName)
             throws UsernameNotFoundException {
         com.codesenior.telif.local.model.User domainUser = userService.getUser(userName);
         boolean enabled = true;
         boolean accountNonExpired = true;
         boolean credentialsNonExpired = true;
         boolean accountNonLocked = true;
         return new User(
                 domainUser.getUsername(),
                 domainUser.getPassword(),
                 enabled,
                 accountNonExpired,
                 credentialsNonExpired,
                 accountNonLocked,
                 getAuthorities(domainUser.getUserRoleList())
         );
     }
     public Collection<? extends GrantedAuthority> getAuthorities(List<UserRole> userRoleList) {
         return getGrantedAuthorities(getRoles(userRoleList));
     }
     public List<String> getRoles(List<UserRole> userRoleList) {
         List<String> roles = new ArrayList<String>();
         for(UserRole userRole:userRoleList){
             roles.add(userRole.getRole());
         }
         return roles;
     }
     public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
         List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
         for (String role : roles) {
             authorities.add(new SimpleGrantedAuthority(role));
         }
         return authorities;
     }
}
UserRole Class
#Entity
public class UserRole {
#Id
#GeneratedValue
private Integer userRoleId;
private String role;
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "userRoleList")
#JsonIgnore
private List<User> userList;
public Integer getUserRoleId() {
return userRoleId;
}
public void setUserRoleId(Integer userRoleId) {
this.userRoleId= userRoleId;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role= role;
}
#Override
public String toString() {
return String.valueOf(userRoleId);
}
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList= userList;
}
}
You can use a Custom SuccessHandler extending SimpleUrlAuthenticationSuccessHandler for redirecting users to different URLs when login according to their assigned roles.
CustomSuccessHandler class provides custom redirect functionality:
package com.mycompany.uomrmsweb.configuration;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
#Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Override
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
System.out.println("Can't redirect");
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(Authentication authentication) {
String url="";
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
List<String> roles = new ArrayList<String>();
for (GrantedAuthority a : authorities) {
roles.add(a.getAuthority());
}
if (isStaff(roles)) {
url = "/staff";
} else if (isAdmin(roles)) {
url = "/admin";
} else if (isStudent(roles)) {
url = "/student";
}else if (isUser(roles)) {
url = "/home";
} else {
url="/Access_Denied";
}
return url;
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
private boolean isUser(List<String> roles) {
if (roles.contains("ROLE_USER")) {
return true;
}
return false;
}
private boolean isStudent(List<String> roles) {
if (roles.contains("ROLE_Student")) {
return true;
}
return false;
}
private boolean isAdmin(List<String> roles) {
if (roles.contains("ROLE_SystemAdmin") || roles.contains("ROLE_ExaminationsStaff")) {
return true;
}
return false;
}
private boolean isStaff(List<String> roles) {
if (roles.contains("ROLE_AcademicStaff") || roles.contains("ROLE_UniversityAdmin")) {
return true;
}
return false;
}
}
Extending Spring SimpleUrlAuthenticationSuccessHandler class and overriding handle() method which simply invokes a redirect using configured RedirectStrategy [default in this case] with the URL returned by the user defined determineTargetUrl() method. This method extracts the Roles of currently logged in user from Authentication object and then construct appropriate URL based on there roles. Finally RedirectStrategy , which is responsible for all redirections within Spring Security framework , redirects the request to specified URL.
Registering CustomSuccessHandler using SecurityConfiguration class:
package com.mycompany.uomrmsweb.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
#Qualifier("customUserDetailsService")
UserDetailsService userDetailsService;
#Autowired
CustomSuccessHandler customSuccessHandler;
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").access("hasRole('USER')")
.antMatchers("/admin/**").access("hasRole('SystemAdmin') or hasRole('ExaminationsStaff')")
.antMatchers("/staff/**").access("hasRole('AcademicStaff') or hasRole('UniversityAdmin')")
.antMatchers("/student/**").access("hasRole('Student')")
.and().formLogin().loginPage("/login").successHandler(customSuccessHandler)
.usernameParameter("username").passwordParameter("password")
.and().csrf()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
}
successHandler is the class responsible for eventual redirection based on any custom logic, which in this case will be to redirect the user [to student/admin/staff ] based on his role [USER/Student/SystemAdmin/UniversityAdmin/ExaminationsStaff/AcademicStaff].
I found Utku Özdemir's solution works to some extent, but kind of defeats the purpose of the saved request since the session attribute will take precedence over it. This means that redirects to secure pages will not work as intended - after login you will be sent to the page you were on instead of the redirect target. So as an alternative you could use a modified version of SavedRequestAwareAuthenticationSuccessHandler instead of extending it. This will allow you to have better control over when to use the session attribute.
Here is an example:
private static class MyCustomLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private RequestCache requestCache = new HttpSessionRequestCache();
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest == null) {
HttpSession session = request.getSession();
if (session != null) {
String redirectUrl = (String) session.getAttribute("url_prior_login");
if (redirectUrl != null) {
session.removeAttribute("url_prior_login");
getRedirectStrategy().sendRedirect(request, response, redirectUrl);
} else {
super.onAuthenticationSuccess(request, response, authentication);
}
} else {
super.onAuthenticationSuccess(request, response, authentication);
}
return;
}
String targetUrlParameter = getTargetUrlParameter();
if (isAlwaysUseDefaultTargetUrl()
|| (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
requestCache.removeRequest(request, response);
super.onAuthenticationSuccess(request, response, authentication);
return;
}
clearAuthenticationAttributes(request);
// Use the DefaultSavedRequest URL
String targetUrl = savedRequest.getRedirectUrl();
logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
getRedirectStrategy().sendRedirect(request, response, targetUrl);
}
}
Also, you don't want to save the referrer when authentication has failed, since the referrer will then be the login page itself. So check for the error param manually or provide a separate RequestMapping like below.
#RequestMapping(value = "/login", params = "error")
public String loginError() {
// Don't save referrer here!
}
In order to redirect to a specific page no matter what the user role is, one can simply use
defaultSucessUrl in the configuration file of Spring.
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin").hasRole("ADMIN")
.and()
.formLogin() .loginPage("/login")
.defaultSuccessUrl("/admin",true)
.loginProcessingUrl("/authenticateTheUser")
.permitAll();
The simplest solution is to add the success handler that extends SimpleUrlAuthenticationSuccessHandler as an anonymous class and calls setUseReferer(true) in its initialization block.
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
//...
.formLogin(
cfg -> cfg
.loginPage("/login")
.successHandler(new SimpleUrlAuthenticationSuccessHandler() {{
setUseReferer(true);
}})
)
.logout(cfg -> cfg.logoutSuccessHandler((request, response, authentication) ->
response.sendRedirect(request.getHeader("Referer")))
)
//...
.build();
}

Resources