I have this code in my Web Security Config:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/**")
.hasRole("ADMIN")
.and()
.httpBasic().and().csrf().disable();
}
So I added an user with "ADMIN" role in my database and I always get 403 error when I tryed loggin with this user, then I enabled log for spring and I found this line:
2015-10-18 23:13:24.112 DEBUG 4899 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /api/user/login; Attributes: [hasRole('ROLE_ADMIN')]
Why Spring Security is looking for "ROLE_ADMIN" instead "ADMIN"?
Spring security adds the prefix "ROLE_" by default.
If you want this removed or changed, take a look at
How to change role from interceptor-url?
EDIT: found this as well:
Spring Security remove RoleVoter prefix
In Spring 4, there are two methods hasAuthority() and hasAnyAuthority() defined in org.springframework.security.access.expression.SecurityExpressionRoot class. These two methods checks only your custom role name without adding ROLE_ prefix. Definition as follows:
public final boolean hasAuthority(String authority) {
return hasAnyAuthority(authority);
}
public final boolean hasAnyAuthority(String... authorities) {
return hasAnyAuthorityName(null, authorities);
}
private boolean hasAnyAuthorityName(String prefix, String... roles) {
Set<String> roleSet = getAuthoritySet();
for (String role : roles) {
String defaultedRole = getRoleWithDefaultPrefix(prefix, role);
if (roleSet.contains(defaultedRole)) {
return true;
}
}
return false;
}
private static String getRoleWithDefaultPrefix(String defaultRolePrefix, String role) {
if (role == null) {
return role;
}
if (defaultRolePrefix == null || defaultRolePrefix.length() == 0) {
return role;
}
if (role.startsWith(defaultRolePrefix)) {
return role;
}
return defaultRolePrefix + role;
}
Example usage:
<http auto-config="false" use-expressions="true" pattern="/user/**"
entry-point-ref="loginUrlAuthenticationEntryPoint">
<!--If we use hasAnyAuthority, we can remove ROLE_ prefix-->
<intercept-url pattern="/user/home/yoneticiler" access="hasAnyAuthority('FULL_ADMIN','ADMIN')"/>
<intercept-url pattern="/user/home/addUser" access="hasAnyAuthority('FULL_ADMIN','ADMIN')"/>
<intercept-url pattern="/user/home/addUserGroup" access="hasAuthority('FULL_ADMIN')"/>
<intercept-url pattern="/user/home/deleteUserGroup" access="hasAuthority('FULL_ADMIN')"/>
<intercept-url pattern="/user/home/**" access="hasAnyAuthority('FULL_ADMIN','ADMIN','EDITOR','NORMAL')"/>
<access-denied-handler error-page="/403"/>
<custom-filter position="FORM_LOGIN_FILTER" ref="customUsernamePasswordAuthenticationFilter"/>
<logout logout-url="/user/logout"
invalidate-session="true"
logout-success-url="/user/index?logout"/>
<!-- enable csrf protection -->
<csrf/>
</http> <beans:bean id="loginUrlAuthenticationEntryPoint"
class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<beans:constructor-arg value="/user"/>
</beans:bean>
As #olyanren said, you can use hasAuthority() method in Spring 4 instead of hasRole(). I am adding JavaConfig example:
#Override
protected void configure(HttpSecurity http) throws Exception {
.authorizeRequests()
.antMatchers("/api/**")
.access("hasAuthority('ADMIN')")
.and()
.httpBasic().and().csrf().disable();
}
You can create a mapper to add ROLE_ at the beginning of all of your roles:
#Bean
public GrantedAuthoritiesMapper authoritiesMapper() {
SimpleAuthorityMapper mapper = new SimpleAuthorityMapper();
mapper.setPrefix("ROLE_"); // this line is not required
mapper.setConvertToUpperCase(true); // convert your roles to uppercase
mapper.setDefaultAuthority("USER"); // set a default role
return mapper;
}
The you should add the mapper to your provider:
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
// your config ...
provider.setAuthoritiesMapper(authoritiesMapper());
return provider;
}
_ROLE prefix is used by spring security, to identify that it is as a role. A role has a set of privileges a.k.a Authorities, these authorities define varies permissions for a role.
ex:- EDIT_PROFILE, DELETE_PROFILE
You can define both the roles and authorities, if you are defining a role then it must be prefixed with "ROLE_"
In your case you are looking for a role, so by default spring security looks for a string that is prefixed with "ROLE_".
Related
I am making a Spring MVC web application. I have a login page and a dashboard page. Anyone attempting to access the dashboard JSP must be logged in:
Here's my Spring Security config:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity
#Import({SpringConfiguration.class})
public class SecurityContext extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource dataSource;
// authorizeRequests() -> use-expresions = "true"
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/createaccount","/error", "/register", "/login", "/newaccount", "/resources/**").permitAll()
.antMatchers("/**", "/*", "/").authenticated()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/dashboard")
.loginProcessingUrl("/j_spring_security_check")
.usernameParameter("username")
.passwordParameter("password")
.failureUrl("/login?error=true")
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.invalidateHttpSession(true)
.and()
.csrf();
// Upon starting the application, it prints the asdfasdf so I know the SecurityContext is loaded
System.out.println("asdfasdf");
}
// Equivalent of jdbc-user-service in XML
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery("SELECT username, password, enabled FROM Users WHERE username=?")
.authoritiesByUsernameQuery("SELECT username, authority FROM authorities where username=?");
}
}
As you can see, I have some endpoints which I permit anyone to access such as /login, /register, but all other URLs require that they be authenticated. When I start the application, if I try go to the dashboard page, I can access it just fine without needing to login which is not what I want.
My issue is that I want people attempting to reach the dashboard to be sent to the login page if they are not logged in/authenticated.
I'm trying to avoid using XML entirely and only use Java to configure my application, would anyone know what I'm doing wrong? I am almost certain it's something wrong with with my SecurityContext.
I might as well include the context XML too of which I'm trying to convert to Java config style
<security:authentication-manager>
<security:jdbc-user-service
data-source-ref="dataSource"
users-by-username-query="select username, password, enabled from Users where username=?"
authorities-by-username-query="select username, authority from Authority where username =? " />
</security:authentication-provider>
</security:authentication-manager>
<security:http use-expressions="true">
<security:intercept-url pattern="/newaccount"
access="permitAll" />
<security:intercept-url pattern="/accountcreated"
access="permitAll" />
<security:intercept-url pattern="/createaccount"
access="permitAll" />
<security:intercept-url pattern="/error"
access="permitAll" />
<security:intercept-url pattern="/resources/**"
access="permitAll" />
<security:intercept-url pattern="/login"
access="permitAll" />
<security:intercept-url pattern="/setemote"
access="isAuthenticated()" />
<security:intercept-url pattern="/**"
access="isAuthenticated()" />
<security:intercept-url pattern="/*"
access="isAuthenticated()" />
<security:form-login login-page="/login"
default-target-url="/" login-processing-url="/j_spring_security_check"
username-parameter="username" password-parameter="password"
authentication-failure-url="/login?error=true" />
<security:csrf />
</security:http>
Good day.
You have to be sure that you have SecurityWebApplicationInitializer, looking like that:
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
super(SecurityContext.class);
}
}
Where SecurityContext - is your class extending WebSecurityConfigurerAdapter.
If you already have it then the problem might be in the lack of roles.
To have roles you might want to implement the config a bit differently, something like that:
.antMatchers("/restricted_area/*")
.access("hasRole('ADMIN')")
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("username")
.passwordParameter("password")
.successHandler(authenticationSuccessHandler)
.permitAll()
.and()
.logout()
.permitAll();
For working with roles and authentication you can extend org.springframework.security.core.userdetails.UserDetailsService having a separate class that would work along with the Spring' authorization/authentication machinery checking the credentials.
As you see I also have authenticationSuccessHandler here. This is actually extended
org.springframework.security.web.authentication.AuthenticationSuccessHandler
What it does is redirecting to specific pages depending on the role: e.g. regular user to user' dashboard, admin to admin' dashboard.
Not sure if this is relevant to your question though, but the implementation is something like that:
#Component("customHandler")
public class CustomAuthenticationHandler implements AuthenticationSuccessHandler {
private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationHandler.class);
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Autowired
private UserService userService;
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
Object principal = authentication.getPrincipal();
String username = ((UserDetails) principal).getUsername();
userService.updateLastLoginTimeByName(username);
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);
}
/**
* Builds the target URL according to the logic defined in the main class
* Javadoc.
*/
protected String determineTargetUrl(Authentication authentication) {
boolean isAdmin = false;
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
isAdmin = true;
break;
}
}
if (isAdmin) {
return "/restricted_area/";
} 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;
}
}
I am new to Spring Security and I am working on a login, logout, and session timeout feature. I have configured my code by referring to this document. My code looks below:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin/**")
.access("hasRole('ROLE_USER')").and().formLogin()
.loginPage("/login").failureUrl("/login?error")
.usernameParameter("username")
.passwordParameter("password")
.and().logout().logoutSuccessUrl("/login?logout").and().csrf();
http.sessionManagement().maximumSessions(1).expiredUrl("/login?expired");
}
Override the class AbstractSecurityWebApplicationInitializer
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
#Override
public boolean enableHttpSessionEventPublisher() {
return true;
}
}
I need clarification on whether I am doing it right, if it looks good, then where I need to setup the session timeout. I am doing it fully based on annotation.
If you are using JavaConfig and do not want to use XML you can create a HttpSessionListener and use getSession().setMaxInactiveInterval(), then in the Initializer add the listener in onStartup():
public class SessionListener implements HttpSessionListener {
#Override
public void sessionCreated(HttpSessionEvent event) {
System.out.println("session created");
event.getSession().setMaxInactiveInterval(15);
}
#Override
public void sessionDestroyed(HttpSessionEvent event) {
System.out.println("session destroyed");
}
}
Then in the Initializer:
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.addListener(new SessionListener());
}
I was able to solve above issue by adding below config in web.xml only. any better way will be accepted.
<session-config>
<session-timeout>20</session-timeout>
</session-config>
When using application.properties set property server.session.timeout= value is in seconds.
Different ways to configure session timeout time(maxInactiveInterval) in spring security.
1. By addinng session config in web.xml(from raju vaishnav's answer)
2. By creating implementation of HttpSessionListener and adding it to servlet context.(from munilvc's answer)
3. By registering your custom AuthenticationSuccessHandler in spring security configuration, and setting session maximum inactive interval in onAuthenticationSuccess method.
This implementation has advantages
On login success, You can set different value of maxInactiveInterval for different roles/users.
On login success, you can set user object in session, hence user object can be accessed in any controller from session.
Disadvantage: You can not set session timeout for ANONYMOUS user(Un-authenticated user)
Create AuthenticationSuccessHandler Handler
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler
{
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException
{
Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
if (roles.contains("ROLE_ADMIN"))
{
request.getSession(false).setMaxInactiveInterval(60);
}
else
{
request.getSession(false).setMaxInactiveInterval(120);
}
//Your login success url goes here, currently login success url="/"
response.sendRedirect(request.getContextPath());
}
}
Register success handler
In Java Config way
#Override
protected void configure(final HttpSecurity http) throws Exception
{
http
.authorizeRequests()
.antMatchers("/resources/**", "/login"").permitAll()
.antMatchers("/app/admin/*").hasRole("ADMIN")
.antMatchers("/app/user/*", "/").hasAnyRole("ADMIN", "USER")
.and().exceptionHandling().accessDeniedPage("/403")
.and().formLogin()
.loginPage("/login").usernameParameter("userName")
.passwordParameter("password")
.successHandler(new MyAuthenticationSuccessHandler())
.failureUrl("/login?error=true")
.and().logout()
.logoutSuccessHandler(new CustomLogoutSuccessHandler())
.invalidateHttpSession(true)
.and().csrf().disable();
http.sessionManagement().maximumSessions(1).expiredUrl("/login?expired=true");
}
In xml config way
<http auto-config="true" use-expressions="true" create-session="ifRequired">
<csrf disabled="true"/>
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/app/admin/*" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/" access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN')" />
<intercept-url pattern="/app/user/*" access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN')" />
<access-denied-handler error-page="/403" />
<form-login
login-page="/login"
authentication-success-handler-ref="authenticationSuccessHandler"
authentication-failure-url="/login?error=true"
username-parameter="userName"
password-parameter="password" />
<logout invalidate-session="false" success-handler-ref="customLogoutSuccessHandler"/>
<session-management invalid-session-url="/login?expired=true">
<concurrency-control max-sessions="1" />
</session-management>
</http>
<beans:bean id="authenticationSuccessHandler" class="com.pvn.mvctiles.configuration.MyAuthenticationSuccessHandler" />
Working code is available in my github repository
Working code is available in two forms
1. XML config way of implementation
2. JAVA config way of implementation
If you want to have automatic logout feature and timer which displays when session is about to expire, if user is filling form but not submitted then user can extend session by clicking on keep session alive button.
If you want to implement auto logout refer stack overflow answer on auto logout on session timeout. Hope this will help.
In your application properties use
server.servlet.session.timeout=1m (If a duration suffix is not specified, seconds will be used.)
By default it is 30 minutes.
I handled it inside subclass of UsernamePasswordAuthenticationFilter
You can get username by -
obtainUsername(request);
and apply user checks and set time out accordingly, like-
if(username.equalsIgnoreCase("komal-singh-sisodiya#xyz.com"))
{
logger.debug("setting timeout 15 min");
request.getSession(false).setMaxInactiveInterval(15*60);
}
Add the below in application.proprites
server.servlet.session.timeout=
this will work:
#EnableJdbcHttpSession(maxInactiveIntervalInSeconds = 84600)
In my Spring project, I have defined my own custom authentication provider. Before bringing in Spring Security, I used BCrypt in Java code and now passwords are saved after BCrypting in Database.
spring-security.xml
<security:authentication-manager>
<security:authentication-provider ref="myAuthenticationProvider">
</security:authentication-provider>
</security:authentication-manager>
<b:bean id="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
<b:bean id="myAuthenticationProvider" class="com.cT.www.provider.CustomAuthenticationProvider">
</b:bean>
And my custom authentication provider looks as follows.
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
public CustomAuthenticationProvider() {
super();
}
#Autowired
private PersonService personService;
#Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
System.out.println(authentication.getName() + "principal" +(String) authentication.getCredentials() );
String username = authentication.getName();
String password = (String) authentication.getCredentials();
UserSignUp user = (UserSignUp) personService.loadUserByUsername(username);
if (user == null || !user.getUsername().equalsIgnoreCase(username)) {
throw new BadCredentialsException("Username not found.");
}
if (!password.equals(user.getPassword())) {
throw new BadCredentialsException("Wrong password.");
}
List<Role> authorities = user.getAuthorities();
return new UsernamePasswordAuthenticationToken(user, password, authorities);
}
#Override
public boolean supports(Class<?> arg0) {
// TODO Auto-generated method stub
return true;
}
}
I don't wanna use user-service-ref in spring-security.xml wihtin authentication-manager.
If your user passwords are already saved as BCrypt in database you don't need much of thing to do. In your authenticate method just replace your password checking condition with below
if (BCrypt.checkpw(password, user.getPassword())) {
throw new BadCredentialsException("Wrong password.");
}
Refer BCrypt source for more details.
You can refer to BCryptPasswordEncoder this way:
<authentication-manager>
<authentication-provider>
<password-encoder ref="encoder" />
</authentication-provider>
</authentication-manager>
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="11" />
</beans:bean>
For details see http://www.mkyong.com/spring-security/spring-security-password-hashing-example/
I can't log in using spring-security.
The error is (in Mozilla)
The connection was interrupted
The connection to 127.0.0.1:8180 was interrupted while the page was loading.
The site could be temporarily unavailable or too busy. Try again in a few moments.
If you are unable to load any pages, check your computer's network connection.
If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the Web.
Recently I've added a service that will get users from database. before it always was ok, but now I'm stunned. Please show me where to dig.
the url where I get this error is:
https://localhost:8180/j_spring_security_check
spring-security.xml
<http auto-config="true">
<http-basic/>
<intercept-url pattern="/sec/moderation.html" access="ROLE_MODERATOR"/>
<intercept-url pattern="/admin/*" access="ROLE_ADMIN"/>
<intercept-url pattern="/treeview" access="ROLE_ADMIN"/>
<form-login login-page="/login" default-target-url="/home" authentication-failure-url="/error"/>
<logout logout-success-url="/home"/>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="customUserDetailsService">
<password-encoder hash="plaintext"></password-encoder>
</authentication-provider>
</authentication-manager>
CustomUserDetailsService.java
#Service
#Transactional(readOnly=true)
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UserDao userDao;
#Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
UserEntity domainUser = userDao.getUser(login);
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
return new User(
domainUser.getLogin(),
domainUser.getPassword(),
enabled,
accountNonExpired,
credentialsNonExpired,
accountNonLocked,
getAuthorities(domainUser.getRole())
);
}
public Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
return authList;
}
public List<String> getRoles(Integer role) {
List<String> roles = new ArrayList<String>();
if (role.intValue() == 1) {
roles.add("ROLE_MODERATOR");
roles.add("ROLE_ADMIN");
} else if (role.intValue() == 2) {
roles.add("ROLE_MODERATOR");
}
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;
}
}
Ia there an ability to disable https for /j_spring_security_check ?
The default login page generated by spring security does not use https, so I presume you use a custom page. The requirement for https must be in the <form action="..."> element of that page.
Here is my spring security config:
<http pattern="/auth/login" security="none" />
<http pattern="/auth/loginFailed" security="none" />
<http pattern="/resources/**" security="none" />
<http auto-config="true" access-decision-manager-ref="accessDecisionManager">
<intercept-url pattern="/auth/logout" access="permitAll"/>
<intercept-url pattern="/admin/**" access="ADMINISTRATIVE_ACCESS"/>
<intercept-url pattern="/**" access="XYZ_ACCESS"/>
<form-login
login-page="/auth/login"
authentication-failure-url="/auth/loginFailed"
authentication-success-handler-ref="authenticationSuccessHandler" />
<logout logout-url="/auth/logout" logout-success-url="/auth/login" />
</http>
The authenticationSuccessHandler extends the SavedRequestAwareAuthenticationSuccessHandler ensuring that the user is redirected to the page he originally requested.
However, since /auth/login is marked as security="none", I am unable to successfully redirect the user to the homepage if he accesses the login page after being logged in. I believe this is the right user experience too.
I tried the below too but the Principal object is always null, presumably because of the security="none" attribute again.
#RequestMapping(value = "/auth/login", method = GET)
public String showLoginForm(HttpServletRequest request, Principal principal) {
if(principal != null) {
return "redirect:/";
}
return "login";
}
I've checked the topic more deeply than last time and found that you have to determine if user is authenticated by yourself in controller. Row Winch (Spring Security dev) says here:
Spring Security is not aware of the internals of your application
(i.e. if you want to make your login page flex based upon if the user
is logged in or not). To show your home page when the login page is
requested and the user is logged in use the SecurityContextHolder in
the login page (or its controller) and redirect or forward the user to
the home page.
So solution would be determining if user requesting /auth/login is anonymous or not, something like below.
applicationContext-security.xml:
<http auto-config="true" use-expressions="true"
access-decision-manager-ref="accessDecisionManager">
<intercept-url pattern="/auth/login" access="permitAll" />
<intercept-url pattern="/auth/logout" access="permitAll" />
<intercept-url pattern="/admin/**" access="ADMINISTRATIVE_ACCESS" />
<intercept-url pattern="/**" access="XYZ_ACCESS" />
<form-login login-page="/auth/login"
authentication-failure-url="/auth/loginFailed"
authentication-success-handler-ref="authenticationSuccessHandler" />
<logout logout-url="/auth/logout" logout-success-url="/auth/login" />
</http>
<beans:bean id="defaultTargetUrl" class="java.lang.String">
<beans:constructor-arg value="/content" />
</beans:bean>
<beans:bean id="authenticationTrustResolver"
class="org.springframework.security.authentication.AuthenticationTrustResolverImpl" />
<beans:bean id="authenticationSuccessHandler"
class="com.example.spring.security.MyAuthenticationSuccessHandler">
<beans:property name="defaultTargetUrl" ref="defaultTargetUrl" />
</beans:bean>
Add to applicationContext.xml bean definition:
<bean id="securityContextAccessor"
class="com.example.spring.security.SecurityContextAccessorImpl" />
which is class
public final class SecurityContextAccessorImpl
implements SecurityContextAccessor {
#Autowired
private AuthenticationTrustResolver authenticationTrustResolver;
#Override
public boolean isCurrentAuthenticationAnonymous() {
final Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
return authenticationTrustResolver.isAnonymous(authentication);
}
}
implementing simple interface
public interface SecurityContextAccessor {
boolean isCurrentAuthenticationAnonymous();
}
(SecurityContextHolder accessing code is decoupled from controller, I followed suggestion from this answer, hence SecurityContextAccessor interface.)
And last but not least redirect logic in controller:
#Controller
#RequestMapping("/auth")
public class AuthController {
#Autowired
SecurityContextAccessor securityContextAccessor;
#Autowired
#Qualifier("defaultTargetUrl")
private String defaultTargetUrl;
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
if (securityContextAccessor.isCurrentAuthenticationAnonymous()) {
return "login";
} else {
return "redirect:" + defaultTargetUrl;
}
}
}
Defining defaultTargetUrl String bean seems like a hack, but I don't have better way not to hardcode url... (Actually in our project we use <util:constant> with class containing static final String fields.) But it works after all.
You could also restrict your login page to ROLE_ANONYMOUS and set an <access-denied-handler />:
<access-denied-handler ref="accessDeniedHandler" />
<intercept-url pattern="/auth/login" access="ROLE_ANONYMOUS" />
And in your handler check if the user is already authenticated:
#Service
public class AccessDeniedHandler extends AccessDeniedHandlerImpl {
private final String HOME_PAGE = "/index.html";
#Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && !(auth instanceof AnonymousAuthenticationToken)) {
response.sendRedirect(HOME_PAGE);
}
super.handle(request, response, e);
}
}
Implement a Redirect Interceptor for this purpose:
The Interceptor (implementing HandlerInterceptor interface) check if someone try to access the login page, and if this person is already logged in, then the interceptor sends a redirect to the index page.
public class LoginPageRedirectInterceptor extends HandlerInterceptorAdapter {
private String[] loginPagePrefixes = new String[] { "/login" };
private String redirectUrl = "/index.html";
private UrlPathHelper urlPathHelper = new UrlPathHelper();
#Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
if (isInLoginPaths(this.urlPathHelper.getLookupPathForRequest(request))
&& isAuthenticated()) {
response.setContentType("text/plain");
sendRedirect(request, response);
return false;
} else {
return true;
}
}
private boolean isAuthenticated() {
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
return false;
}
if (authentication instanceof AnonymousAuthenticationToken) {
return false;
}
return authentication.isAuthenticated();
}
private void sendRedirect(HttpServletRequest request,
HttpServletResponse response) {
String encodedRedirectURL = response.encodeRedirectURL(
request.getContextPath() + this.redirectUrl);
response.setStatus(HttpStatus.SC_TEMPORARY_REDIRECT);
response.setHeader("Location", encodedRedirectURL);
}
private boolean isInLoginPaths(final String requestUrl) {
for (String login : this.loginPagePrefixes) {
if (requestUrl.startsWith(login)) {
return true;
}
}
return false;
}
}
You can keep it simple flow by access-denied-page attribute in http element or as dtrunk said to write handler for access denied as well as. the config would be like
<http access-denied-page="/403" ... >
<intercept-url pattern="/login" access="ROLE_ANONYMOUS" />
<intercept-url pattern="/user/**" access="ROLE_USER" />
<intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
<form-login login-page="/login" default-target-url="/home" ... />
...
</http>
in controller for /403
#RequestMapping(value = "/403", method = RequestMethod.GET)
public String accessDenied() { //simple impl
return "redirect:/home";
}
and for /home
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(Authentication authentication) {
// map as many home urls with Role
Map<String, String> dashBoardUrls = new HashMap<String, String>();
dashBoardUrls.put("ROLE_USER", "/user/dashboard");
dashBoardUrls.put("ROLE_ADMIN", "/admin/dashboard");
String url = null;
Collection<? extends GrantedAuthority> grants = authentication
.getAuthorities();
// for one role per user
for (GrantedAuthority grantedAuthority : grants) {
url = dashBoardUrls.get(grantedAuthority.getAuthority());
}
if (url == null)
return "/errors/default_access_denied.jsp";
return "redirect:" + url;
}
and when you make request for /admin/dashboard without logged in, it will redirect /login automatically by security
<http pattern="/login" auto-config="true" disable-url-rewriting="true">
<intercept-url pattern="/login" access="ROLE_ANONYMOUS"/>
<access-denied-handler error-page="/index.jsp"/>
</http>
You can try checking
if(SecurityContextHolder.getContext().getAuthentication() == null)
True means the user isn't authenticated, and thus can be sent to the login page. I don't know how robust/reliable this is, but it seems reasonable to try.